浏览代码

Merge remote-tracking branch 'origin/master' into build/automation

# Conflicts:
#	ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/ShaderGraph/HDPBRPass.template
#	ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/ShaderGraph/HDPBRPass.template.meta
#	ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/ShaderGraph/HDUnlitPassForward.template
#	ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/ShaderGraph/HDUnlitPassForward.template.meta
#	ScriptableRenderPipeline/HDRenderPipeline/sub-package.json
#	ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/LightweightAssetEditor.cs
#	ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/LightweightAssetEditor.cs.meta
#	ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/LightweightPipelineAssetEditor.cs
#	ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/LightweightPipelineAssetEditor.cs.meta
#	ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightShadowPass.cs.meta
#	ScriptableRenderPipeline/Ligh...
/main
Tim Cooper 7 年前
当前提交
2c4a517b
共有 208 个文件被更改,包括 3525 次插入2904 次删除
  1. 8
      TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset
  2. 16
      TestProjects/GraphicsTests/Assets/Tests/UTF_Suites_HDRP/Resources/HDRP_Deferred.asset
  3. 16
      TestProjects/GraphicsTests/Assets/Tests/UTF_Suites_HDRP/Resources/HDRP_Forward.asset
  4. 6
      com.unity.render-pipelines.core/CHANGELOG.md
  5. 12
      com.unity.render-pipelines.core/CoreRP/Debugging/DebugManager.cs
  6. 43
      com.unity.render-pipelines.core/CoreRP/Debugging/MousePositionDebug.cs
  7. 7
      com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorStyles.cs
  8. 18
      com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorUtils.cs
  9. 18
      com.unity.render-pipelines.core/CoreRP/Editor/Debugging/DebugWindow.cs
  10. 4
      com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeComponentEditor.cs
  11. 14
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/D3D11.hlsl
  12. 13
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/GLCore.hlsl
  13. 19
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/GLES2.hlsl
  14. 13
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/GLES3.hlsl
  15. 14
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/Metal.hlsl
  16. 14
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/PSSL.hlsl
  17. 14
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/Switch.hlsl
  18. 14
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/Vulkan.hlsl
  19. 14
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/XBoxOne.hlsl
  20. 15
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/CommonMaterial.hlsl
  21. 2
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/ShadowAlgorithms.hlsl
  22. 42
      com.unity.render-pipelines.core/CoreRP/Utilities/CoreUtils.cs
  23. 4
      com.unity.render-pipelines.high-definition/CHANGELOG.md
  24. 3
      com.unity.render-pipelines.high-definition/HDRP/Camera/HDCamera.cs
  25. 8
      com.unity.render-pipelines.high-definition/HDRP/Camera/HDCameraFrameHistoryType.cs
  26. 228
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.cs
  27. 45
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.cs.hlsl
  28. 2
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.hlsl
  29. 83
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugFullScreen.shader
  30. 11
      com.unity.render-pipelines.high-definition/HDRP/Debug/LightingDebug.cs
  31. 19
      com.unity.render-pipelines.high-definition/HDRP/Debug/LightingDebug.cs.hlsl
  32. 1
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightEditor.Styles.cs
  33. 15
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightEditor.cs
  34. 37
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/ScreenSpaceRefractionEditor.cs
  35. 28
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/BaseLitUI.cs
  36. 16
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/LitUI.cs
  37. 3
      com.unity.render-pipelines.high-definition/HDRP/Editor/com.unity.render-pipelines.high-definition.Editor.asmdef
  38. 66
      com.unity.render-pipelines.high-definition/HDRP/HDRenderPipeline.cs
  39. 22
      com.unity.render-pipelines.high-definition/HDRP/HDStringConstants.cs
  40. 2
      com.unity.render-pipelines.high-definition/HDRP/Lighting/GlobalIlluminationUtils.cs
  41. 6
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Light/HDAdditionalLightData.cs
  42. 4
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightDefinition.cs
  43. 12
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightDefinition.cs.hlsl
  44. 10
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightEvaluation.hlsl
  45. 23
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoop.cs
  46. 2
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/PlanarReflectionProbe.cs
  47. 2
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ProbeWrapper.cs
  48. 34
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ScreenSpaceRefraction.cs
  49. 846
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ScreenSpaceTracing.hlsl
  50. 13
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/Volumes/ProxyVolume.cs
  51. 5
      com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLit.shader
  52. 5
      com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLitData.hlsl
  53. 5
      com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLitTessellation.shader
  54. 5
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.cs
  55. 9
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.cs.hlsl
  56. 369
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.hlsl
  57. 7
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.shader
  58. 5
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitData.hlsl
  59. 5
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitProperties.hlsl
  60. 7
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitTessellation.shader
  61. 19
      com.unity.render-pipelines.high-definition/HDRP/ShaderVariables.hlsl
  62. 154
      com.unity.render-pipelines.lightweight/LWRP/Data/LightweightPipelineAsset.cs
  63. 130
      com.unity.render-pipelines.lightweight/LWRP/Editor/LightweightCameraEditor.cs
  64. 181
      com.unity.render-pipelines.lightweight/LWRP/Editor/LightweightLightEditor.cs
  65. 978
      com.unity.render-pipelines.lightweight/LWRP/LightweightPipeline.cs
  66. 156
      com.unity.render-pipelines.lightweight/LWRP/LightweightPipelineCore.cs
  67. 10
      com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Core.hlsl
  68. 64
      com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/DepthCopy.hlsl
  69. 26
      com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Shadows.hlsl
  70. 7
      com.unity.render-pipelines.lightweight/LWRP/Shaders/LightweightCopyDepth.shader
  71. 8
      com.unity.render-pipelines.lightweight/LWRP/Shaders/LightweightScreenSpaceShadows.shader
  72. 2
      com.unity.shadergraph/Editor/Data/Graphs/AbstractMaterialGraph.cs
  73. 24
      com.unity.shadergraph/Editor/Data/Graphs/MaterialSlot.cs
  74. 12
      com.unity.shadergraph/Editor/Data/Graphs/PreviewProperty.cs
  75. 2
      com.unity.shadergraph/Editor/Data/Graphs/Texture2DInputMaterialSlot.cs
  76. 6
      com.unity.shadergraph/Editor/Data/Graphs/TextureShaderProperty.cs
  77. 4
      com.unity.shadergraph/Editor/Data/Implementation/NodeUtils.cs
  78. 14
      com.unity.shadergraph/Editor/Data/Nodes/CodeFunctionNode.cs
  79. 15
      com.unity.shadergraph/Editor/Data/Nodes/Input/PropertyNode.cs
  80. 2
      com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs
  81. 4
      com.unity.shadergraph/Editor/Data/Nodes/PropertyType.cs
  82. 6
      com.unity.shadergraph/Editor/Data/Nodes/SlotValue.cs
  83. 30
      com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs
  84. 40
      com.unity.shadergraph/Editor/Data/Util/GraphContext.cs
  85. 37
      com.unity.shadergraph/Editor/Data/Util/GraphUtil.cs
  86. 28
      com.unity.shadergraph/Editor/Data/Util/PropertyCollector.cs
  87. 22
      com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardFieldPropertyView.cs
  88. 4
      com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs
  89. 4
      com.unity.shadergraph/Editor/Drawing/Controls/DefaultControl.cs
  90. 8
      com.unity.shadergraph/Editor/Drawing/MaterialGraphEditWindow.cs
  91. 4
      com.unity.shadergraph/Editor/Drawing/Views/GraphEditorView.cs
  92. 174
      com.unity.shadergraph/Editor/Drawing/Views/MaterialGraphView.cs
  93. 41
      com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs
  94. 6
      com.unity.shadergraph/Editor/Resources/Styles/PortInputView.uss
  95. 10
      com.unity.shadergraph/Editor/Resources/Styles/ShaderPort.uss
  96. 1001
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/ShaderGraph/HDPBRSubShader.cs
  97. 888
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/ShaderGraph/HDSubShaderUtilities.cs
  98. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/ShaderGraph/HDUnlitSubShader.cs

8
TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset


m_Cascade2Split: 0.25
m_Cascade4Split: {x: 0.067, y: 0.2, z: 0.467}
m_LocalShadowsSupported: 1
m_LocalShadowsAtlasResolution: 256
m_LocalShadowsAtlasResolution: 512
m_CustomShaderVariantStrippingSettings: 0
m_KeepAdditionalLightVariants: 1
m_KeepVertexLightVariants: 1
m_KeepDirectionalShadowVariants: 1
m_KeepLocalShadowVariants: 1
m_KeepSoftShadowVariants: 1
m_ResourcesAsset: {fileID: 11400000, guid: aac5a08c32552a14c89394b703f1978a, type: 2}
m_ShadowType: 0

16
TestProjects/GraphicsTests/Assets/Tests/UTF_Suites_HDRP/Resources/HDRP_Deferred.asset


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

minimumUnityVersion: 4
platforms: -1
run: 0
- name: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2204_ScreenSpaceReflectionProxyBox.unity
scene: {fileID: 102900000, guid: 371699c064b85d04ba90b577c881c643, type: 3}
scenePath: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2204_ScreenSpaceReflectionProxyBox.unity
testTypes: 2
minimumUnityVersion: 4
platforms: -1
run: 1
- name: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2206_ProbeRoughness.unity
scene: {fileID: 102900000, guid: fde2b1b0825ef5f40a0e5069afcca848, type: 3}
scenePath: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2206_ProbeRoughness.unity

run: 0
- name: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2205_ScreenSpaceReflectionProxySphere.unity
scene: {fileID: 102900000, guid: 3a4f431f1be840b45945d9ec965b621c, type: 3}
scenePath: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2205_ScreenSpaceReflectionProxySphere.unity
testTypes: 2
minimumUnityVersion: 4
platforms: -1
run: 1
- name: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2301_Shadow_Mask.unity
scene: {fileID: 102900000, guid: 1029947770f955b4290bbdd8b641f7f1, type: 3}
scenePath: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2301_Shadow_Mask.unity

16
TestProjects/GraphicsTests/Assets/Tests/UTF_Suites_HDRP/Resources/HDRP_Forward.asset


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

minimumUnityVersion: 4
platforms: -1
run: 0
- name: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2204_ScreenSpaceReflectionProxyBox.unity
scene: {fileID: 102900000, guid: 371699c064b85d04ba90b577c881c643, type: 3}
scenePath: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2204_ScreenSpaceReflectionProxyBox.unity
testTypes: 2
minimumUnityVersion: 4
platforms: -1
run: 1
- name: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2206_ProbeRoughness.unity
scene: {fileID: 102900000, guid: fde2b1b0825ef5f40a0e5069afcca848, type: 3}
scenePath: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2206_ProbeRoughness.unity

run: 0
- name: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2205_ScreenSpaceReflectionProxySphere.unity
scene: {fileID: 102900000, guid: 3a4f431f1be840b45945d9ec965b621c, type: 3}
scenePath: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2205_ScreenSpaceReflectionProxySphere.unity
testTypes: 2
minimumUnityVersion: 4
platforms: -1
run: 1
- name: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2301_Shadow_Mask.unity
scene: {fileID: 102900000, guid: 1029947770f955b4290bbdd8b641f7f1, type: 3}
scenePath: Assets/ScriptableRenderPipeline/Tests/UTF_Tests_HDRP/Scenes/2x_Lighting/2301_Shadow_Mask.unity

6
com.unity.render-pipelines.core/CHANGELOG.md


and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Improvements
- Improved volume UI & styling
- Moved root files into folders for easier maintenance
- Moved root files into folders for easier maintenance
## [0.1.6] - 2018-xx-yy

12
com.unity.render-pipelines.core/CoreRP/Debugging/DebugManager.cs


public sealed partial class DebugManager
{
#if UNITY_EDITOR
// HACK: Make debug windows work correctly with FrameSettings in Editor
public static bool renderPipelineIsRecreated = false;
#endif
static readonly DebugManager s_Instance = new DebugManager();
public static DebugManager instance { get { return s_Instance; } }

public event Action<bool> onDisplayRuntimeUIChanged = delegate { };
public event Action onSetDirty = delegate { };
public bool refreshEditorRequested;
GameObject m_Root;
DebugUIHandlerCanvas m_RootUICanvas;

{
RegisterInputs();
RegisterActions();
}
public void RefreshEditor()
{
refreshEditorRequested = true;
}
public void Reset()

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


using System;
using UnityEditor;
namespace UnityEngine.Experimental.Rendering
{

}
#if UNITY_EDITOR
[ExecuteInEditMode]
class GameViewEventCatcher : MonoBehaviour
{
public static GameViewEventCatcher s_Instance = null;
public static void Cleanup()
{
if (s_Instance != null)
DestroyImmediate(s_Instance.gameObject);
}
public static void Build()
{
Cleanup();
var go = new GameObject("__GameViewEventCatcher");
go.hideFlags = HideFlags.HideAndDontSave;
s_Instance = go.AddComponent<GameViewEventCatcher>();
}
void Update()
{
if (Input.mousePosition.x < 0
|| Input.mousePosition.y < 0
|| Input.mousePosition.x > Screen.width
|| Input.mousePosition.y > Screen.height)
return;
instance.m_mousePosition = Input.mousePosition;
instance.m_mousePosition.y = Screen.height - instance.m_mousePosition.y;
if (Input.GetMouseButton(1))
instance.m_MouseClickPosition = instance.m_mousePosition;
if (Input.GetKey(KeyCode.PageUp))
++instance.m_DebugStep;
if (Input.GetKey(KeyCode.PageDown))
instance.m_DebugStep = Mathf.Max(0, instance.m_DebugStep - 1);
if (Input.GetKey(KeyCode.End))
instance.m_MouseClickPosition = instance.m_mousePosition;
}
}
private Vector2 m_mousePosition = Vector2.zero;
Vector2 m_MouseClickPosition = Vector2.zero;
int m_DebugStep = 0;

#if UNITY_EDITOR
UnityEditor.SceneView.onSceneGUIDelegate -= OnSceneGUI;
UnityEditor.SceneView.onSceneGUIDelegate += OnSceneGUI;
GameViewEventCatcher.Build();
#endif
}

UnityEditor.SceneView.onSceneGUIDelegate -= OnSceneGUI;
GameViewEventCatcher.Cleanup();
#endif
}

7
com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorStyles.cs


public static readonly GUIStyle smallTickbox;
public static readonly GUIStyle miniLabelButton;
public static readonly Texture2D paneOptionsIconDark;
public static readonly Texture2D paneOptionsIconLight;
static readonly Texture2D paneOptionsIconDark;
static readonly Texture2D paneOptionsIconLight;
public static Texture2D paneOptionsIcon { get { return EditorGUIUtility.isProSkin ? paneOptionsIconDark : paneOptionsIconLight; } }
smallTickbox = new GUIStyle("ShurikenCheckMark");
smallTickbox = new GUIStyle("ShurikenToggle");
var transparentTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
transparentTexture.SetPixel(0, 0, Color.clear);

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


var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 16f;
labelRect.xMin += 32f;
var foldoutRect = backgroundRect;
foldoutRect.y += 1f;
foldoutRect.width = 13f;
foldoutRect.height = 13f;
toggleRect.x += 16f;
toggleRect.y += 2f;
toggleRect.width = 13f;
toggleRect.height = 13f;

using (new EditorGUI.DisabledScope(!activeField.boolValue))
EditorGUI.LabelField(labelRect, GetContent(title), EditorStyles.boldLabel);
// Foldout
group.serializedObject.Update();
group.isExpanded = GUI.Toggle(foldoutRect, group.isExpanded, GUIContent.none, EditorStyles.foldout);
group.serializedObject.ApplyModifiedProperties();
// Active checkbox
activeField.serializedObject.Update();
activeField.boolValue = GUI.Toggle(toggleRect, activeField.boolValue, GUIContent.none, CoreEditorStyles.smallTickbox);

var menuIcon = EditorGUIUtility.isProSkin
? CoreEditorStyles.paneOptionsIconDark
: CoreEditorStyles.paneOptionsIconLight;
var menuIcon = CoreEditorStyles.paneOptionsIcon;
var menuRect = new Rect(labelRect.xMax + 4f, labelRect.y + 4f, menuIcon.width, menuIcon.height);
if (contextAction != null)

18
com.unity.render-pipelines.core/CoreRP/Editor/Debugging/DebugWindow.cs


void OnEnable()
{
DebugManager.instance.refreshEditorRequested = false;
hideFlags = HideFlags.HideAndDontSave;
autoRepaintOnSceneChange = true;

EditorApplication.update -= Repaint;
var panels = DebugManager.instance.panels;
var selectedPanelIndex = m_Settings.selectedPanel;
if (selectedPanelIndex >= 0
&& selectedPanelIndex < panels.Count
if (selectedPanelIndex >= 0
&& selectedPanelIndex < panels.Count
&& panels[selectedPanelIndex].editorForceUpdate)
EditorApplication.update += Repaint;
}

void Update()
{
// HACK: Make debug windows work correctly with FrameSettings in Editor
// When we manipulate the framesettings on HDRenderPipelineAsset, the debug windows is not
// refresh, it keep the old state of the runtime framesettings in memory and thus overwrite
// our freshly edited value. To ensure debug windows is aware of framesettings change we need to
// destroy its internal widget state.
if (DebugManager.renderPipelineIsRecreated)
// If the render pipeline asset has been reloaded we force-refresh widget states in case
// some debug values need to be refresh/recreated as well (e.g. frame settings on HD)
if (DebugManager.instance.refreshEditorRequested)
DebugManager.renderPipelineIsRecreated = false;
DebugManager.instance.refreshEditorRequested = false;
// END HACK
int treeState = DebugManager.instance.GetState();

4
com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeComponentEditor.cs


{
var overrideRect = GUILayoutUtility.GetRect(17f, 17f, GUILayout.ExpandWidth(false));
overrideRect.yMin += 4f;
var oldColor = GUI.color;
GUI.color = new Color(0.6f, 0.6f, 0.6f, 0.75f);
GUI.color = oldColor;
}
}
}

14
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/D3D11.hlsl


#define TEXTURECUBE_ARRAY(textureName) TextureCubeArray textureName
#define TEXTURE3D(textureName) Texture3D textureName
#define TEXTURE2D_FLOAT(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_FLOAT(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_FLOAT(textureName) TEXTURECUBE(textureName)
#define TEXTURECUBE_ARRAY_FLOAT(textureName) TEXTURECUBE_ARRAY(textureName)
#define TEXTURE3D_FLOAT(textureName) TEXTURE3D(textureName)
#define TEXTURE2D_HALF(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_HALF(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_HALF(textureName) TEXTURECUBE(textureName)
#define TEXTURECUBE_ARRAY_HALF(textureName) TEXTURECUBE_ARRAY(textureName)
#define TEXTURE3D_HALF(textureName) TEXTURE3D(textureName)
#define TEXTURE2D_SHADOW(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_SHADOW(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_SHADOW(textureName) TEXTURECUBE(textureName)

#define SAMPLE_TEXTURECUBE_ARRAY_LOD(textureName, samplerName, coord3, index, lod) textureName.SampleLevel(samplerName, float4(coord3, index), lod)
#define SAMPLE_TEXTURECUBE_ARRAY_BIAS(textureName, samplerName, coord3, index, bias) textureName.SampleBias(samplerName, float4(coord3, index), bias)
#define SAMPLE_TEXTURE3D(textureName, samplerName, coord3) textureName.Sample(samplerName, coord3)
#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE2D_SHADOW(textureName, samplerName, coord3) textureName.SampleCmpLevelZero(samplerName, (coord3).xy, (coord3).z)
#define SAMPLE_TEXTURE2D_ARRAY_SHADOW(textureName, samplerName, coord3, index) textureName.SampleCmpLevelZero(samplerName, float3((coord3).xy, index), (coord3).z)

13
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/GLCore.hlsl


#define TEXTURECUBE_ARRAY(textureName) TextureCubeArray textureName
#define TEXTURE3D(textureName) Texture3D textureName
#define TEXTURE2D_FLOAT(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_FLOAT(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_FLOAT(textureName) TEXTURECUBE(textureName)
#define TEXTURECUBE_ARRAY_FLOAT(textureName) TEXTURECUBE_ARRAY(textureName)
#define TEXTURE3D_FLOAT(textureName) TEXTURE3D(textureName)
#define TEXTURE2D_HALF(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_HALF(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_HALF(textureName) TEXTURECUBE(textureName)
#define TEXTURECUBE_ARRAY_HALF(textureName) TEXTURECUBE_ARRAY(textureName)
#define TEXTURE3D_HALF(textureName) TEXTURE3D(textureName)
#define TEXTURE2D_SHADOW(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_SHADOW(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_SHADOW(textureName) TEXTURECUBE(textureName)

#define GATHER_TEXTURECUBE(textureName, samplerName, coord3) ERROR_ON_UNSUPPORTED_FUNCTION(GATHER_TEXTURECUBE)
#define GATHER_TEXTURECUBE_ARRAY(textureName, samplerName, coord3, index) ERROR_ON_UNSUPPORTED_FUNCTION(GATHER_TEXTURECUBE_ARRAY)
#endif

19
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/GLES2.hlsl


#define CBUFFER_START(name)
#define CBUFFER_END
// flow control attributes
#define UNITY_BRANCH
#define UNITY_FLATTEN
#define UNITY_UNROLL
#define UNITY_UNROLLX(_x)
#define UNITY_LOOP
#define uint int
#define rcp(x) 1.0 / x

#define TEXTURECUBE(textureName) samplerCUBE textureName
#define TEXTURECUBE_ARRAY(textureName) samplerCUBE textureName // No supoport to textureCubeArray and can't emulate with texture2DArray
#define TEXTURE3D(textureName) sampler3D textureName
#define TEXTURE2D_FLOAT(textureName) sampler2D_float textureName
#define TEXTURE2D_ARRAY_FLOAT(textureName) TEXTURECUBE_FLOAT(textureName) // No support to texture2DArray
#define TEXTURECUBE_FLOAT(textureName) samplerCUBE_float textureName
#define TEXTURECUBE_ARRAY_FLOAT(textureName) TEXTURECUBE_FLOAT(textureName) // No support to textureCubeArray
#define TEXTURE3D_FLOAT(textureName) sampler3D_float textureName
#define TEXTURE2D_HALF(textureName) sampler2D_half textureName
#define TEXTURE2D_ARRAY_HALF(textureName) TEXTURECUBE_HALF(textureName) // No support to texture2DArray
#define TEXTURECUBE_HALF(textureName) samplerCUBE_half textureName
#define TEXTURECUBE_ARRAY_HALF(textureName) TEXTURECUBE_HALF(textureName) // No support to textureCubeArray
#define TEXTURE3D_HALF(textureName) sampler3D_half textureName
#define TEXTURE2D_SHADOW(textureName) SHADOW2D_TEXTURE_AND_SAMPLER textureName
#define TEXTURE2D_ARRAY_SHADOW(textureName) TEXTURECUBE_SHADOW(textureName) // No support to texture array

13
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/GLES3.hlsl


#define TEXTURECUBE_ARRAY(textureName) TextureCubeArray textureName
#define TEXTURE3D(textureName) Texture3D textureName
#define TEXTURE2D_FLOAT(textureName) Texture2D_float textureName
#define TEXTURE2D_ARRAY_FLOAT(textureName) Texture2DArray textureName // no support to _float on Array, it's being added
#define TEXTURECUBE_FLOAT(textureName) TextureCube_float textureName
#define TEXTURECUBE_ARRAY_FLOAT(textureName) TextureCubeArray textureName // no support to _float on Array, it's being added
#define TEXTURE3D_FLOAT(textureName) Texture3D_float textureName
#define TEXTURE2D_HALF(textureName) Texture2D_half textureName
#define TEXTURE2D_ARRAY_HALF(textureName) Texture2DArray textureName // no support to _float on Array, it's being added
#define TEXTURECUBE_HALF(textureName) TextureCube_half textureName
#define TEXTURECUBE_ARRAY_HALF(textureName) TextureCubeArray textureName // no support to _float on Array, it's being added
#define TEXTURE3D_HALF(textureName) Texture3D_half textureName
#define TEXTURE2D_SHADOW(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_SHADOW(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_SHADOW(textureName) TEXTURECUBE(textureName)

#define GATHER_TEXTURECUBE(textureName, samplerName, coord3) ERROR_ON_UNSUPPORTED_FUNCTION(GATHER_TEXTURECUBE)
#define GATHER_TEXTURECUBE_ARRAY(textureName, samplerName, coord3, index) ERROR_ON_UNSUPPORTED_FUNCTION(GATHER_TEXTURECUBE_ARRAY)
#endif

14
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/Metal.hlsl


#define TEXTURECUBE_ARRAY(textureName) TextureCubeArray textureName
#define TEXTURE3D(textureName) Texture3D textureName
#define TEXTURE2D_FLOAT(textureName) Texture2D_float textureName
#define TEXTURE2D_ARRAY_FLOAT(textureName) Texture2DArray textureName // no support to _float on Array, it's being added
#define TEXTURECUBE_FLOAT(textureName) TextureCube_float textureName
#define TEXTURECUBE_ARRAY_FLOAT(textureName) TextureCubeArray textureName // no support to _float on Array, it's being added
#define TEXTURE3D_FLOAT(textureName) Texture3D_float textureName
#define TEXTURE2D_HALF(textureName) Texture2D_half textureName
#define TEXTURE2D_ARRAY_HALF(textureName) Texture2DArray textureName // no support to _float on Array, it's being added
#define TEXTURECUBE_HALF(textureName) TextureCube_half textureName
#define TEXTURECUBE_ARRAY_HALF(textureName) TextureCubeArray textureName // no support to _float on Array, it's being added
#define TEXTURE3D_HALF(textureName) Texture3D_half textureName
#define TEXTURE2D_SHADOW(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_SHADOW(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_SHADOW(textureName) TEXTURECUBE(textureName)

#define SAMPLE_TEXTURECUBE_ARRAY_LOD(textureName, samplerName, coord3, index, lod) textureName.SampleLevel(samplerName, float4(coord3, index), lod)
#define SAMPLE_TEXTURECUBE_ARRAY_BIAS(textureName, samplerName, coord3, index, bias) textureName.SampleBias(samplerName, float4(coord3, index), bias)
#define SAMPLE_TEXTURE3D(textureName, samplerName, coord3) textureName.Sample(samplerName, coord3)
#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE2D_SHADOW(textureName, samplerName, coord3) textureName.SampleCmpLevelZero(samplerName, (coord3).xy, (coord3).z)
#define SAMPLE_TEXTURE2D_ARRAY_SHADOW(textureName, samplerName, coord3, index) textureName.SampleCmpLevelZero(samplerName, float3((coord3).xy, index), (coord3).z)

14
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/PSSL.hlsl


#define TEXTURECUBE_ARRAY(textureName) TextureCubeArray textureName
#define TEXTURE3D(textureName) Texture3D textureName
#define TEXTURE2D_FLOAT(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_FLOAT(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_FLOAT(textureName) TEXTURECUBE(textureName)
#define TEXTURECUBE_ARRAY_FLOAT(textureName) TEXTURECUBE_ARRAY(textureName)
#define TEXTURE3D_FLOAT(textureName) TEXTURE3D(textureName)
#define TEXTURE2D_HALF(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_HALF(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_HALF(textureName) TEXTURECUBE(textureName)
#define TEXTURECUBE_ARRAY_HALF(textureName) TEXTURECUBE_ARRAY(textureName)
#define TEXTURE3D_HALF(textureName) TEXTURE3D(textureName)
#define TEXTURE2D_SHADOW(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_SHADOW(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_SHADOW(textureName) TEXTURECUBE(textureName)

#define SAMPLE_TEXTURECUBE_ARRAY_LOD(textureName, samplerName, coord3, index, lod) textureName.SampleLevel(samplerName, float4(coord3, index), lod)
#define SAMPLE_TEXTURECUBE_ARRAY_BIAS(textureName, samplerName, coord3, index, bias) textureName.SampleBias(samplerName, float4(coord3, index), bias)
#define SAMPLE_TEXTURE3D(textureName, samplerName, coord3) textureName.Sample(samplerName, coord3)
#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE2D_SHADOW(textureName, samplerName, coord3) textureName.SampleCmpLevelZero(samplerName, (coord3).xy, (coord3).z)
#define SAMPLE_TEXTURE2D_ARRAY_SHADOW(textureName, samplerName, coord3, index) textureName.SampleCmpLevelZero(samplerName, float3((coord3).xy, index), (coord3).z)

14
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/Switch.hlsl


#define TEXTURECUBE_ARRAY(textureName) TextureCubeArray textureName
#define TEXTURE3D(textureName) Texture3D textureName
#define TEXTURE2D_FLOAT(textureName) Texture2D_float textureName
#define TEXTURE2D_ARRAY_FLOAT(textureName) Texture2DArray textureName // no support to _float on Array, it's being added
#define TEXTURECUBE_FLOAT(textureName) TextureCube_float textureName
#define TEXTURECUBE_ARRAY_FLOAT(textureName) TextureCubeArray textureName // no support to _float on Array, it's being added
#define TEXTURE3D_FLOAT(textureName) Texture3D_float textureName
#define TEXTURE2D_HALF(textureName) Texture2D_half textureName
#define TEXTURE2D_ARRAY_HALF(textureName) Texture2DArray textureName // no support to _float on Array, it's being added
#define TEXTURECUBE_HALF(textureName) TextureCube_half textureName
#define TEXTURECUBE_ARRAY_HALF(textureName) TextureCubeArray textureName // no support to _float on Array, it's being added
#define TEXTURE3D_HALF(textureName) Texture3D_half textureName
#define TEXTURE2D_SHADOW(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_SHADOW(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_SHADOW(textureName) TEXTURECUBE(textureName)

#define SAMPLE_TEXTURECUBE_ARRAY_LOD(textureName, samplerName, coord3, index, lod) textureName.SampleLevel(samplerName, float4(coord3, index), lod)
#define SAMPLE_TEXTURECUBE_ARRAY_BIAS(textureName, samplerName, coord3, index, bias) textureName.SampleBias(samplerName, float4(coord3, index), bias)
#define SAMPLE_TEXTURE3D(textureName, samplerName, coord3) textureName.Sample(samplerName, coord3)
#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE2D_SHADOW(textureName, samplerName, coord3) textureName.SampleCmpLevelZero(samplerName, (coord3).xy, (coord3).z)
#define SAMPLE_TEXTURE2D_ARRAY_SHADOW(textureName, samplerName, coord3, index) textureName.SampleCmpLevelZero(samplerName, float3((coord3).xy, index), (coord3).z)

14
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/Vulkan.hlsl


#define TEXTURECUBE_ARRAY(textureName) TextureCubeArray textureName
#define TEXTURE3D(textureName) Texture3D textureName
#define TEXTURE2D_FLOAT(textureName) Texture2D_float textureName
#define TEXTURE2D_ARRAY_FLOAT(textureName) Texture2DArray textureName // no support to _float on Array, it's being added
#define TEXTURECUBE_FLOAT(textureName) TextureCube_float textureName
#define TEXTURECUBE_ARRAY_FLOAT(textureName) TextureCubeArray textureName // no support to _float on Array, it's being added
#define TEXTURE3D_FLOAT(textureName) Texture3D_float textureName
#define TEXTURE2D_HALF(textureName) Texture2D_half textureName
#define TEXTURE2D_ARRAY_HALF(textureName) Texture2DArray textureName // no support to _float on Array, it's being added
#define TEXTURECUBE_HALF(textureName) TextureCube_half textureName
#define TEXTURECUBE_ARRAY_HALF(textureName) TextureCubeArray textureName // no support to _float on Array, it's being added
#define TEXTURE3D_HALF(textureName) Texture3D_half textureName
#define TEXTURE2D_SHADOW(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_SHADOW(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_SHADOW(textureName) TEXTURECUBE(textureName)

#define SAMPLE_TEXTURECUBE_ARRAY_LOD(textureName, samplerName, coord3, index, lod) textureName.SampleLevel(samplerName, float4(coord3, index), lod)
#define SAMPLE_TEXTURECUBE_ARRAY_BIAS(textureName, samplerName, coord3, index, bias) textureName.SampleBias(samplerName, float4(coord3, index), bias)
#define SAMPLE_TEXTURE3D(textureName, samplerName, coord3) textureName.Sample(samplerName, coord3)
#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE2D_SHADOW(textureName, samplerName, coord3) textureName.SampleCmpLevelZero(samplerName, (coord3).xy, (coord3).z)
#define SAMPLE_TEXTURE2D_ARRAY_SHADOW(textureName, samplerName, coord3, index) textureName.SampleCmpLevelZero(samplerName, float3((coord3).xy, index), (coord3).z)

14
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/API/XBoxOne.hlsl


#define TEXTURECUBE_ARRAY(textureName) TextureCubeArray textureName
#define TEXTURE3D(textureName) Texture3D textureName
#define TEXTURE2D_FLOAT(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_FLOAT(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_FLOAT(textureName) TEXTURECUBE(textureName)
#define TEXTURECUBE_ARRAY_FLOAT(textureName) TEXTURECUBE_ARRAY(textureName)
#define TEXTURE3D_FLOAT(textureName) TEXTURE3D(textureName)
#define TEXTURE2D_HALF(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_HALF(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_HALF(textureName) TEXTURECUBE(textureName)
#define TEXTURECUBE_ARRAY_HALF(textureName) TEXTURECUBE_ARRAY(textureName)
#define TEXTURE3D_HALF(textureName) TEXTURE3D(textureName)
#define TEXTURE2D_SHADOW(textureName) TEXTURE2D(textureName)
#define TEXTURE2D_ARRAY_SHADOW(textureName) TEXTURE2D_ARRAY(textureName)
#define TEXTURECUBE_SHADOW(textureName) TEXTURECUBE(textureName)

#define SAMPLE_TEXTURECUBE_ARRAY_LOD(textureName, samplerName, coord3, index, lod) textureName.SampleLevel(samplerName, float4(coord3, index), lod)
#define SAMPLE_TEXTURECUBE_ARRAY_BIAS(textureName, samplerName, coord3, index, bias) textureName.SampleBias(samplerName, float4(coord3, index), bias)
#define SAMPLE_TEXTURE3D(textureName, samplerName, coord3) textureName.Sample(samplerName, coord3)
#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE2D_SHADOW(textureName, samplerName, coord3) textureName.SampleCmpLevelZero(samplerName, (coord3).xy, (coord3).z)
#define SAMPLE_TEXTURE2D_ARRAY_SHADOW(textureName, samplerName, coord3, index) textureName.SampleCmpLevelZero(samplerName, float3((coord3).xy, index), (coord3).z)

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


return sqrt(2.0 / (variance + 2.0));
}
// Reference: Error Reduction and Simplification for Shading Anti-Aliasing
// take perceptualSmoothness and return modified perceptualSmoothness
float GeometricFilterPerceptualSmoothness(float perceptualSmoothness, float3 geometricNormalWS, float screenSpaceVariance, float threshold)
{
float3 deltaU = ddx(geometricNormalWS);
float3 deltaV = ddy(geometricNormalWS);
float variance = screenSpaceVariance * (dot(deltaU, deltaU) + dot(deltaV, deltaV));
float roughness = PerceptualSmoothnessToRoughness(perceptualSmoothness);
float squaredRoughness = saturate(roughness * roughness + min(2.0 * variance, threshold * threshold)); // threshold can be really low, square the value for easier control
return 1.0 - RoughnessToPerceptualRoughness(sqrt(squaredRoughness));
}
// ----------------------------------------------------------------------------
// Helper for Disney parametrization
// ----------------------------------------------------------------------------

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


payloadOffset++;
alpha = border <= 0.0 ? 0.0 : saturate( (relDistance - (1.0 - border)) / border );
real cascDot = dot( cascadeDir, wposDir );
alpha = cascDot > 0.0 ? alpha : lerp( alpha, 0.0, saturate( -cascDot * 4.0 ) );
alpha = lerp( alpha, 0.0, saturate( -cascDot * 4.0 ) );
return shadowSplitIndex;
}

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


ClearRenderTarget(cmd, clearFlag, clearColor);
}
// Explicit load and store actions
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier buffer, RenderBufferLoadAction loadAction, RenderBufferStoreAction storeAction, ClearFlag clearFlag, Color clearColor)
{
cmd.SetRenderTarget(buffer, loadAction, storeAction);
ClearRenderTarget(cmd, clearFlag, clearColor);
}
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier buffer, RenderBufferLoadAction loadAction, RenderBufferStoreAction storeAction, ClearFlag clearFlag)
{
SetRenderTarget(cmd, buffer, loadAction, storeAction, clearFlag, clearColorAllBlack);
}
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier colorBuffer, RenderBufferLoadAction colorLoadAction, RenderBufferStoreAction colorStoreAction,
RenderTargetIdentifier depthBuffer, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction,
ClearFlag clearFlag, Color clearColor)
{
cmd.SetRenderTarget(colorBuffer, colorLoadAction, colorStoreAction, depthBuffer, depthLoadAction, depthStoreAction);
ClearRenderTarget(cmd, clearFlag, clearColor);
}
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier colorBuffer, RenderBufferLoadAction colorLoadAction, RenderBufferStoreAction colorStoreAction,
RenderTargetIdentifier depthBuffer, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction,
ClearFlag clearFlag)
{
SetRenderTarget(cmd, colorBuffer, colorLoadAction, colorStoreAction, depthBuffer, depthLoadAction, depthStoreAction, clearFlag, clearColorAllBlack);
}
public static string GetRenderTargetAutoName(int width, int height, int depth, RenderTextureFormat format, string name, bool mips = false, bool enableMSAA = false, MSAASamples msaaSamples = MSAASamples.None)
{
string result = string.Format("{0}_{1}x{2}", name, width, height);

// Unity specifics
public static Material CreateEngineMaterial(string shaderPath)
{
var mat = new Material(Shader.Find(shaderPath))
Shader shader = Shader.Find(shaderPath);
if (shader == null)
{
Debug.LogError("Cannot create required material because shader " + shaderPath + " could not be found");
return null;
}
var mat = new Material(shader)
{
hideFlags = HideFlags.HideAndDontSave
};

public static Material CreateEngineMaterial(Shader shader)
{
if (shader == null)
{
Debug.LogError("Cannot create required material because shader is null");
return null;
}
var mat = new Material(shader)
{
hideFlags = HideFlags.HideAndDontSave

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


- Add stripper of shader variant when building a player. Save shader compile time.
- Disable per-object culling that was executed in C++ in HD whereas it was not used (Optimization)
- Enable texture streaming debugging (was not working before 2018.2)
- Added Screen Space Reflection with Proxy Projection Model
- Add per light shadow mask mode control (i.e shadow mask distance and shadow mask). It use the option NonLightmappedOnly
- Add geometric filtering to Lit shader (allow to reduce specular aliasing)
### Changed, Removals and deprecations
- Removed GlobalLightLoopSettings.maxPlanarReflectionProbes and instead use value of GlobalLightLoopSettings.planarReflectionProbeCacheSize

- Fix issue with shadow mask framesettings not correctly taken into account when shadow mask is enabled for lighting.
- Fix directional light and shadow mask transition, they are now matching making smooth transition
- Fix banding issues caused by high intensity volumetric lighting
- Fix the debug window being emptied on SRP asset reload
## [2018.1.0f2]

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


}
// Set up UnityPerView CBuffer.
public void SetupGlobalParams(CommandBuffer cmd, float time, float lastTime)
public void SetupGlobalParams(CommandBuffer cmd, float time, float lastTime, uint frameCount)
{
cmd.SetGlobalMatrix(HDShaderIDs._ViewMatrix, viewMatrix);
cmd.SetGlobalMatrix(HDShaderIDs._InvViewMatrix, viewMatrix.inverse);

cmd.SetGlobalVector(HDShaderIDs.unity_DeltaTime, new Vector4(dt, 1.0f / dt, sdt, 1.0f / sdt));
cmd.SetGlobalVector(HDShaderIDs._SinTime, new Vector4(Mathf.Sin(ct * 0.125f), Mathf.Sin(ct * 0.25f), Mathf.Sin(ct * 0.5f), Mathf.Sin(ct)));
cmd.SetGlobalVector(HDShaderIDs._CosTime, new Vector4(Mathf.Cos(ct * 0.125f), Mathf.Cos(ct * 0.25f), Mathf.Cos(ct * 0.5f), Mathf.Cos(ct)));
cmd.SetGlobalInt(HDShaderIDs._FrameCount, (int)frameCount);
}
public void SetupGlobalStereoParams(CommandBuffer cmd)

8
com.unity.render-pipelines.high-definition/HDRP/Camera/HDCameraFrameHistoryType.cs


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

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


[GenerateHLSL]
public struct ScreenSpaceTracingDebug
{
// Used to debug SSRay model
// Used to debug SSRay model
public Lit.RefractionSSRayModel tracingModel;
public Lit.ProjectionModel tracingModel;
public uint loopStartPositionSSX; // Proxy, HiZ
public uint loopStartPositionSSY; // Proxy, HiZ
public float loopStartLinearDepth; // Proxy, HiZ
public Vector3 loopRayDirectionSS; // HiZ
public uint loopStartPositionSSX; // Proxy, HiZ, Linear
public uint loopStartPositionSSY; // Proxy, HiZ, Linear
public float loopStartLinearDepth; // Proxy, HiZ, Linear
public Vector3 loopRayDirectionSS; // HiZ, Linear
public uint loopIterationMax; // HiZ
public uint loopIterationMax; // HiZ, Linear
// 9x32 bits
public Vector3 iterationPositionSS; // HiZ
public uint iterationMipLevel; // HiZ
public uint iteration; // HiZ
public float iterationLinearDepthBuffer; // HiZ
// 11x32 bits
public Vector3 iterationPositionSS; // HiZ, Linear
public uint iterationMipLevel; // HiZ, Linear
public uint iteration; // HiZ, Linear
public float iterationLinearDepthBufferMin; // HiZ, Linear
public float iterationLinearDepthBufferMax; // HiZ, Linear
public float iterationLinearDepthBufferMinThickness; // HiZ, Linear
public uint iterationCellSizeW; // HiZ
public uint iterationCellSizeH; // HiZ
public uint iterationCellSizeW; // HiZ, Linear
public uint iterationCellSizeH; // HiZ, Linear
// 4x32 bits
public bool endHitSuccess; // Proxy, HiZ
public float endLinearDepth; // Proxy, HiZ
public uint endPositionSSX; // Proxy, HiZ
public uint endPositionSSY; // Proxy, HiZ
// 5x32 bits
public int endHitSuccess; // Proxy, HiZ, Linear
public float endLinearDepth; // Proxy, HiZ, Linear
public uint endPositionSSX; // Proxy, HiZ, Linear
public uint endPositionSSY; // Proxy, HiZ, Linear
public float endHitWeight; // HiZ, Linear
// 0x32 bits (padding)
// 7x32 Lighting
public Vector3 lightingSampledColor; // All
public Vector3 lightingSpecularFGD; // All
public float lightingWeight; // All
// 2x32 bits (padding)
public Vector2 padding;
public bool intersectDepthBuffer { get { return (1.0f / iterationPositionSS.z) >= iterationLinearDepthBufferMin && (1.0f / iterationPositionSS.z) <= iterationLinearDepthBufferMinThickness; } }
}
public class DebugDisplaySettings

public static string k_PanelScreenSpaceTracing = "Screen Space Tracing";
public static string k_PanelDecals = "Decals";
//static readonly string[] k_HiZIntersectionKind = { "None", "Depth", "Cell" };
static readonly string[] k_HiZIntersectionKind = { "None", "Cell", "Depth" };
DebugUI.Widget[] m_DebugDisplayStatsItems;
DebugUI.Widget[] m_DebugMaterialItems;

public float debugOverlayRatio = 0.33f;
public FullScreenDebugMode fullScreenDebugMode = FullScreenDebugMode.None;
public float fullscreenDebugMip = 0.0f;
public bool showSSRayGrid = true;
public bool showSSRayDepthPyramid = true;
public bool showSSRayGrid = false;
public bool showSSRayDepthPyramid = false;
public bool showSSSampledColor = false;
public MaterialDebugSettings materialDebugSettings = new MaterialDebugSettings();
public LightingDebugSettings lightingDebugSettings = new LightingDebugSettings();

public static int[] debugScreenSpaceTracingProxyValues = null;
public static GUIContent[] debugScreenSpaceTracingHiZStrings = null;
public static int[] debugScreenSpaceTracingHiZValues = null;
public static GUIContent[] debugScreenSpaceTracingLinearStrings = null;
public static int[] debugScreenSpaceTracingLinearValues = null;
public static GUIContent[] debuggedAlgorithmStrings = null;
public static int[] debuggedAlgorithmValues = null;
Lit.RefractionSSRayModel m_LastSSRayModel = Lit.RefractionSSRayModel.None;
Lit.ProjectionModel m_LastProjectionModel = Lit.ProjectionModel.None;
ScreenSpaceTracingDebug m_ScreenSpaceTracingDebugData;
public ScreenSpaceTracingDebug screenSpaceTracingDebugData
{

m_ScreenSpaceTracingDebugData = value;
if (m_LastSSRayModel != m_ScreenSpaceTracingDebugData.tracingModel)
m_ScreenSpaceTracingDebugData = value;
if (m_LastProjectionModel != m_ScreenSpaceTracingDebugData.tracingModel)
m_LastSSRayModel = m_ScreenSpaceTracingDebugData.tracingModel;
RefreshScreenSpaceTracingDebug<Lit.RefractionSSRayModel>(null, m_LastSSRayModel);
m_LastProjectionModel = m_ScreenSpaceTracingDebugData.tracingModel;
RefreshScreenSpaceTracingDebug<Lit.ProjectionModel>(null, m_LastProjectionModel);
if (m_ScreenSpaceTracingDebugData.tracingModel != Lit.RefractionSSRayModel.HiZ)
if (m_ScreenSpaceTracingDebugData.tracingModel == Lit.ProjectionModel.Proxy)
{
showSSRayDepthPyramid = false;
showSSRayGrid = false;

var debugScreenSpaceTracingHiZStringsList = new List<GUIContent>();
var debugScreenSpaceTracingProxyStringsList = new List<GUIContent>();
var debugScreenSpaceTracingLinearStringsList = new List<GUIContent>();
var debugScreenSpaceTracingLinearValueList = new List<int>();
if (!g.text.StartsWith("Proxy"))
if (!g.text.StartsWith("Proxy") && !g.text.StartsWith("Linear"))
if (!g.text.StartsWith("HiZ"))
if (!g.text.StartsWith("HiZ") && !g.text.StartsWith("Linear"))
if (!g.text.StartsWith("Proxy") && !g.text.StartsWith("HiZ"))
{
debugScreenSpaceTracingLinearStringsList.Add(g);
debugScreenSpaceTracingLinearValueList.Add(v);
}
}
debugScreenSpaceTracingHiZStrings = debugScreenSpaceTracingHiZStringsList.ToArray();

debugScreenSpaceTracingLinearStrings = debugScreenSpaceTracingLinearStringsList.ToArray();
debugScreenSpaceTracingLinearValues = debugScreenSpaceTracingLinearValueList.ToArray();
debuggedAlgorithmStrings = Enum.GetNames(typeof(Lit.ProjectionModel))
.Select(t => new GUIContent(t))
.ToArray();
debuggedAlgorithmValues = (int[])Enum.GetValues(typeof(Lit.ProjectionModel));
}
public int GetDebugMaterialIndex()

}
}
void SetScreenSpaceTracingRefractionDebugMode(int value)
bool IsScreenSpaceTracingReflectionDebugEnabled()
{
return fullScreenDebugMode == FullScreenDebugMode.ScreenSpaceTracing
&& lightingDebugSettings.debugLightingMode == DebugLightingMode.ScreenSpaceTracingReflection;
}
void SetScreenSpaceTracingReflectionDebugEnabled(bool value)
{
if (value)
{
lightingDebugSettings.debugLightingMode = DebugLightingMode.ScreenSpaceTracingReflection;
fullScreenDebugMode = FullScreenDebugMode.ScreenSpaceTracing;
}
else
{
lightingDebugSettings.debugLightingMode = DebugLightingMode.None;
fullScreenDebugMode = FullScreenDebugMode.None;
}
}
void SetScreenSpaceTracingDebugMode(int value)
lightingDebugSettings.debugLightingMode = DebugLightingMode.ScreenSpaceTracingRefraction;
lightingDebugSettings.debugScreenSpaceTracingMode = (DebugScreenSpaceTracing)value;
}
else

{
var list = new List<DebugUI.Container>();
var refractionContainer = new DebugUI.Container
var settingsContainer = new DebugUI.Container
displayName = "Refraction",
children =
displayName = "Refraction / Reflection",
children =
new DebugUI.BoolField { displayName = "Debug Enabled", getter = IsScreenSpaceTracingRefractionDebugEnabled, setter = SetScreenSpaceTracingRefractionDebugEnabled, onValueChanged = RefreshScreenSpaceTracingDebug },
new DebugUI.BoolField { displayName = "Debug Refraction Enabled", getter = IsScreenSpaceTracingRefractionDebugEnabled, setter = SetScreenSpaceTracingRefractionDebugEnabled, onValueChanged = RefreshScreenSpaceTracingDebug },
new DebugUI.BoolField { displayName = "Debug Reflection Enabled", getter = IsScreenSpaceTracingReflectionDebugEnabled, setter = SetScreenSpaceTracingReflectionDebugEnabled, onValueChanged = RefreshScreenSpaceTracingDebug },
list.Add(refractionContainer);
list.Add(settingsContainer);
if (IsScreenSpaceTracingRefractionDebugEnabled())
if (IsScreenSpaceTracingRefractionDebugEnabled()
|| IsScreenSpaceTracingReflectionDebugEnabled())
var debuggedAlgorithmCBName = string.Format("_SS{0}DebuggedAlgorithm", IsScreenSpaceTracingRefractionDebugEnabled() ? "Refraction" : "Reflection");
var debugSettingsContainer = new DebugUI.Container
{
displayName = "Debug Settings",

new DebugUI.Value { displayName = "SSRay Model", getter = () => screenSpaceTracingDebugData.tracingModel }
new DebugUI.Value { displayName = string.Empty, getter = () => "Warning: In forward only mode, debugging information may not be representative of the rendered pixel." },
new DebugUI.Value { displayName = "SSRay Model", getter = () => screenSpaceTracingDebugData.tracingModel },
new DebugUI.EnumField { displayName = "Debugged Algorithm", getter = () => Shader.GetGlobalInt(debuggedAlgorithmCBName), setter = v => Shader.SetGlobalInt(debuggedAlgorithmCBName, v), enumValues = debuggedAlgorithmValues, enumNames = debuggedAlgorithmStrings },
}
};
settingsContainer.children.Add(debugSettingsContainer);
var lightingDebug = new DebugUI.Container
{
displayName = "Lighting",
children =
{
new DebugUI.Value { displayName = "Sampled Color", getter = () => FormatVector(screenSpaceTracingDebugData.lightingSampledColor) },
new DebugUI.Value { displayName = "Specular FGD", getter = () => FormatVector(screenSpaceTracingDebugData.lightingSpecularFGD) },
new DebugUI.Value { displayName = "Weight", getter = () => screenSpaceTracingDebugData.lightingWeight.ToString("F6") },
new DebugUI.Value { displayName = "Weighted Color", getter = () => FormatVector(Vector3.Scale(screenSpaceTracingDebugData.lightingSpecularFGD, screenSpaceTracingDebugData.lightingSampledColor) * screenSpaceTracingDebugData.lightingWeight) },
refractionContainer.children.Add(debugSettingsContainer);
case Lit.RefractionSSRayModel.Proxy:
case Lit.ProjectionModel.Proxy:
new DebugUI.EnumField { displayName = "Debug Mode", getter = GetDebugLightingSubMode, setter = SetScreenSpaceTracingRefractionDebugMode, enumNames = debugScreenSpaceTracingProxyStrings, enumValues = debugScreenSpaceTracingProxyValues, onValueChanged = RefreshScreenSpaceTracingDebug }
new DebugUI.EnumField { displayName = "Debug Mode", getter = GetDebugLightingSubMode, setter = SetScreenSpaceTracingDebugMode, enumNames = debugScreenSpaceTracingProxyStrings, enumValues = debugScreenSpaceTracingProxyValues, onValueChanged = RefreshScreenSpaceTracingDebug }
refractionContainer.children.Add(
settingsContainer.children.Add(
new DebugUI.Value { displayName = "Hit Success", getter = () => screenSpaceTracingDebugData.endHitSuccess },
new DebugUI.Value { displayName = "Hit Success", getter = () => screenSpaceTracingDebugData.endHitSuccess != 0 },
new DebugUI.Value { displayName = "Proxy Shape", getter = () => screenSpaceTracingDebugData.proxyShapeType },
new DebugUI.Value { displayName = "Projection Distance", getter = () => screenSpaceTracingDebugData.projectionDistance },
new DebugUI.Value { displayName = "Start Position", getter = () => screenSpaceTracingDebugData.loopStartPositionSS },

}
}
},
lightingDebug
case Lit.RefractionSSRayModel.HiZ:
case Lit.ProjectionModel.HiZ:
new DebugUI.EnumField { displayName = "Debug Mode", getter = GetDebugLightingSubMode, setter = SetScreenSpaceTracingRefractionDebugMode, enumNames = debugScreenSpaceTracingHiZStrings, enumValues = debugScreenSpaceTracingHiZValues, onValueChanged = RefreshScreenSpaceTracingDebug },
new DebugUI.EnumField { displayName = "Debug Mode", getter = GetDebugLightingSubMode, setter = SetScreenSpaceTracingDebugMode, enumNames = debugScreenSpaceTracingHiZStrings, enumValues = debugScreenSpaceTracingHiZValues, onValueChanged = RefreshScreenSpaceTracingDebug },
new DebugUI.BoolField { displayName = "Display Grid", getter = () => showSSRayGrid, setter = v => showSSRayGrid = v },
new DebugUI.BoolField { displayName = "Display Depth", getter = () => showSSRayDepthPyramid, setter = v => showSSRayDepthPyramid = v },
new DebugUI.BoolField { displayName = "Display Sampled Color", getter = () => showSSSampledColor, setter = v => showSSSampledColor = v }
);
settingsContainer.children.Add(
new DebugUI.Container
{
displayName = "Debug Values (loop)",
children =
{
new DebugUI.Value { displayName = "Hit Success", getter = () => screenSpaceTracingDebugData.endHitSuccess != 0 },
new DebugUI.Value { displayName = "Start Position", getter = () => screenSpaceTracingDebugData.loopStartPositionSS },
new DebugUI.Value { displayName = "Start Linear Depth", getter = () => screenSpaceTracingDebugData.loopStartLinearDepth },
new DebugUI.Value { displayName = "Ray Direction SS", getter = () => new Vector2(screenSpaceTracingDebugData.loopRayDirectionSS.x, screenSpaceTracingDebugData.loopRayDirectionSS.y) },
new DebugUI.Value { displayName = "Ray Depth", getter = () => 1f / screenSpaceTracingDebugData.loopRayDirectionSS.z },
new DebugUI.Value { displayName = "End Position", getter = () => screenSpaceTracingDebugData.endPositionSS },
new DebugUI.Value { displayName = "End Linear Depth", getter = () => screenSpaceTracingDebugData.endLinearDepth },
new DebugUI.Value { displayName = "Hit Weight", getter = () => screenSpaceTracingDebugData.endHitWeight.ToString("F4") },
}
},
new DebugUI.Container
{
displayName = "Debug Values (iteration)",
children =
{
new DebugUI.Value { displayName = "Iteration", getter = () => string.Format("{0}/{1}", screenSpaceTracingDebugData.iteration, screenSpaceTracingDebugData.loopIterationMax) },
new DebugUI.Value { displayName = "Position SS", getter = () => new Vector2(screenSpaceTracingDebugData.iterationPositionSS.x, screenSpaceTracingDebugData.iterationPositionSS.y) },
new DebugUI.Value { displayName = "Depth", getter = () => 1f / screenSpaceTracingDebugData.iterationPositionSS.z },
new DebugUI.Value { displayName = "Depth Buffer Min/Min + Thickness/Max", getter = () => string.Format("{0}/{1}/{2}", screenSpaceTracingDebugData.iterationLinearDepthBufferMin, screenSpaceTracingDebugData.iterationLinearDepthBufferMinThickness, screenSpaceTracingDebugData.iterationLinearDepthBufferMax) },
new DebugUI.Value { displayName = "Intersection Thickness", getter = () => (screenSpaceTracingDebugData.iterationLinearDepthBufferMinThickness - 1f / screenSpaceTracingDebugData.iterationPositionSS.z).ToString("F6") },
new DebugUI.Value { displayName = "Depth Buffer Diff (Max - Min)", getter = () => (screenSpaceTracingDebugData.iterationLinearDepthBufferMax - screenSpaceTracingDebugData.iterationLinearDepthBufferMin).ToString("F6") },
new DebugUI.Value { displayName = "Intersect Depth Buffer", getter = () => screenSpaceTracingDebugData.intersectDepthBuffer },
new DebugUI.Value { displayName = "Mip Level", getter = () => screenSpaceTracingDebugData.iterationMipLevel },
new DebugUI.Value { displayName = "Cell Id", getter = () => screenSpaceTracingDebugData.iterationCellId },
new DebugUI.Value { displayName = "Cell Size", getter = () => screenSpaceTracingDebugData.iterationCellSize },
new DebugUI.Value { displayName = "Intersection Kind", getter = () => k_HiZIntersectionKind[(int)screenSpaceTracingDebugData.iterationIntersectionKind] },
}
},
lightingDebug
);
break;
}
case Lit.ProjectionModel.Linear:
{
debugSettingsContainer.children.Add(
new DebugUI.EnumField { displayName = "Debug Mode", getter = GetDebugLightingSubMode, setter = SetScreenSpaceTracingDebugMode, enumNames = debugScreenSpaceTracingLinearStrings, enumValues = debugScreenSpaceTracingLinearValues, onValueChanged = RefreshScreenSpaceTracingDebug },
refractionContainer.children.Add(
settingsContainer.children.Add(
new DebugUI.Value { displayName = "Hit Success", getter = () => screenSpaceTracingDebugData.endHitSuccess },
new DebugUI.Value { displayName = "Hit Success", getter = () => screenSpaceTracingDebugData.endHitSuccess != 0 },
new DebugUI.Value { displayName = "Start Position", getter = () => screenSpaceTracingDebugData.loopStartPositionSS },
new DebugUI.Value { displayName = "Start Linear Depth", getter = () => screenSpaceTracingDebugData.loopStartLinearDepth },
new DebugUI.Value { displayName = "Ray Direction SS", getter = () => new Vector2(screenSpaceTracingDebugData.loopRayDirectionSS.x, screenSpaceTracingDebugData.loopRayDirectionSS.y) },

new DebugUI.Value { displayName = "Hit Weight", getter = () => screenSpaceTracingDebugData.endHitWeight.ToString("F4") },
}
},
new DebugUI.Container

new DebugUI.Value { displayName = "Iteration", getter = () => string.Format("{0}/{1}", screenSpaceTracingDebugData.iteration, screenSpaceTracingDebugData.loopIterationMax) },
new DebugUI.Value { displayName = "Position SS", getter = () => new Vector2(screenSpaceTracingDebugData.iterationPositionSS.x, screenSpaceTracingDebugData.iterationPositionSS.y) },
new DebugUI.Value { displayName = "Depth", getter = () => 1f / screenSpaceTracingDebugData.iterationPositionSS.z },
new DebugUI.Value { displayName = "Depth Buffer", getter = () => screenSpaceTracingDebugData.iterationLinearDepthBuffer },
new DebugUI.Value { displayName = "Mip Level", getter = () => string.Format("{0}/{1}", screenSpaceTracingDebugData.iterationMipLevel, screenSpaceTracingDebugData.loopMipLevelMax) },
new DebugUI.Value { displayName = "Intersection kind", getter = () => screenSpaceTracingDebugData.iterationIntersectionKind },
new DebugUI.Value { displayName = "Intersection Thickness", getter = () => (screenSpaceTracingDebugData.iterationLinearDepthBufferMinThickness - 1f / screenSpaceTracingDebugData.iterationPositionSS.z).ToString("F6") },
new DebugUI.Value { displayName = "Depth Buffer Min/Min + Thickness/Max", getter = () => string.Format("{0}/{1}/{2}", screenSpaceTracingDebugData.iterationLinearDepthBufferMin, screenSpaceTracingDebugData.iterationLinearDepthBufferMinThickness, screenSpaceTracingDebugData.iterationLinearDepthBufferMax) },
new DebugUI.Value { displayName = "Intersect Depth Buffer", getter = () => screenSpaceTracingDebugData.intersectDepthBuffer },
new DebugUI.Value { displayName = "Mip Level", getter = () => screenSpaceTracingDebugData.iterationMipLevel },
}
},
lightingDebug
);
break;
}

values[index] = i;
index++;
}
}
static string FormatVector(Vector3 v)
{
return string.Format("({0:F6}, {1:F6}, {2:F6})", v.x, v.y, v.z);
}
}
}

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


float3 iterationPositionSS;
uint iterationMipLevel;
uint iteration;
float iterationLinearDepthBuffer;
float iterationLinearDepthBufferMin;
float iterationLinearDepthBufferMax;
float iterationLinearDepthBufferMinThickness;
bool endHitSuccess;
int endHitSuccess;
float endHitWeight;
float3 lightingSampledColor;
float3 lightingSpecularFGD;
float lightingWeight;
float2 padding;
};
//

{
return value.iteration;
}
float GetIterationLinearDepthBuffer(ScreenSpaceTracingDebug value)
float GetIterationLinearDepthBufferMin(ScreenSpaceTracingDebug value)
return value.iterationLinearDepthBuffer;
return value.iterationLinearDepthBufferMin;
}
float GetIterationLinearDepthBufferMax(ScreenSpaceTracingDebug value)
{
return value.iterationLinearDepthBufferMax;
}
float GetIterationLinearDepthBufferMinThickness(ScreenSpaceTracingDebug value)
{
return value.iterationLinearDepthBufferMinThickness;
}
int GetIterationIntersectionKind(ScreenSpaceTracingDebug value)
{

{
return value.projectionDistance;
}
bool GetEndHitSuccess(ScreenSpaceTracingDebug value)
int GetEndHitSuccess(ScreenSpaceTracingDebug value)
{
return value.endHitSuccess;
}

uint GetEndPositionSSY(ScreenSpaceTracingDebug value)
{
return value.endPositionSSY;
}
float GetEndHitWeight(ScreenSpaceTracingDebug value)
{
return value.endHitWeight;
}
float3 GetLightingSampledColor(ScreenSpaceTracingDebug value)
{
return value.lightingSampledColor;
}
float3 GetLightingSpecularFGD(ScreenSpaceTracingDebug value)
{
return value.lightingSpecularFGD;
}
float GetLightingWeight(ScreenSpaceTracingDebug value)
{
return value.lightingWeight;
}
float2 GetPadding(ScreenSpaceTracingDebug value)
{
return value.padding;
}

2
com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.hlsl


CBUFFER_END
TEXTURE2D(_DebugFont); // Debug font to write string in shader
RWStructuredBuffer<ScreenSpaceTracingDebug> _DebugScreenSpaceTracingData;
RWStructuredBuffer<ScreenSpaceTracingDebug> _DebugScreenSpaceTracingData : register(u7); // TODO: Change the register number for PS4
void GetPropertiesDataDebug(uint paramId, inout float3 result, inout bool needLinearToSRGB)
{

83
com.unity.render-pipelines.high-definition/HDRP/Debug/DebugFullScreen.shader


float _RequireToFlipInputTexture;
float _ShowGrid;
float _ShowDepthPyramidDebug;
float _ShowSSRaySampledColor;
CBUFFER_END
TEXTURE2D(_DebugFullScreenTexture);

float dist1 = abs(dot(rel_p, float2(dir.y, -dir.x)));
float dist2 = abs(dot(rel_p, dir)) - 0.5 * len;
return max(dist1, dist2);
}
void ColorWidget(
int2 positionSS,
float4 rect,
float3 borderColor,
float3 innerColor,
inout float4 debugColor,
inout float4 backgroundColor
)
{
const float4 distToRects = float4(rect.zw - positionSS, positionSS - rect.xy);
if (all(distToRects > 0))
{
const float distToRect = min(min(distToRects.x, distToRects.y), min(distToRects.z, distToRects.w));
const float sdf = clamp(distToRect * 0.5, 0, 1);
debugColor = float4(
lerp(borderColor, innerColor, sdf),
1.0
);
backgroundColor.a = 0;
}
}
float DrawArrow(float2 texcoord, float body, float head, float height, float linewidth, float antialias)

ScreenSpaceTracingDebug debug = _DebugScreenSpaceTracingData[0];
// Fetch Depth Buffer and Position Inputs
const float deviceDepth = LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, int2(input.positionCS.xy) >> debug.iterationMipLevel, debug.iterationMipLevel).r;
PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, deviceDepth, UNITY_MATRIX_I_VP, UNITY_MATRIX_VP);
const float2 deviceDepth = LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, int2(input.positionCS.xy) >> debug.iterationMipLevel, debug.iterationMipLevel).rg;
PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, deviceDepth.r, UNITY_MATRIX_I_VP, UNITY_MATRIX_VP);
const uint2 loopStartPositionSS = uint2(debug.loopStartPositionSSX, debug.loopStartPositionSSY);
const uint2 endPositionSS = uint2(debug.endPositionSSX, debug.endPositionSSY);
uint2 loopStartPositionSS = uint2(debug.loopStartPositionSSX, debug.loopStartPositionSSY);
uint2 endPositionSS = uint2(debug.endPositionSSX, debug.endPositionSSY);
float3 iterationPositionSS = debug.iterationPositionSS;
if (_RequireToFlipInputTexture > 0)
{
loopStartPositionSS.y = uint(_ScreenSize.y) - loopStartPositionSS.y;
endPositionSS.y = uint(_ScreenSize.y) - endPositionSS.y;
iterationPositionSS.y = _ScreenSize.y - iterationPositionSS.y;
}
float distanceToPosition = FLT_MAX;
float positionSDF = 0;

const float raySegmentSDF = clamp(1 - distanceToRaySegment, 0, 1);
float cellSDF = 0;
float debugLinearDepth = 0;
if (debug.tracingModel == REFRACTIONSSRAYMODEL_HI_Z)
float2 debugLinearDepth = float2(LinearEyeDepth(deviceDepth.r, _ZBufferParams), LinearEyeDepth(deviceDepth.g, _ZBufferParams));
if (debug.tracingModel == PROJECTIONMODEL_HI_Z
|| debug.tracingModel == PROJECTIONMODEL_LINEAR)
distanceToPosition = length(int2(posInput.positionSS) - int2(debug.iterationPositionSS.xy));
distanceToPosition = length(int2(posInput.positionSS) - int2(iterationPositionSS.xy));
positionSDF = clamp(circleRadius - distanceToPosition, 0, 1);
// Grid rendering

cellSDF = max(distanceToCell.x, distanceToCell.y) * _ShowGrid;
debugLinearDepth = posInput.linearDepth;
}
col = float4(

const float w = clamp(1 - startPositionRingSDF - positionRingSDF, 0, 1);
col.rgb = col.rgb * w + float3(1, 1, 1) * (1 - w);
// Draw color widgets
if (_ShowSSRaySampledColor == 1)
{
// Sampled color
ColorWidget(
posInput.positionSS,
float4(10, 10, 50, 50) + endPositionSS.xyxy,
float3(1, 0, 0), debug.lightingSampledColor,
col,
color
);
// Specular FGD
ColorWidget(
posInput.positionSS,
float4(-50, 10, -10, 50) + endPositionSS.xyxy,
float3(0, 1, 0), debug.lightingSpecularFGD,
col,
color
);
// Weighted
ColorWidget(
posInput.positionSS,
float4(-50, -50, -10, -10) + endPositionSS.xyxy,
float3(0, 0, 1), debug.lightingSampledColor * debug.lightingSpecularFGD * debug.lightingWeight,
col,
color
);
}
color.rgb = frac(float3(debugLinearDepth, debugLinearDepth, debugLinearDepth) * 0.1);
color.rgb = float3(frac(debugLinearDepth * 0.1), 0.0);
col = float4(col.rgb * col.a + color.rgb, 1);
col = float4(col.rgb * col.a + color.rgb * color.a, 1);
return col;
}

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


RayDirWS,
HitDepth,
HitSuccess,
TracingModel,
HiZIntersectionKind
HiZIntersectionKind,
HiZHitWeight,
HiZSampledColor,
HiZDiff,
LinearPositionNDC,
LinearRayDirNDC,
LinearIterationCount,
LinearHitWeight,
LinearSampledColor
}
public enum ShadowMapDebugMode

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


#define DEBUGSCREENSPACETRACING_RAY_DIR_WS (2)
#define DEBUGSCREENSPACETRACING_HIT_DEPTH (3)
#define DEBUGSCREENSPACETRACING_HIT_SUCCESS (4)
#define DEBUGSCREENSPACETRACING_HI_ZPOSITION_NDC (5)
#define DEBUGSCREENSPACETRACING_HI_ZRAY_DIR_NDC (6)
#define DEBUGSCREENSPACETRACING_HI_ZITERATION_COUNT (7)
#define DEBUGSCREENSPACETRACING_HI_ZMAX_USED_MIP_LEVEL (8)
#define DEBUGSCREENSPACETRACING_HI_ZINTERSECTION_KIND (9)
#define DEBUGSCREENSPACETRACING_TRACING_MODEL (5)
#define DEBUGSCREENSPACETRACING_HI_ZPOSITION_NDC (6)
#define DEBUGSCREENSPACETRACING_HI_ZRAY_DIR_NDC (7)
#define DEBUGSCREENSPACETRACING_HI_ZITERATION_COUNT (8)
#define DEBUGSCREENSPACETRACING_HI_ZMAX_USED_MIP_LEVEL (9)
#define DEBUGSCREENSPACETRACING_HI_ZINTERSECTION_KIND (10)
#define DEBUGSCREENSPACETRACING_HI_ZHIT_WEIGHT (11)
#define DEBUGSCREENSPACETRACING_HI_ZSAMPLED_COLOR (12)
#define DEBUGSCREENSPACETRACING_HI_ZDIFF (13)
#define DEBUGSCREENSPACETRACING_LINEAR_POSITION_NDC (14)
#define DEBUGSCREENSPACETRACING_LINEAR_RAY_DIR_NDC (15)
#define DEBUGSCREENSPACETRACING_LINEAR_ITERATION_COUNT (16)
#define DEBUGSCREENSPACETRACING_LINEAR_HIT_WEIGHT (17)
#define DEBUGSCREENSPACETRACING_LINEAR_SAMPLED_COLOR (18)
#endif

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


public readonly GUIContent maxSmoothness = new GUIContent("Max Smoothness", "Very low cost way of faking spherical area lighting. This will modify the roughness of the material lit. This is useful when the specular highlight is too small or too sharp.");
public readonly GUIContent affectDiffuse = new GUIContent("Affect Diffuse", "This will disable diffuse lighting for this light. Doesn't save performance, diffuse lighting is still computed.");
public readonly GUIContent affectSpecular = new GUIContent("Affect Specular", "This will disable specular lighting for this light. Doesn't save performance, specular lighting is still computed.");
public readonly GUIContent nonLightmappedOnly = new GUIContent("Non Lightmapped Only", "This will disable the rendering of lightmapped object for shadow map. Only effective with shadow mask feature");
public readonly GUIContent lightDimmer = new GUIContent("Dimmer", "Aim to be used with script, timeline or animation. It allows dimming one or multiple lights of heterogeneous intensity easily (without needing to know the intensity of each light).");
public readonly GUIContent volumetricDimmer = new GUIContent("Volumetric Dimmer", "Allows to reduce the intensity of the scattered volumetric lighting.");
public readonly GUIContent fadeDistance = new GUIContent("Fade Distance", "The distance at which the light will smoothly fade before being culled to minimize popping.");

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


public SerializedProperty fadeDistance;
public SerializedProperty affectDiffuse;
public SerializedProperty affectSpecular;
public SerializedProperty nonLightmappedOnly;
public SerializedProperty lightTypeExtent;
public SerializedProperty spotLightShape;
public SerializedProperty shapeWidth;

fadeDistance = o.Find(x => x.fadeDistance),
affectDiffuse = o.Find(x => x.affectDiffuse),
affectSpecular = o.Find(x => x.affectSpecular),
nonLightmappedOnly = o.Find(x => x.nonLightmappedOnly),
lightTypeExtent = o.Find(x => x.lightTypeExtent),
spotLightShape = o.Find(x => x.spotLightShape),
shapeWidth = o.Find(x => x.shapeWidth),

case LightType.Point:
EditorGUILayout.PropertyField(settings.bakedShadowRadiusProp, s_Styles.bakedShadowRadius);
break;
}
if (settings.isMixed)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AdditionalLightData.nonLightmappedOnly, s_Styles.nonLightmappedOnly);
if (EditorGUI.EndChangeCheck())
{
((Light)target).lightShadowCasterMode = m_AdditionalLightData.nonLightmappedOnly.boolValue ? LightShadowCasterMode.NonLightmappedOnly : LightShadowCasterMode.Everything;
}
}
}

37
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/ScreenSpaceRefractionEditor.cs


using System.Collections;
using UnityEngine;
using UnityEditor;
using UnityEditor.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEngine.Experimental.Rendering.HDPipeline
namespace UnityEditor.Experimental.Rendering.HDPipeline
public class ScreenSpaceRefractionEditor : VolumeComponentEditor
public class ScreenSpaceRefractionEditor : ScreenSpaceLightingEditor
SerializedDataParameter m_RayMinLevel;
SerializedDataParameter m_RayMaxLevel;
SerializedDataParameter m_RayMaxIterations;
SerializedDataParameter m_RayDepthSuccessBias;
SerializedDataParameter m_ScreenWeightDistance;
public override void OnEnable()
{
var o = new PropertyFetcher<ScreenSpaceRefraction>(serializedObject);
m_RayMinLevel = Unpack(o.Find(x => x.rayMinLevel));
m_RayMaxLevel = Unpack(o.Find(x => x.rayMaxLevel));
m_RayMaxIterations = Unpack(o.Find(x => x.rayMaxIterations));
m_RayDepthSuccessBias = Unpack(o.Find(x => x.rayDepthSuccessBias));
m_ScreenWeightDistance = Unpack(o.Find(x => x.screenWeightDistance));
}
public override void OnInspectorGUI()
{
EditorGUILayout.LabelField(CoreEditorUtils.GetContent("HiZ Settings"));
PropertyField(m_RayMinLevel, CoreEditorUtils.GetContent("Ray Min Level"));
PropertyField(m_RayMaxLevel, CoreEditorUtils.GetContent("Ray Max Level"));
PropertyField(m_RayMaxIterations, CoreEditorUtils.GetContent("Ray Max Iterations"));
PropertyField(m_RayDepthSuccessBias, CoreEditorUtils.GetContent("Ray Depth Success Bias"));
EditorGUILayout.Separator();
EditorGUILayout.LabelField(CoreEditorUtils.GetContent("Common Settings"));
PropertyField(m_ScreenWeightDistance, CoreEditorUtils.GetContent("Screen Weight Distance"));
}
}
}

28
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/BaseLitUI.cs


public static GUIContent windShiverDirectionalityText = new GUIContent("Shiver Directionality");
public static GUIContent supportDBufferText = new GUIContent("Enable Decal", "Allow to specify if the material can receive decal or not");
public static GUIContent enableGeometricSpecularAAText = new GUIContent("Enable geometric specular AA", "This reduce specular aliasing on highly dense mesh (Particularly useful when they don't use normal map)");
public static GUIContent specularAAScreenSpaceVarianceText = new GUIContent("Screen space variance", "Allow to control the strength of the specular AA reduction. Higher mean more blurry result and less aliasing");
public static GUIContent specularAAThresholdText = new GUIContent("Threshold", "Allow to limit the effect of specular AA reduction. 0 mean don't apply reduction, higher value mean allow higher reduction");
}
public enum DoubleSidedNormalMode

// Decal
protected MaterialProperty supportDBuffer = null;
protected const string kSupportDBuffer = "_SupportDBuffer";
protected MaterialProperty enableGeometricSpecularAA = null;
protected const string kEnableGeometricSpecularAA = "_EnableGeometricSpecularAA";
protected MaterialProperty specularAAScreenSpaceVariance = null;
protected const string kSpecularAAScreenSpaceVariance = "_SpecularAAScreenSpaceVariance";
protected MaterialProperty specularAAThreshold = null;
protected const string kSpecularAAThreshold = "_SpecularAAThreshold";
protected override void FindBaseMaterialProperties(MaterialProperty[] props)
{

// Decal
supportDBuffer = FindProperty(kSupportDBuffer, props);
// specular AA
enableGeometricSpecularAA = FindProperty(kEnableGeometricSpecularAA, props, false);
specularAAScreenSpaceVariance = FindProperty(kSpecularAAScreenSpaceVariance, props, false);
specularAAThreshold = FindProperty(kSpecularAAThreshold, props, false);
}
void TessellationModePopup()

}
m_MaterialEditor.ShaderProperty(supportDBuffer, StylesBaseLit.supportDBufferText);
m_MaterialEditor.ShaderProperty(enableGeometricSpecularAA, StylesBaseLit.enableGeometricSpecularAAText);
if (enableGeometricSpecularAA.floatValue > 0.0)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(specularAAScreenSpaceVariance, StylesBaseLit.specularAAScreenSpaceVarianceText);
m_MaterialEditor.ShaderProperty(specularAAThreshold, StylesBaseLit.specularAAThresholdText);
EditorGUI.indentLevel--;
}
m_MaterialEditor.ShaderProperty(enableMotionVectorForVertexAnimation, StylesBaseUnlit.enableMotionVectorForVertexAnimationText);

// Use negation so we don't create keyword by default
CoreUtils.SetKeyword(material, "_DISABLE_DBUFFER", material.GetFloat(kSupportDBuffer) == 0.0);
CoreUtils.SetKeyword(material, "_ENABLE_GEOMETRIC_SPECULAR_AA", material.GetFloat(kEnableGeometricSpecularAA) == 1.0);
}
static public void SetupBaseLitMaterialPass(Material material)

16
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/LitUI.cs


// Transparency
public static string refractionModelText = "Refraction Model";
public static GUIContent refractionSSRayModelText = new GUIContent("SSRay Model", "Screen Space Ray Model");
public static GUIContent refractionProjectionModelText = new GUIContent("SSRay Model", "Screen Space Ray Model");
public static GUIContent refractionIorText = new GUIContent("Index of refraction", "Index of refraction");
public static GUIContent refractionThicknessText = new GUIContent("Refraction Thickness", "Thickness for rough refraction");
public static GUIContent refractionThicknessMultiplierText = new GUIContent("Refraction Thickness multiplier (m)", "Thickness multiplier");

protected const string kThicknessMultiplier = "_ThicknessMultiplier";
protected MaterialProperty refractionModel = null;
protected const string kRefractionModel = "_RefractionModel";
protected MaterialProperty refractionSSRayModel = null;
protected const string kRefractionSSRayModel = "_RefractionSSRayModel";
protected MaterialProperty ssrefractionProjectionModel = null;
protected const string kSSRefractionProjectionModel = "_SSRefractionProjectionModel";
protected override bool showBlendModePopup
{

// Transparency
refractionModel = FindProperty(kRefractionModel, props, false);
refractionSSRayModel = FindProperty(kRefractionSSRayModel, props, false);
ssrefractionProjectionModel = FindProperty(kSSRefractionProjectionModel, props, false);
transmittanceColor = FindProperty(kTransmittanceColor, props, false);
transmittanceColorMap = FindProperty(kTransmittanceColorMap, props, false);
atDistance = FindProperty(kATDistance, props, false);

var mode = (Lit.RefractionModel)refractionModel.floatValue;
if (mode != Lit.RefractionModel.None)
{
m_MaterialEditor.ShaderProperty(refractionSSRayModel, Styles.refractionSSRayModelText);
m_MaterialEditor.ShaderProperty(ssrefractionProjectionModel, Styles.refractionProjectionModelText);
m_MaterialEditor.ShaderProperty(ior, Styles.refractionIorText);
blendMode.floatValue = (float)BlendMode.Alpha;

CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SPECULAR_COLOR", materialId == BaseLitGUI.MaterialId.LitSpecular);
var refractionModelValue = (Lit.RefractionModel)material.GetFloat(kRefractionModel);
var refractionSSRayModelValue = (Lit.RefractionSSRayModel)material.GetFloat(kRefractionSSRayModel);
var refractionProjectionModelValue = (Lit.ProjectionModel)material.GetFloat(kSSRefractionProjectionModel);
CoreUtils.SetKeyword(material, "_REFRACTION_SSRAY_PROXY", (refractionSSRayModelValue == Lit.RefractionSSRayModel.Proxy) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_REFRACTION_SSRAY_HIZ", (refractionSSRayModelValue == Lit.RefractionSSRayModel.HiZ) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_REFRACTION_SSRAY_PROXY", (refractionProjectionModelValue == Lit.ProjectionModel.Proxy) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_REFRACTION_SSRAY_HIZ", (refractionProjectionModelValue == Lit.ProjectionModel.HiZ) && canHaveRefraction);
}
}
} // namespace UnityEditor

3
com.unity.render-pipelines.high-definition/HDRP/Editor/com.unity.render-pipelines.high-definition.Editor.asmdef


"com.unity.render-pipelines.core.Editor",
"com.unity.render-pipelines.high-definition.Runtime",
"com.unity.postprocessing.Runtime",
"com.unity.postprocessing.Editor"
"com.unity.postprocessing.Editor",
"Unity.ShaderGraph.Editor"
],
"optionalUnityReferences": [],
"includePlatforms": [

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


RTHandleSystem.RTHandle m_DebugFullScreenTempBuffer;
bool m_FullScreenDebugPushed;
bool m_ValidAPI; // False by default mean we render normally, true mean we don't render anything
bool m_IsCameraRendering; // Use to avoid nested rendering of camera
public Material GetBlitMaterial() { return m_Blit; }

public HDRenderPipeline(HDRenderPipelineAsset asset)
{
#if UNITY_EDITOR
// HACK: Make debug windows work correctly with FrameSettings in Editor
DebugManager.renderPipelineIsRecreated = true;
#endif
DebugManager.instance.RefreshEditor();
m_IsCameraRendering = false;
if (!SetRenderingFeatures())
{

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

var ssRefraction = VolumeManager.instance.stack.GetComponent<ScreenSpaceRefraction>()
?? ScreenSpaceRefraction.@default;
ssRefraction.PushShaderParameters(cmd);
var ssReflection = VolumeManager.instance.stack.GetComponent<ScreenSpaceReflection>()
?? ScreenSpaceReflection.@default;
ssReflection.PushShaderParameters(cmd);
hdCamera.SetupGlobalParams(cmd, m_Time, m_LastTime);
hdCamera.SetupGlobalParams(cmd, m_Time, m_LastTime, m_FrameCount);
cmd.SetGlobalInt(HDShaderIDs._SSReflectionEnabled, hdCamera.frameSettings.enableSSR ? 1 : 0);
var previousDepthPyramidRT = hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.DepthPyramid);
if (previousDepthPyramidRT != null)

0.0f
));
}
else
{
cmd.SetGlobalTexture(HDShaderIDs._DepthPyramidTexture, Texture2D.blackTexture);
cmd.SetGlobalVector(HDShaderIDs._DepthPyramidSize, Vector4.one);
cmd.SetGlobalVector(HDShaderIDs._DepthPyramidScale, Vector4.one);
}
var previousColorPyramidRT = hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.ColorPyramid);
if (previousColorPyramidRT != null)

Mathf.Log(Mathf.Min(previousColorPyramidRT.rt.width, previousColorPyramidRT.rt.height), 2),
0.0f
));
}
else
{
cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, Texture2D.blackTexture);
cmd.SetGlobalVector(HDShaderIDs._ColorPyramidSize, Vector4.one);
cmd.SetGlobalVector(HDShaderIDs._ColorPyramidScale, Vector4.one);
}
}
}

if (!m_ValidAPI)
return;
if (m_IsCameraRendering)
{
Debug.LogWarning("Nested camera rendering is forbidden. If you are calling camera.Render inside OnWillRenderObject callback, use BeginCameraRender callback instead.");
return;
}
base.Render(renderContext, cameras);
RenderPipeline.BeginFrameRendering(cameras);

continue;
RenderPipeline.BeginCameraRendering(camera);
m_IsCameraRendering = true;
// First, get aggregate of frame settings base on global settings, camera frame settings and debug settings
// Note: the SceneView camera will never have additionalCameraData

// 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);
RenderCameraVelocity(m_CullResults, hdCamera, renderContext, cmd);

// Caution: We require sun light here as some skies use the sun light to render, it means that UpdateSkyEnvironment must be called after PrepareLightsForGPU.
// TODO: Try to arrange code so we can trigger this call earlier and use async compute here to run sky convolution during other passes (once we move convolution shader to compute).
UpdateSkyEnvironment(hdCamera, cmd);
RenderDepthPyramid(hdCamera, cmd, renderContext, FullScreenDebugMode.DepthPyramid);
StopStereoRendering(renderContext, hdCamera);

// Overwrite camera properties set during the shadow pass with the original camera properties.
renderContext.SetupCameraProperties(camera, hdCamera.frameSettings.enableStereo);
hdCamera.SetupGlobalParams(cmd, m_Time, m_LastTime);
hdCamera.SetupGlobalParams(cmd, m_Time, m_LastTime, m_FrameCount);
if (hdCamera.frameSettings.enableStereo)
hdCamera.SetupGlobalStereoParams(cmd);
}

// Assign -1 in tracing model to notifiy we took the data.
// When debugging in forward, we want only the first time the pixel is drawn
data.tracingModel = (Lit.RefractionSSRayModel)(-1);
data.tracingModel = (Lit.ProjectionModel)(-1);
m_IsCameraRendering = false;
} // For each camera
}

// Output split lighting for materials asking for it (masked in the stencil buffer)
options.outputSplitLighting = true;
m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, m_MRTCache2, m_CameraDepthStencilBuffer, depthTexture, options);
m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, m_MRTCache2, m_CameraDepthStencilBuffer, depthTexture, options, m_DebugScreenSpaceTracingData);
m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, m_MRTCache2, m_CameraDepthStencilBuffer, depthTexture, options);
m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, m_MRTCache2, m_CameraDepthStencilBuffer, depthTexture, options, m_DebugScreenSpaceTracingData);
}
void UpdateSkyEnvironment(HDCamera hdCamera, CommandBuffer cmd)

HDUtils.SetRenderTarget(cmd, hdCamera, m_VelocityBuffer, m_CameraDepthStencilBuffer);
RenderOpaqueRenderList(cullResults, hdCamera, renderContext, cmd, HDShaderPassNames.s_MotionVectorsName, RendererConfiguration.PerObjectMotionVectors);
cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, m_VelocityBuffer);
cmd.SetGlobalVector(HDShaderIDs._CameraMotionVectorsSize, new Vector4(
m_VelocityBuffer.referenceSize.x,
m_VelocityBuffer.referenceSize.y,
1f / m_VelocityBuffer.referenceSize.x,
1f / m_VelocityBuffer.referenceSize.y
));
cmd.SetGlobalVector(HDShaderIDs._CameraMotionVectorsScale, new Vector4(
m_VelocityBuffer.referenceSize.x / (float)m_VelocityBuffer.rt.width,
m_VelocityBuffer.referenceSize.y / (float)m_VelocityBuffer.rt.height,
1, 0.0f
));
}
}

// If the flag hasn't been set yet on this camera, motion vectors will skip a frame.
hdCamera.camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth;
HDUtils.DrawFullScreen(cmd, hdCamera, m_CameraMotionVectorsMaterial, m_VelocityBuffer, m_CameraDepthStencilBuffer, null, 0);
PushFullScreenDebugTexture(hdCamera, cmd, m_VelocityBuffer, FullScreenDebugMode.MotionVectors);
}
}

cmd.SetGlobalInt(HDShaderIDs._DebugStep, HDUtils.debugStep);
cmd.SetGlobalInt(HDShaderIDs._ShowGrid, m_CurrentDebugDisplaySettings.showSSRayGrid ? 1 : 0);
cmd.SetGlobalInt(HDShaderIDs._ShowDepthPyramidDebug, m_CurrentDebugDisplaySettings.showSSRayDepthPyramid ? 1 : 0);
cmd.SetGlobalInt(HDShaderIDs._ShowSSRaySampledColor, m_CurrentDebugDisplaySettings.showSSSampledColor ? 1 : 0);
// The DebugNeedsExposure test allows us to set a neutral value if exposure is not needed. This way we don't need to make various tests inside shaders but only in this function.
cmd.SetGlobalFloat(HDShaderIDs._DebugExposure, m_CurrentDebugDisplaySettings.DebugNeedsExposure() ? lightingDebugSettings.debugExposure : 0.0f);

// (i.e. we have perform a flip, we need to flip the input texture)
m_DebugFullScreen.SetFloat(HDShaderIDs._RequireToFlipInputTexture, hdCamera.camera.cameraType != CameraType.SceneView ? 1.0f : 0.0f);
m_DebugFullScreen.SetBuffer(HDShaderIDs._DebugScreenSpaceTracingData, m_DebugScreenSpaceTracingData);
m_DebugFullScreen.SetTexture(HDShaderIDs._DepthPyramidTexture, hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.DepthPyramid));
m_DebugFullScreen.SetTexture(HDShaderIDs._DepthPyramidTexture, hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.DepthPyramid));
HDUtils.DrawFullScreen(cmd, hdCamera, m_DebugFullScreen, (RenderTargetIdentifier)BuiltinRenderTextureType.CameraTarget);
PushColorPickerDebugTexture(hdCamera, cmd, (RenderTargetIdentifier)BuiltinRenderTextureType.CameraTarget);

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


public static readonly int _DebugExposure = Shader.PropertyToID("_DebugExposure");
public static readonly int _DebugScreenSpaceTracingData = Shader.PropertyToID("_DebugScreenSpaceTracingData");
public static readonly int _ShowGrid = Shader.PropertyToID("_ShowGrid");
public static readonly int _ShowSSRaySampledColor = Shader.PropertyToID("_ShowSSRaySampledColor");
public static readonly int _ShowDepthPyramidDebug = Shader.PropertyToID("_ShowDepthPyramidDebug");
public static readonly int _DebugViewMaterial = Shader.PropertyToID("_DebugViewMaterial");

public static readonly int _UseTileLightList = Shader.PropertyToID("_UseTileLightList");
public static readonly int _FrameCount = Shader.PropertyToID("_FrameCount");
public static readonly int _Time = Shader.PropertyToID("_Time");
public static readonly int _LastTime = Shader.PropertyToID("_LastTime");
public static readonly int _SinTime = Shader.PropertyToID("_SinTime");

Shader.PropertyToID("_SSSBufferTexture3"),
};
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 _SSRefractionRayLevel = Shader.PropertyToID("_SSRefractionRayLevel");
public static readonly int _SSRefractionRayDepthSuccessBias = Shader.PropertyToID("_SSRefractionRayDepthSuccessBias");
public static readonly int _SSRefractionDepthBufferThickness = Shader.PropertyToID("_SSRefractionDepthBufferThickness");
public static readonly int _SSReflectionRayMarchBehindObjects = Shader.PropertyToID("_SSReflectionRayMarchBehindObjects");
public static readonly int _SSReflectionRayMaxScreenDistance = Shader.PropertyToID("_SSReflectionRayMaxScreenDistance");
public static readonly int _SSReflectionRayBlendScreenDistance = Shader.PropertyToID("_SSReflectionRayBlendScreenDistance");
public static readonly int _SSReflectionRayLevel = Shader.PropertyToID("_SSReflectionRayLevel");
public static readonly int _SSReflectionRayMinLevel = Shader.PropertyToID("_SSReflectionRayMinLevel");
public static readonly int _SSReflectionRayMaxLevel = Shader.PropertyToID("_SSReflectionRayMaxLevel");
public static readonly int _SSReflectionRayMaxIterations = Shader.PropertyToID("_SSReflectionRayMaxIterations");
public static readonly int _SSReflectionDepthBufferThickness = Shader.PropertyToID("_SSReflectionDepthBufferThickness");
public static readonly int _SSReflectionInvScreenWeightDistance = Shader.PropertyToID("_SSReflectionInvScreenWeightDistance");
public static readonly int _SSReflectionProjectionModel = Shader.PropertyToID("_SSReflectionProjectionModel");
public static readonly int _SSReflectionEnabled = Shader.PropertyToID("_SSReflectionEnabled");
public static readonly int _VelocityTexture = Shader.PropertyToID("_VelocityTexture");
public static readonly int _ShadowMaskTexture = Shader.PropertyToID("_ShadowMaskTexture");

public static readonly int _CameraDepthTexture = Shader.PropertyToID("_CameraDepthTexture");
public static readonly int _CameraMotionVectorsTexture = Shader.PropertyToID("_CameraMotionVectorsTexture");
public static readonly int _CameraMotionVectorsSize = Shader.PropertyToID("_CameraMotionVectorsSize");
public static readonly int _CameraMotionVectorsScale = Shader.PropertyToID("_CameraMotionVectorsScale");
public static readonly int _FullScreenDebugMode = Shader.PropertyToID("_FullScreenDebugMode");
public static readonly int _InputCubemap = Shader.PropertyToID("_InputCubemap");

2
com.unity.render-pipelines.high-definition/HDRP/Lighting/GlobalIlluminationUtils.cs


// Note that the HDRI is correctly integrated in the GlobalIllumination system, we don't need to do anything regarding it.
#if UNITY_EDITOR
#endif
ld.shadow = (byte)(l.shadows != LightShadows.None ? 1 : 0);

6
com.unity.render-pipelines.high-definition/HDRP/Lighting/Light/HDAdditionalLightData.cs


public bool affectDiffuse = true;
public bool affectSpecular = true;
// This property work only with shadow mask and allow to say we don't render any lightMapped object in the shadow map
public bool nonLightmappedOnly = false;
public LightTypeExtent lightTypeExtent = LightTypeExtent.Punctual;
// Only for Spotlight, should be hide for other light

light.lightmapBakeType = LightmapBakeType.Realtime;
#endif
}
// We don't use the global settings of shadow mask by default
light.lightShadowCasterMode = LightShadowCasterMode.Everything;
// At first init we need to initialize correctly the default value
lightData.ConvertPhysicalLightIntensityToLightIntensity();

4
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightDefinition.cs


public float diffuseScale;
public float volumetricDimmer;
public int dynamicShadowCasterOnly; // Use with ShadowMask feature // TODO: make it a bool
public int nonLightmappedOnly; // Use with ShadowMask feature // TODO: make it a bool
public Vector4 shadowMaskSelector; // Use with ShadowMask feature
};

public float angleScale; // Spot light
public float angleOffset; // Spot light
public float shadowDimmer;
public int dynamicShadowCasterOnly; // Use with ShadowMask feature // TODO: make it a bool
public int nonLightmappedOnly; // Use with ShadowMask feature // TODO: make it a bool
public Vector4 shadowMaskSelector; // Use with ShadowMask feature

12
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightDefinition.cs.hlsl


float3 up;
float diffuseScale;
float volumetricDimmer;
int dynamicShadowCasterOnly;
int nonLightmappedOnly;
float4 shadowMaskSelector;
};

float angleScale;
float angleOffset;
float shadowDimmer;
int dynamicShadowCasterOnly;
int nonLightmappedOnly;
float4 shadowMaskSelector;
float2 size;
int lightType;

{
return value.volumetricDimmer;
}
int GetDynamicShadowCasterOnly(DirectionalLightData value)
int GetNonLightmappedOnly(DirectionalLightData value)
return value.dynamicShadowCasterOnly;
return value.nonLightmappedOnly;
}
float4 GetShadowMaskSelector(DirectionalLightData value)
{

{
return value.shadowDimmer;
}
int GetDynamicShadowCasterOnly(LightData value)
int GetNonLightmappedOnly(LightData value)
return value.dynamicShadowCasterOnly;
return value.nonLightmappedOnly;
}
float4 GetShadowMaskSelector(LightData value)
{

10
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightEvaluation.hlsl


int cascadeCount;
int shadowSplitIndex = EvalShadow_GetSplitIndex(lightLoopContext.shadowContext, lightData.shadowIndex, positionWS, payloadOffset, fade, cascadeCount);
// we have a fade caclulation for each cascade but we must lerp with shadow mask only for the last one
fade = ((shadowSplitIndex + 1) == cascadeCount || shadowSplitIndex == -1.0) ? fade : 0.0;
// if shadowSplitIndex is -1 it mean we are outside cascade and should return 1.0 to use shadowmask: saturate(-shadowSplitIndex) return 0 for >= 0 and 1 for -1
fade = ((shadowSplitIndex + 1) == cascadeCount) ? fade : saturate(-shadowSplitIndex);
// See comment in EvaluateBSDF_Punctual
shadow = lightData.dynamicShadowCasterOnly ? min(shadowMask, shadow) : shadow;
// See comment in EvaluateBSDF_Punctual
shadow = lightData.nonLightmappedOnly ? min(shadowMask, shadow) : shadow;
// Note: There is no shadowDimmer when there is no shadow mask
#endif

// The min handle the case of having only dynamic objects in the ShadowMap
// The second case for blend with distance is handled with ShadowDimmer. ShadowDimmer is define manually and by shadowDistance by light.
// With distance, ShadowDimmer become one and only the ShadowMask appear, we get the blend with distance behavior.
shadow = lightData.dynamicShadowCasterOnly ? min(shadowMask, shadow) : shadow;
shadow = lightData.nonLightmappedOnly ? min(shadowMask, shadow) : shadow;
shadow = lerp(shadowMask, shadow, lightData.shadowDimmer);
#else
shadow = lerp(1.0, shadow, lightData.shadowDimmer);

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


if (IsBakedShadowMaskLight(light.light))
{
directionalLightData.shadowMaskSelector[light.light.bakingOutput.occlusionMaskChannel] = 1.0f;
// TODO: make this option per light, not global
directionalLightData.dynamicShadowCasterOnly = QualitySettings.shadowmaskMode == ShadowmaskMode.Shadowmask ? 1 : 0;
directionalLightData.nonLightmappedOnly = light.light.lightShadowCasterMode == LightShadowCasterMode.NonLightmappedOnly ? 1 : 0;
directionalLightData.dynamicShadowCasterOnly = 0;
directionalLightData.nonLightmappedOnly = 0;
}
// Fallback to the first non shadow casting directional light.

{
lightData.shadowMaskSelector[light.light.bakingOutput.occlusionMaskChannel] = 1.0f;
// TODO: make this option per light, not global
lightData.dynamicShadowCasterOnly = QualitySettings.shadowmaskMode == ShadowmaskMode.Shadowmask ? 1 : 0;
lightData.nonLightmappedOnly = light.light.lightShadowCasterMode == LightShadowCasterMode.NonLightmappedOnly ? 1 : 0;
lightData.dynamicShadowCasterOnly = 0;
lightData.nonLightmappedOnly = 0;
}
m_lightList.lights.Add(lightData);

// If any light require it, we need to enabled bake shadow mask feature
m_enableBakeShadowMask = false;
m_lightList.Clear();
// We need to properly reset this here otherwise if we go from 1 light to no visible light we would keep the old reference active.

public void RenderDeferredLighting( HDCamera hdCamera, CommandBuffer cmd, DebugDisplaySettings debugDisplaySettings,
RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthStencilBuffer, RenderTargetIdentifier depthTexture,
LightingPassOptions options)
LightingPassOptions options, ComputeBuffer debugSSTBuffer)
{
cmd.SetGlobalBuffer(HDShaderIDs.g_vLightListGlobal, s_LightList);

using (new ProfilingSample(cmd, sLabel, CustomSamplerId.TPRenderDeferredLighting.GetSampler()))
{
var camera = hdCamera.camera;
var ssReflection = VolumeManager.instance.stack.GetComponent<ScreenSpaceReflection>() ?? ScreenSpaceReflection.@default;
// Compute path
if (m_FrameSettings.lightLoopSettings.enableTileAndCluster && m_FrameSettings.lightLoopSettings.enableComputeLightEvaluation)

cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs.specularLightingUAV, colorBuffers[0]);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs.diffuseLightingUAV, colorBuffers[1]);
if (debugDisplaySettings.lightingDebugSettings.debugLightingMode == DebugLightingMode.ScreenSpaceTracingReflection)
cmd.SetComputeBufferParam(deferredComputeShader, kernel, HDShaderIDs._DebugScreenSpaceTracingData, debugSSTBuffer);
// always do deferred lighting in blocks of 16x16 (not same as tiled light size)
if (enableFeatureVariants)

currentLightingMaterial.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal);
}
var debugSSTThisFrame = debugDisplaySettings.lightingDebugSettings.debugLightingMode == DebugLightingMode.ScreenSpaceTracingReflection;
if (debugSSTThisFrame)
cmd.SetRandomWriteTarget(7, debugSSTBuffer);
if (debugSSTThisFrame)
cmd.ClearRandomWriteTargets();
}
}
} // End profiling

2
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/PlanarReflectionProbe.cs


get
{
return m_ProxyVolumeReference != null
? m_ProxyVolumeReference.proxyVolume.boxSize * 0.5f
? m_ProxyVolumeReference.proxyVolume.extents
: influenceVolume.boxBaseSize;
}
}

2
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ProbeWrapper.cs


get
{
return additional.proxyVolumeComponent != null
? additional.proxyVolumeComponent.proxyVolume.boxSize * 0.5f
? additional.proxyVolumeComponent.proxyVolume.extents
: influenceExtents;
}
}

34
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ScreenSpaceRefraction.cs


namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[Serializable]
public class ScreenSpaceRefraction : VolumeComponent
public class ScreenSpaceRefraction : ScreenSpaceLighting
{
static ScreenSpaceRefraction s_Default = null;
public static ScreenSpaceRefraction @default

}
}
public IntParameter rayMinLevel = new IntParameter(2);
public IntParameter rayMaxLevel = new IntParameter(6);
public IntParameter rayMaxIterations = new IntParameter(32);
public FloatParameter rayDepthSuccessBias = new FloatParameter(0.1f);
public ClampedFloatParameter screenWeightDistance = new ClampedFloatParameter(0.1f, 0, 1);
public void PushShaderParameters(CommandBuffer cmd)
protected override void FetchIDs(
out int rayLevelID,
out int rayMinLevelID,
out int rayMaxLevelID,
out int rayMaxIterationsID,
out int depthBufferThicknessID,
out int invScreenWeightDistanceID,
out int rayMaxScreenDistanceID,
out int rayBlendScreenDistanceID,
out int rayMarchBehindObjectsID
)
cmd.SetGlobalInt(HDShaderIDs._SSRefractionRayMinLevel, rayMinLevel.value);
cmd.SetGlobalInt(HDShaderIDs._SSRefractionRayMaxLevel, rayMaxLevel.value);
cmd.SetGlobalInt(HDShaderIDs._SSRefractionRayMaxIterations, rayMaxIterations.value);
cmd.SetGlobalFloat(HDShaderIDs._SSRefractionRayDepthSuccessBias, rayDepthSuccessBias.value);
cmd.SetGlobalFloat(HDShaderIDs._SSRefractionInvScreenWeightDistance, 1f / screenWeightDistance.value);
rayLevelID = HDShaderIDs._SSRefractionRayLevel;
rayMinLevelID = HDShaderIDs._SSRefractionRayMinLevel;
rayMaxLevelID = HDShaderIDs._SSRefractionRayMaxLevel;
rayMaxIterationsID = HDShaderIDs._SSRefractionRayMaxIterations;
depthBufferThicknessID = HDShaderIDs._SSRefractionDepthBufferThickness;
invScreenWeightDistanceID = HDShaderIDs._SSRefractionInvScreenWeightDistance;
rayMaxScreenDistanceID = HDShaderIDs._SSRefractionRayMaxScreenDistance;
rayBlendScreenDistanceID = HDShaderIDs._SSRefractionRayBlendScreenDistance;
rayMarchBehindObjectsID = HDShaderIDs._SSRefractionRayMarchBehindObjects;
}
}
}

846
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ScreenSpaceTracing.hlsl


#ifndef UNITY_SCREEN_SPACE_TRACING_INCLUDED
#define UNITY_SCREEN_SPACE_TRACING_INCLUDED
// How this file works:
// This file is separated in two sections: 1. Library, 2. Constant Buffer Specific Signatures
//
// 1. Library
// This section contains all function and structures for the Screen Space Tracing.
//
// 2. Constant Buffer Specific Signatures
// This section defines signatures that will use specifics constant buffers.
// Thus you can use the Screen Space Tracing library with different settings.
// It can be usefull to use it for both reflection and refraction but with different settings' sets.
//
//
// To use this file:
// 1. Define the macro SSRTID
// 2. Include the file
// 3. Undef the macro SSRTID
//
//
// Example for reflection:
// #define SSRTID Reflection
// #include "ScreenSpaceTracing.hlsl"
// #undef SSRTID
//
// Use library here, like ScreenSpaceProxyRaycastReflection(...)
// #################################################
// Notes
// #################################################
// Some banding issues can occurs when raymarching the depth buffer.
//
// This can be hidden by offsetting the ray origin with a jitter.
// Combined with a temporal filtering, the banding artifact will be smoothed.
// This will trade banding for noise.
//
// This happens when we raymarch with a ray direction that is quite different from the view vector.
// Exemple when raymarching with a direction perpendicular to the view vector:
//
// Depth buffer far
// |
// v
// near
//
// --------
// hit ==>xx
// xx
//
// fail ===>
// xx
// hit ===>xx
//
// xx
// #################################################
// Screen Space Tracing Library
// #################################################
const float DepthPlaneBias = 1E-5;
// -------------------------------------------------

struct ScreenSpaceRayHit
{
uint2 positionSS; // Position of the hit point (SS)
float2 positionNDC; // Position of the hit point (NDC)
float linearDepth; // Linear depth of the hit point
uint2 positionSS; // Position of the hit point (SS)
float2 positionNDC; // Position of the hit point (NDC)
float linearDepth; // Linear depth of the hit point
#ifdef DEBUG_DISPLAY
float3 debugOutput;

struct ScreenSpaceHiZRaymarchInput
struct ScreenSpaceRaymarchInput
uint maxIterations; // Number of iterations before failing
#ifdef DEBUG_DISPLAY
bool debug;

{
float3 rayOriginWS; // Ray origin (WS)
float3 rayDirWS; // Ray direction (WS)
EnvLightData proxyData;
EnvLightData proxyData; // Proxy to use for raycasting
#ifdef DEBUG_DISPLAY
bool debug;

// -------------------------------------------------
// Calculate the ray origin and direction in SS
// out positionSS : (x, y, 1/depth)
// out raySS : (x, y, 1/depth)
float3 rayOriginWS,
float3 rayDirWS,
uint2 bufferSize,
out float3 positionSS,
out float3 raySS
float3 rayOriginWS, // Ray origin (World Space)
float3 rayDirWS, // Ray direction (World Space)
uint2 bufferSize, // Texture size of screen buffers
out float3 positionSS, // (x, y, 1/linearDepth)
out float3 raySS, // (dx, dy, d(1/linearDepth))
out float rayEndDepth // Linear depth of the end point used to calculate raySS
const float kNearClipPlane = -0.01;
const float kMaxRayTraceDistance = 1000;
float3 rayOriginVS = mul(GetWorldToViewMatrix(), float4(rayOriginWS, 1.0)).xyz;
float3 rayDirVS = mul((float3x3)GetWorldToViewMatrix(), rayDirWS);
// Clip ray to near plane to avoid raymarching behind camera
float rayLength = ((rayOriginVS.z + rayDirVS.z * kMaxRayTraceDistance) > kNearClipPlane)
? ((kNearClipPlane - rayOriginVS.z) / rayDirVS.z)
: kMaxRayTraceDistance;
float3 rayEndWS = rayOriginWS + rayDirWS * 10;
float3 rayEndWS = rayOriginWS + rayDirWS * rayLength;
float4 positionCS = ComputeClipSpacePosition(positionWS, GetWorldToHClipMatrix());
float4 rayEndCS = ComputeClipSpacePosition(rayEndWS, GetWorldToHClipMatrix());

rayEndDepth = rayEndCS.w;
float3 rayStartSS = float3(
positionNDC.xy * bufferSize,

rayEndNDC.xy * bufferSize,
1.0 / rayEndCS.w); // Screen space depth interpolate properly in 1/z
1.0 / rayEndDepth); // Screen space depth interpolate properly in 1/z
}
// Check whether the depth of the ray is above the sampled depth
// Arguments are inversed linear depth
bool IsPositionAboveDepth(float rayDepth, float invLinearDepth)
{
// as depth is inverted, we must invert the check as well
// rayZ > HiZ <=> 1/rayZ < 1/HiZ
return rayDepth > invLinearDepth;
float LoadDepth(float2 positionSS, int level)
float2 LoadDepth(float2 positionSS, int level)
float pyramidDepth = LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, int2(positionSS.xy) >> level, level).r;
float linearDepth = LinearEyeDepth(pyramidDepth, _ZBufferParams);
float2 pyramidDepth = LOAD_TEXTURE2D_LOD(_DepthPyramidTexture, int2(positionSS.xy) >> level, level).rg;
float2 linearDepth = float2(LinearEyeDepth(pyramidDepth.r, _ZBufferParams), LinearEyeDepth(pyramidDepth.g, _ZBufferParams));
float LoadInvDepth(float2 positionSS, int level)
float2 LoadInvDepth(float2 positionSS, int level)
float linearDepth = LoadDepth(positionSS, level);
float invLinearDepth = 1 / linearDepth;
float2 linearDepth = LoadDepth(positionSS, level);
float2 invLinearDepth = 1 / linearDepth;
return invLinearDepth;
}

return positionSS + raySS * t;
}
// Calculate intersection between a ray and a cell
float3 IntersectCellPlanes(
float3 positionSS,
float3 raySS,
float2 invRaySS,
int2 cellId,
uint2 cellSize,
int2 cellPlanes,
float2 crossOffset
float2 CalculateDistanceToCellPlanes(
float3 positionSS, // Ray Origin (Screen Space, 1/LinearDepth)
float2 invRaySS, // 1/RayDirection
int2 cellId, // (Row, Colum) of the cell
uint2 cellSize, // Size of the cell in pixel
int2 cellPlanes // Planes to intersect (one of (0,0), (1, 0), (0, 1), (1, 1))
const float SQRT_2 = sqrt(2);
const float CellPlaneBias = 1E-2;
return distanceToCellAxes;
}
// Calculate intersection between a ray and a cell
float3 IntersectCellPlanes(
float3 positionSS, // Ray Origin (Screen Space, 1/LinearDepth)
float3 raySS, // Ray Direction (Screen Space, 1/LinearDepth)
float2 invRaySS, // 1/RayDirection
int2 cellId, // (Row, Colum) of the cell
uint2 cellSize, // Size of the cell in pixel
int2 cellPlanes, // Planes to intersect (one of (0,0), (1, 0), (0, 1), (1, 1))
float2 crossOffset // Offset to use to ensure cell boundary crossing
)
{
float2 distanceToCellAxes = CalculateDistanceToCellPlanes(
positionSS,
invRaySS,
cellId,
cellSize,
cellPlanes
);
// Offset by 1E-3 to ensure cell boundary crossing
// Offset to ensure cell crossing
+ CellPlaneBias;
+ 0.1;
// Interpolate screen space to get next test point
float3 testHitPositionSS = positionSS + raySS * t;

float CalculateHitWeight(
ScreenSpaceRayHit hit,
float2 startPositionSS,
float minLinearDepth,
float settingsDepthBufferThickness,
float settingsRayMaxScreenDistance,
float settingsRayBlendScreenDistance
)
{
// Blend when the hit is near the thickness of the object
//float thicknessWeight = clamp(1 - (hit.linearDepth - minLinearDepth) / settingsDepthBufferThickness, 0, 1);
// Blend when the ray when the raymarched distance is too long
float2 screenDistanceNDC = abs(hit.positionSS.xy - startPositionSS) * _ScreenSize.zw;
float2 screenDistanceWeights = clamp((settingsRayMaxScreenDistance - screenDistanceNDC) / settingsRayBlendScreenDistance, 0, 1);
float screenDistanceWeight = min(screenDistanceWeights.x, screenDistanceWeights.y);
// return thicknessWeight * screenDistanceWeight;
return screenDistanceWeight;
}
#ifdef DEBUG_DISPLAY
// -------------------------------------------------
// Debug Utilities

float3 rayDirWS,
bool hitSuccessful,
int tracingModel,
inout ScreenSpaceRayHit hit
)
{

hit.debugOutput = frac(hit.linearDepth * 0.1);
break;
case DEBUGSCREENSPACETRACING_HIT_SUCCESS:
hit.debugOutput = hitSuccessful;
hit.debugOutput = GetIndexColor(hitSuccessful ? 1 : 2);
break;
case DEBUGSCREENSPACETRACING_TRACING_MODEL:
hit.debugOutput = GetIndexColor(tracingModel);
#endif
void DebugComputeHiZOutput(
int iteration,
float3 startPositionSS,
float3 rayDirSS,
int maxIterations,
int maxUsedLevel,
int maxMipLevel,
int intersectionKind,
inout ScreenSpaceRayHit hit
float SampleBayer4(uint2 positionSS)
{
const float4x4 Bayer4 = float4x4(0, 8, 2, 10,
12, 4, 14, 6,
3, 11, 1, 9,
15, 7, 13, 5) / 16;
return Bayer4[positionSS.x % 4][positionSS.y % 4];
}
// -------------------------------------------------
// Algorithms
// -------------------------------------------------
// -------------------------------------------------
// Algorithm: Linear Raymarching
// -------------------------------------------------
// Based on Digital Differential Analyzer and Morgan McGuire's Screen Space Ray Tracing (http://casual-effects.blogspot.fr/2014/08/screen-space-ray-tracing.html)
//
// Linear raymarching algorithm with precomputed properties
// -------------------------------------------------
bool ScreenSpaceLinearRaymarch(
ScreenSpaceRaymarchInput input,
// Settings
int settingRayLevel, // Mip level to use to ray march depth buffer
uint settingsRayMaxIterations, // Maximum number of iterations (= max number of depth samples)
float settingsDepthBufferThickness, // Bias to use when trying to detect whenever we raymarch behind a surface
float settingsRayMaxScreenDistance, // Maximum screen distance raymarched
float settingsRayBlendScreenDistance, // Distance to blend before maximum screen distance is reached
int settingsDebuggedAlgorithm, // currently debugged algorithm (see PROJECTIONMODEL defines)
// Precomputed properties
float3 startPositionSS, // Start position in Screen Space (x in pixel, y in pixel, z = 1/linearDepth)
float3 raySS, // Ray direction in Screen Space (dx in pixel, dy in pixel, z = 1/endPointLinearDepth - 1/startPointLinearDepth)
float rayEndDepth, // Linear depth of the end point used to calculate raySS.
uint2 bufferSize, // Texture size of screen buffers
// Out
out ScreenSpaceRayHit hit,
out float hitWeight,
out uint iteration
ZERO_INITIALIZE(ScreenSpaceRayHit, hit);
bool hitSuccessful = false;
iteration = 0u;
hitWeight = 0;
int mipLevel = min(max(settingRayLevel, 0), int(_DepthPyramidScale.z));
uint maxIterations = settingsRayMaxIterations;
float3 positionSS = startPositionSS;
raySS /= max(abs(raySS.x), abs(raySS.y));
raySS *= 1 << mipLevel;
#ifdef DEBUG_DISPLAY
float3 debugIterationPositionSS = positionSS;
uint debugIteration = iteration;
float debugIterationLinearDepthBufferMin = 0;
float debugIterationLinearDepthBufferMinThickness = 0;
float debugIterationLinearDepthBufferMax = 0;
#endif
float2 invLinearDepth = float2(0.0, 0.0);
float minLinearDepth = 0;
float minLinearDepthWithThickness = 0;
float positionLinearDepth = 0;
for (iteration = 0u; iteration < maxIterations; ++iteration)
{
positionSS += raySS;
// Sampled as 1/Z so it interpolate properly in screen space.
invLinearDepth = LoadInvDepth(positionSS.xy, mipLevel);
minLinearDepth = 1 / invLinearDepth.r;
minLinearDepthWithThickness = minLinearDepth + settingsDepthBufferThickness;
positionLinearDepth = 1 / positionSS.z;
bool isAboveDepth = positionLinearDepth < minLinearDepth;
bool isAboveThickness = positionLinearDepth < minLinearDepthWithThickness;
bool isBehindDepth = !isAboveThickness;
bool intersectWithDepth = !isAboveDepth && isAboveThickness;
#ifdef DEBUG_DISPLAY
// Fetch post iteration debug values
if (input.debug && _DebugStep >= int(iteration))
{
debugIterationPositionSS = positionSS;
debugIterationLinearDepthBufferMin = minLinearDepth;
debugIterationLinearDepthBufferMinThickness = minLinearDepthWithThickness;
debugIterationLinearDepthBufferMax = 1 / invLinearDepth.g;
debugIteration = iteration;
}
#endif
if (intersectWithDepth)
{
hitSuccessful = true;
break;
}
// Check if we are out of the buffer
if (any(int2(positionSS.xy) > int2(bufferSize))
|| any(positionSS.xy < 0)
)
{
hitSuccessful = false;
break;
}
}
if (iteration >= maxIterations)
hitSuccessful = false;
hit.linearDepth = 1 / positionSS.z;
hit.positionNDC = float2(positionSS.xy) / float2(bufferSize);
hit.positionSS = uint2(positionSS.xy);
// Detect when we go behind an object given a thickness
hitWeight = CalculateHitWeight(
hit,
startPositionSS.xy,
invLinearDepth.r,
settingsDepthBufferThickness,
settingsRayMaxScreenDistance,
settingsRayBlendScreenDistance
);
if (hitWeight <= 0)
hitSuccessful = false;
#ifdef DEBUG_DISPLAY
DebugComputeCommonOutput(input.rayDirWS, hitSuccessful, PROJECTIONMODEL_LINEAR, hit);
case DEBUGSCREENSPACETRACING_HI_ZPOSITION_NDC:
case DEBUGSCREENSPACETRACING_LINEAR_POSITION_NDC:
case DEBUGSCREENSPACETRACING_HI_ZITERATION_COUNT:
hit.debugOutput = float(iteration) / float(maxIterations);
case DEBUGSCREENSPACETRACING_LINEAR_ITERATION_COUNT:
hit.debugOutput = float(iteration) / float(settingsRayMaxIterations);
case DEBUGSCREENSPACETRACING_HI_ZRAY_DIR_NDC:
hit.debugOutput = float3(rayDirSS.xy * 0.5 + 0.5, frac(0.1 / rayDirSS.z));
case DEBUGSCREENSPACETRACING_LINEAR_RAY_DIR_NDC:
hit.debugOutput = float3(raySS.xy * 0.5 + 0.5, frac(0.1 / raySS.z));
case DEBUGSCREENSPACETRACING_HI_ZMAX_USED_MIP_LEVEL:
hit.debugOutput = float(maxUsedLevel) / float(maxMipLevel);
break;
case DEBUGSCREENSPACETRACING_HI_ZINTERSECTION_KIND:
hit.debugOutput = GetIndexColor(intersectionKind);
case DEBUGSCREENSPACETRACING_LINEAR_HIT_WEIGHT:
hit.debugOutput = float3(hitWeight, hitWeight, hitWeight);
}
#endif
#endif
// -------------------------------------------------
// Algorithm: Proxy raycast
// -------------------------------------------------
if (input.debug
&& _DebugScreenSpaceTracingData[0].tracingModel == -1
&& settingsDebuggedAlgorithm == PROJECTIONMODEL_LINEAR
)
{
// Build debug structure
ScreenSpaceTracingDebug debug;
ZERO_INITIALIZE(ScreenSpaceTracingDebug, debug);
#ifdef SSRTID
debug.tracingModel = PROJECTIONMODEL_LINEAR;
debug.loopStartPositionSSX = uint(startPositionSS.x);
debug.loopStartPositionSSY = uint(startPositionSS.y);
debug.loopStartLinearDepth = 1 / startPositionSS.z;
debug.loopRayDirectionSS = raySS;
debug.loopIterationMax = iteration;
debug.iterationPositionSS = debugIterationPositionSS;
debug.iterationMipLevel = mipLevel;
debug.iteration = debugIteration;
debug.iterationLinearDepthBufferMin = debugIterationLinearDepthBufferMin;
debug.iterationLinearDepthBufferMinThickness = debugIterationLinearDepthBufferMinThickness;
debug.iterationLinearDepthBufferMax = debugIterationLinearDepthBufferMax;
debug.endHitSuccess = hitSuccessful;
debug.endLinearDepth = hit.linearDepth;
debug.endPositionSSX = hit.positionSS.x;
debug.endPositionSSY = hit.positionSS.y;
debug.iterationCellSizeW = 1 << mipLevel;
debug.iterationCellSizeH = 1 << mipLevel;
debug.endHitWeight = hitWeight;
#define SSRT_SETTING(name, SSRTID) _SS ## SSRTID ## name
#define SSRT_FUNC(name, SSRTID) name ## SSRTID
_DebugScreenSpaceTracingData[0] = debug;
}
#endif
CBUFFER_START(SSRT_FUNC(UnityScreenSpaceRaymarching, SSRTID))
int SSRT_SETTING(RayMinLevel, SSRTID);
int SSRT_SETTING(RayMaxLevel, SSRTID);
int SSRT_SETTING(RayMaxIterations, SSRTID);
float SSRT_SETTING(RayDepthSuccessBias, SSRTID);
CBUFFER_END
return hitSuccessful;
}
bool SSRT_FUNC(ScreenSpaceProxyRaycast, SSRTID)(
// -------------------------------------------------
// Algorithm: Scene Proxy Raycasting
// -------------------------------------------------
// We perform a raycast against a proxy volume that approximate the current scene.
// Is is a simple shape (Sphere, Box).
// -------------------------------------------------
bool ScreenSpaceProxyRaycast(
// Settings
int settingsDebuggedAlgorithm, // currently debugged algorithm (see PROJECTIONMODEL defines)
// Out
// Initialize loop
ZERO_INITIALIZE(ScreenSpaceRayHit, hit);
float3x3 worldToPS = WorldToProxySpace(input.proxyData);

hit.positionSS = hitPositionSS;
hit.linearDepth = hitLinearDepth;
bool hitSuccessful = true;
bool hitSuccessful = hitLinearDepth > 0; // Negative means that the hit is behind the camera
DebugComputeCommonOutput(input.rayDirWS, hitSuccessful, hit);
DebugComputeCommonOutput(input.rayDirWS, hitSuccessful, PROJECTIONMODEL_PROXY, hit);
if (input.debug)
if (input.debug
&& _DebugScreenSpaceTracingData[0].tracingModel == -1
&& settingsDebuggedAlgorithm == PROJECTIONMODEL_PROXY
)
{
ScreenSpaceTracingDebug debug;
ZERO_INITIALIZE(ScreenSpaceTracingDebug, debug);

debug.tracingModel = REFRACTIONSSRAYMODEL_PROXY;
debug.tracingModel = PROJECTIONMODEL_PROXY;
debug.loopStartPositionSSX = rayOriginSS.x;
debug.loopStartPositionSSY = rayOriginSS.y;
debug.loopStartLinearDepth = rayOriginCS.w;

}
// -------------------------------------------------
// Algorithm: HiZ raymarching
// Algorithm: Linear Raymarching And Scene Proxy Raycasting
// -------------------------------------------------
// Perform a linear raymarching for close hit detection and fallback on proxy raycasting
bool ScreenSpaceLinearProxyRaycast(
ScreenSpaceProxyRaycastInput input,
// Settings (linear)
int settingRayLevel, // Mip level to use to ray march depth buffer
uint settingsRayMaxIterations, // Maximum number of iterations (= max number of depth samples)
float settingsDepthBufferThickness, // Bias to use when trying to detect whenever we raymarch behind a surface
float settingsRayMaxScreenDistance, // Maximum screen distance raymarched
float settingsRayBlendScreenDistance, // Distance to blend before maximum screen distance is reached
// Settings (common)
int settingsDebuggedAlgorithm, // currently debugged algorithm (see PROJECTIONMODEL defines)
// Out
out ScreenSpaceRayHit hit
)
{
// Perform linear raymarch
ScreenSpaceRaymarchInput inputLinear;
inputLinear.rayOriginWS = input.rayOriginWS;
inputLinear.rayDirWS = input.rayDirWS;
#ifdef DEBUG_DISPLAY
inputLinear.debug = input.debug;
#endif
// Based on Yasin Uludag, 2014. "Hi-Z Screen-Space Cone-Traced Reflections", GPU Pro5: Advanced Rendering Techniques
uint2 bufferSize = uint2(_DepthPyramidSize.xy);
// Compute properties for linear raymarch
float3 startPositionSS;
float3 raySS;
float rayEndDepth;
CalculateRaySS(
input.rayOriginWS,
input.rayDirWS,
bufferSize,
startPositionSS,
raySS,
rayEndDepth
);
bool SSRT_FUNC(ScreenSpaceHiZRaymarch, SSRTID)(
ScreenSpaceHiZRaymarchInput input,
out ScreenSpaceRayHit hit
uint iteration;
float hitWeight;
bool hitSuccessful = ScreenSpaceLinearRaymarch(
inputLinear,
// Settings
settingRayLevel,
settingsRayMaxIterations,
settingsDepthBufferThickness,
settingsRayMaxScreenDistance,
settingsRayBlendScreenDistance,
settingsDebuggedAlgorithm,
// Precomputed properties
startPositionSS,
raySS,
rayEndDepth,
bufferSize,
// Out
hit,
hitWeight,
iteration
);
if (!hitSuccessful)
{
hitSuccessful = ScreenSpaceProxyRaycast(
input,
// Settings
settingsDebuggedAlgorithm,
// Out
hit
);
}
return hitSuccessful;
}
// -------------------------------------------------
// Algorithm: HiZ raymarching
// -------------------------------------------------
// Based on Yasin Uludag, 2014. "Hi-Z Screen-Space Cone-Traced Reflections", GPU Pro5: Advanced Rendering Techniques
//
// NB: We perform first a linear raymarch to handle close hits, then we perform the actual HiZ raymarching.
// We do this for two reasons:
// - It is cheaper in case of close hit than starting with HiZ
// - It will start the HiZ algorithm with an offset, preventing false positive hit at ray origin.
// -------------------------------------------------
bool ScreenSpaceHiZRaymarch(
ScreenSpaceRaymarchInput input,
// Settings
uint settingsRayMinLevel, // Minimum mip level to use for ray marching the depth buffer in HiZ
uint settingsRayMaxLevel, // Maximum mip level to use for ray marching the depth buffer in HiZ
uint settingsRayMaxIterations, // Maximum number of iteration for the HiZ raymarching (= number of depth sample for HiZ)
float settingsDepthBufferThickness, // Bias to use when trying to detect whenever we raymarch behind a surface
float settingsRayMaxScreenDistance, // Maximum screen distance raymarched
float settingsRayBlendScreenDistance, // Distance to blend before maximum screen distance is reached
bool settingsRayMarchBehindObjects, // Whether to raymarch behind objects
int settingsDebuggedAlgorithm, // currently debugged algorithm (see PROJECTIONMODEL defines)
// out
out ScreenSpaceRayHit hit,
out float hitWeight
)
{
const float2 CROSS_OFFSET = float2(1, 1);

bool hitSuccessful = true;
hitWeight = 0;
bool hitSuccessful = false;
int minMipLevel = max(SSRT_SETTING(RayMinLevel, SSRTID), 0);
int maxMipLevel = min(SSRT_SETTING(RayMaxLevel, SSRTID), int(_DepthPyramidScale.z));
int minMipLevel = max(settingsRayMinLevel, 0u);
int maxMipLevel = min(settingsRayMaxLevel, uint(_DepthPyramidScale.z));
uint maxIterations = min(input.maxIterations, SSRT_SETTING(RayMaxIterations, SSRTID));
uint maxIterations = settingsRayMaxIterations;
float rayEndDepth;
raySS
raySS,
rayEndDepth
);
#ifdef DEBUG_DISPLAY

float3 debugIterationPositionSS = float3(0, 0, 0);
uint debugIteration = 0u;
uint debugIterationIntersectionKind = 0u;
float debugIterationLinearDepthBuffer = 0;
float debugIterationLinearDepthBufferMin = 0;
float debugIterationLinearDepthBufferMinThickness = 0;
float debugIterationLinearDepthBufferMax = 0;
iteration = 0u;
int intersectionKind = 0;
float raySSLength = length(raySS.xy);
raySS /= raySSLength;

uint2 cellSize = uint2(1, 1) << currentLevel;
float3 positionSS = startPositionSS;
float invHiZDepth = 0;
float2 invLinearDepth = float2(0.0, 0.0);
float positionLinearDepth = 0;
float minLinearDepth = 0;
float minLinearDepthWithThickness = 0;
// Intersect with first cell and add an offsot to avoid HiZ raymarching to stuck at the origin
{
const float epsilon = 1E-3;
const float minTraversal = 2 << currentLevel;
float2 distanceToCellAxes = CalculateDistanceToCellPlanes(
positionSS,
invRaySS,
int2(positionSS.xy) / cellSize,
cellSize,
cellPlanes
);
float t = min(distanceToCellAxes.x * minTraversal + epsilon, distanceToCellAxes.y * minTraversal + epsilon);
positionSS = positionSS + raySS * t;
}
bool isBehindDepth = false;
hitSuccessful = true;
if (iteration >= maxIterations)
{
hitSuccessful = false;

#ifdef DEBUG_DISPLAY
// Fetch pre iteration debug values
if (input.debug && _DebugStep >= iteration)
if (input.debug && _DebugStep >= int(iteration))
debugIterationMipLevel = currentLevel;
#endif

// Sampled as 1/Z so it interpolate properly in screen space.
invHiZDepth = LoadInvDepth(positionSS.xy, currentLevel);
invLinearDepth = LoadInvDepth(positionSS.xy, currentLevel);
positionLinearDepth = 1 / positionSS.z;
minLinearDepth = 1 / invLinearDepth.r;
minLinearDepthWithThickness = minLinearDepth + settingsDepthBufferThickness;
bool isAboveDepth = positionLinearDepth < minLinearDepth;
bool isAboveThickness = positionLinearDepth < minLinearDepthWithThickness;
isBehindDepth = !isAboveThickness;
bool intersectWithDepth = minLinearDepth >= positionLinearDepth && isAboveThickness;
if (IsPositionAboveDepth(positionSS.z, invHiZDepth))
// Nominal case, we raymarch in front of the depth buffer and accelerate with HiZ
if (isAboveDepth)
float3 candidatePositionSS = IntersectDepthPlane(positionSS, raySS, invHiZDepth);
float3 candidatePositionSS = IntersectDepthPlane(positionSS, raySS, invLinearDepth.r);
intersectionKind = HIZINTERSECTIONKIND_DEPTH;

cellId,
cellSize,
cellPlanes,
crossOffset);
crossOffset
);
intersectionKind = HIZINTERSECTIONKIND_CELL;

positionSS = candidatePositionSS;
}
// Raymarching behind object in depth buffer, this case degenerate into a linear search
else if (settingsRayMarchBehindObjects && isBehindDepth && currentLevel <= (minMipLevel + 1))
{
const int2 cellId = int2(positionSS.xy) / cellSize;
positionSS = IntersectCellPlanes(
positionSS,
raySS,
invRaySS,
cellId,
cellSize,
cellPlanes,
crossOffset
);
intersectionKind = HIZINTERSECTIONKIND_CELL;
mipLevelDelta = 1;
}
float4 distancesToBorders = float4(positionSS.xy, bufferSize - positionSS.xy);
float distanceToBorders = min(min(distancesToBorders.x, distancesToBorders.y), min(distancesToBorders.z, distancesToBorders.w));
int minLevelForBorders = int(log2(distanceToBorders));
currentLevel = min(currentLevel, minLevelForBorders);
if (input.debug && _DebugStep >= iteration)
if (input.debug && _DebugStep >= int(iteration))
debugIterationLinearDepthBuffer = 1 / invHiZDepth;
debugIterationLinearDepthBufferMin = 1 / invLinearDepth.r;
debugIterationLinearDepthBufferMinThickness = 1 / invLinearDepth.r + settingsDepthBufferThickness;
debugIterationLinearDepthBufferMax = 1 / invLinearDepth.g;
debugIteration = iteration;
debugIterationIntersectionKind = intersectionKind;
debugIterationCellSize = cellSize;

// Check if we are out of the buffer
if (any(int2(positionSS.xy) > int2(bufferSize))
|| any(positionSS.xy < 0)
)
|| any(positionSS.xy < 0))
{
hitSuccessful = false;
break;

}
hit.linearDepth = 1 / positionSS.z;
hit.positionNDC = float2(positionSS.xy) / float2(bufferSize);
hit.linearDepth = positionLinearDepth;
hit.positionNDC = float2(hit.positionSS) / float2(bufferSize);
if (hit.linearDepth > (1 / invHiZDepth) + SSRT_SETTING(RayDepthSuccessBias, SSRTID))
// Detect when we go behind an object given a thickness
hitWeight = CalculateHitWeight(
hit,
startPositionSS.xy,
minLinearDepth,
settingsDepthBufferThickness,
settingsRayMaxScreenDistance,
settingsRayBlendScreenDistance
);
if (hitWeight <= 0 || isBehindDepth)
DebugComputeCommonOutput(input.rayDirWS, hitSuccessful, hit);
DebugComputeHiZOutput(
iteration,
startPositionSS,
raySS,
SSRT_SETTING(RayMaxIterations, SSRTID),
debugLoopMipMaxUsedLevel,
maxMipLevel,
intersectionKind,
hit
);
DebugComputeCommonOutput(input.rayDirWS, hitSuccessful, PROJECTIONMODEL_HI_Z, hit);
switch (_DebugLightingSubMode)
{
case DEBUGSCREENSPACETRACING_HI_ZPOSITION_NDC:
hit.debugOutput = float3(float2(startPositionSS.xy) * _ScreenSize.zw, 0);
break;
case DEBUGSCREENSPACETRACING_HI_ZITERATION_COUNT:
hit.debugOutput = float(iteration) / float(settingsRayMaxIterations);
break;
case DEBUGSCREENSPACETRACING_HI_ZRAY_DIR_NDC:
hit.debugOutput = float3(raySS.xy * 0.5 + 0.5, frac(0.1 / raySS.z));
break;
case DEBUGSCREENSPACETRACING_HI_ZMAX_USED_MIP_LEVEL:
hit.debugOutput = float(debugLoopMipMaxUsedLevel) / float(maxMipLevel);
break;
case DEBUGSCREENSPACETRACING_HI_ZINTERSECTION_KIND:
hit.debugOutput = GetIndexColor(intersectionKind);
break;
case DEBUGSCREENSPACETRACING_HI_ZHIT_WEIGHT:
hit.debugOutput = float3(hitWeight, hitWeight, hitWeight);
break;
}
if (input.debug)
if (input.debug
&& _DebugScreenSpaceTracingData[0].tracingModel == -1
&& settingsDebuggedAlgorithm == PROJECTIONMODEL_HI_Z
)
debug.tracingModel = REFRACTIONSSRAYMODEL_HI_Z;
debug.loopStartPositionSSX = uint(startPositionSS.x);
debug.loopStartPositionSSY = uint(startPositionSS.y);
debug.loopStartLinearDepth = 1 / startPositionSS.z;
debug.loopRayDirectionSS = raySS;
debug.loopMipLevelMax = debugLoopMipMaxUsedLevel;
debug.loopIterationMax = iteration;
debug.iterationPositionSS = debugIterationPositionSS;
debug.iterationMipLevel = debugIterationMipLevel;
debug.iteration = debugIteration;
debug.iterationLinearDepthBuffer = debugIterationLinearDepthBuffer;
debug.iterationIntersectionKind = debugIterationIntersectionKind;
debug.iterationCellSizeW = debugIterationCellSize.x;
debug.iterationCellSizeH = debugIterationCellSize.y;
debug.endHitSuccess = hitSuccessful;
debug.endLinearDepth = hit.linearDepth;
debug.endPositionSSX = hit.positionSS.x;
debug.endPositionSSY = hit.positionSS.y;
debug.tracingModel = PROJECTIONMODEL_HI_Z;
debug.loopStartPositionSSX = uint(startPositionSS.x);
debug.loopStartPositionSSY = uint(startPositionSS.y);
debug.loopStartLinearDepth = 1 / startPositionSS.z;
debug.loopRayDirectionSS = raySS;
debug.loopMipLevelMax = debugLoopMipMaxUsedLevel;
debug.loopIterationMax = iteration;
debug.iterationPositionSS = debugIterationPositionSS;
debug.iterationMipLevel = debugIterationMipLevel;
debug.iteration = debugIteration;
debug.iterationLinearDepthBufferMin = debugIterationLinearDepthBufferMin;
debug.iterationLinearDepthBufferMinThickness = debugIterationLinearDepthBufferMinThickness;
debug.iterationLinearDepthBufferMax = debugIterationLinearDepthBufferMax;
debug.iterationIntersectionKind = debugIterationIntersectionKind;
debug.iterationCellSizeW = debugIterationCellSize.x;
debug.iterationCellSizeH = debugIterationCellSize.y;
debug.endHitSuccess = hitSuccessful;
debug.endLinearDepth = hit.linearDepth;
debug.endPositionSSX = hit.positionSS.x;
debug.endPositionSSY = hit.positionSS.y;
debug.endHitWeight = hitWeight;
_DebugScreenSpaceTracingData[0] = debug;
}

}
#endif
// #################################################
// Screen Space Tracing CB Specific Signatures
// #################################################
#ifdef SSRTID
// -------------------------------------------------
// Macros
// -------------------------------------------------
#define SSRT_SETTING(name, SSRTID) _SS ## SSRTID ## name
// -------------------------------------------------
// Constant buffers
// -------------------------------------------------
CBUFFER_START(MERGE_NAME(UnityScreenSpaceRaymarching, SSRTID))
int SSRT_SETTING(RayLevel, SSRTID);
int SSRT_SETTING(RayMinLevel, SSRTID);
int SSRT_SETTING(RayMaxLevel, SSRTID);
int SSRT_SETTING(RayMaxIterations, SSRTID);
float SSRT_SETTING(DepthBufferThickness, SSRTID);
float SSRT_SETTING(RayMaxScreenDistance, SSRTID);
float SSRT_SETTING(RayBlendScreenDistance, SSRTID);
int SSRT_SETTING(RayMarchBehindObjects, SSRTID);
#ifdef DEBUG_DISPLAY
int SSRT_SETTING(DebuggedAlgorithm, SSRTID);
#endif
CBUFFER_END
// -------------------------------------------------
// Algorithm: Linear Raymarching
// -------------------------------------------------
bool MERGE_NAME(ScreenSpaceLinearRaymarch, SSRTID)(
ScreenSpaceRaymarchInput input,
out ScreenSpaceRayHit hit,
out float hitWeight
)
{
uint2 bufferSize = uint2(_DepthPyramidSize.xy);
float3 startPositionSS;
float3 raySS;
float rayEndDepth;
CalculateRaySS(
input.rayOriginWS,
input.rayDirWS,
bufferSize,
startPositionSS,
raySS,
rayEndDepth
);
uint iteration;
return ScreenSpaceLinearRaymarch(
input,
// settings
SSRT_SETTING(RayLevel, SSRTID),
SSRT_SETTING(RayMaxIterations, SSRTID),
max(0.01, SSRT_SETTING(DepthBufferThickness, SSRTID)),
SSRT_SETTING(RayMaxScreenDistance, SSRTID),
SSRT_SETTING(RayBlendScreenDistance, SSRTID),
#ifdef DEBUG_DISPLAY
SSRT_SETTING(DebuggedAlgorithm, SSRTID),
#else
PROJECTIONMODEL_NONE,
#endif
// precomputed properties
startPositionSS,
raySS,
rayEndDepth,
bufferSize,
// out
hit,
hitWeight,
iteration
);
}
// -------------------------------------------------
// Algorithm: Scene Proxy Raycasting
// -------------------------------------------------
bool MERGE_NAME(ScreenSpaceProxyRaycast, SSRTID)(
ScreenSpaceProxyRaycastInput input,
out ScreenSpaceRayHit hit
)
{
#ifdef DEBUG_DISPLAY
int debuggedAlgorithm = int(SSRT_SETTING(DebuggedAlgorithm, SSRTID));
#else
int debuggedAlgorithm = int(PROJECTIONMODEL_NONE);
#endif
return ScreenSpaceProxyRaycast(
input,
// Settings
debuggedAlgorithm,
// Out
hit
);
}
// -------------------------------------------------
// Algorithm: HiZ raymarching
// -------------------------------------------------
bool MERGE_NAME(ScreenSpaceHiZRaymarch, SSRTID)(
ScreenSpaceRaymarchInput input,
out ScreenSpaceRayHit hit,
out float hitWeight
)
{
return ScreenSpaceHiZRaymarch(
input,
// Settings
SSRT_SETTING(RayMinLevel, SSRTID),
SSRT_SETTING(RayMaxLevel, SSRTID),
SSRT_SETTING(RayMaxIterations, SSRTID),
max(0.01, SSRT_SETTING(DepthBufferThickness, SSRTID)),
SSRT_SETTING(RayMaxScreenDistance, SSRTID),
SSRT_SETTING(RayBlendScreenDistance, SSRTID),
SSRT_SETTING(RayMarchBehindObjects, SSRTID) == 1,
#ifdef DEBUG_DISPLAY
SSRT_SETTING(DebuggedAlgorithm, SSRTID),
#else
PROJECTIONMODEL_NONE,
#endif
// out
hit,
hitWeight
);
}
// -------------------------------------------------
// Cleaning
// -------------------------------------------------
#undef SSRT_FUNC
#endif

13
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/Volumes/ProxyVolume.cs


public Vector3 sphereOffset { get { return m_SphereOffset; } set { m_SphereOffset = value; } }
public bool sphereInfiniteProjection { get { return m_SphereInfiniteProjection; } }
public Vector3 extents
{
get
{
switch (shapeType)
{
case ShapeType.Box: return m_BoxSize * 0.5f;
case ShapeType.Sphere: return Vector3.one * m_SphereRadius;
default: return Vector3.one;
}
}
}
public bool infiniteProjection
{
get

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


[ToggleUI] _DisplacementLockTilingScale("displacement lock tiling scale", Float) = 1.0
[ToggleUI] _DepthOffsetEnable("Depth Offset View space", Float) = 0.0
[ToggleUI] _EnableGeometricSpecularAA("EnableGeometricSpecularAA", Float) = 0.0
_SpecularAAScreenSpaceVariance("SpecularAAScreenSpaceVariance", Range(0.0, 1.0)) = 0.1
_SpecularAAThreshold("SpecularAAThreshold", Range(0.0, 1.0)) = 0.2
[ToggleUI] _EnableMotionVectorForVertexAnimation("EnableMotionVectorForVertexAnimation", Float) = 0.0
_PPDMinSamples("Min sample for POM", Range(1.0, 64.0)) = 5

#pragma shader_feature _ _LAYEREDLIT_3_LAYERS _LAYEREDLIT_4_LAYERS
#pragma shader_feature _DISABLE_DBUFFER
#pragma shader_feature _ENABLE_GEOMETRIC_SPECULAR_AA
// Keyword for transparent
#pragma shader_feature _SURFACE_TYPE_TRANSPARENT

5
com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLitData.hlsl


surfaceData.metallic = 0;
}
#endif
#ifdef _ENABLE_GEOMETRIC_SPECULAR_AA
// Specular AA
surfaceData.perceptualSmoothness = GeometricFilterPerceptualSmoothness(surfaceData.perceptualSmoothness, input.worldToTangent[2], _SpecularAAScreenSpaceVariance, _SpecularAAThreshold);
#endif
GetBuiltinData(input, surfaceData, alpha, bentNormalWS, depthOffset, builtinData);
}

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


[ToggleUI] _DisplacementLockTilingScale("displacement lock tiling scale", Float) = 1.0
[ToggleUI] _DepthOffsetEnable("Depth Offset View space", Float) = 0.0
[ToggleUI] _EnableGeometricSpecularAA("EnableGeometricSpecularAA", Float) = 0.0
_SpecularAAScreenSpaceVariance("SpecularAAScreenSpaceVariance", Range(0.0, 1.0)) = 0.1
_SpecularAAThreshold("SpecularAAThreshold", Range(0.0, 1.0)) = 0.2
[ToggleUI] _EnableMotionVectorForVertexAnimation("EnableMotionVectorForVertexAnimation", Float) = 0.0
_PPDMinSamples("Min sample for POM", Range(1.0, 64.0)) = 5

#pragma shader_feature _ _LAYEREDLIT_3_LAYERS _LAYEREDLIT_4_LAYERS
#pragma shader_feature _DISABLE_DBUFFER
#pragma shader_feature _ENABLE_GEOMETRIC_SPECULAR_AA
// Keyword for transparent
#pragma shader_feature _SURFACE_TYPE_TRANSPARENT

5
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.cs


};
[GenerateHLSL]
public enum RefractionSSRayModel
public enum ProjectionModel
HiZ = 2
HiZ = 2,
Linear = 3
};
[GenerateHLSL]

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


#define MATERIALFEATUREFLAGS_LIT_CLEAR_COAT (64)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+RefractionSSRayModel: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+ProjectionModel: static fields
#define REFRACTIONSSRAYMODEL_NONE (0)
#define REFRACTIONSSRAYMODEL_PROXY (1)
#define REFRACTIONSSRAYMODEL_HI_Z (2)
#define PROJECTIONMODEL_NONE (0)
#define PROJECTIONMODEL_PROXY (1)
#define PROJECTIONMODEL_HI_Z (2)
#define PROJECTIONMODEL_LINEAR (3)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+HiZIntersectionKind: static fields

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


// If a user do a lighting architecture without material classification, this can be remove
#include "../../Lighting/LightLoop/LightLoop.cs.hlsl"
// Currently disable SSR until critical editor fix is available
#undef LIGHTFEATUREFLAGS_SSREFLECTION
#define LIGHTFEATUREFLAGS_SSREFLECTION 0
/* 0 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_ENV | MATERIAL_FEATURE_MASK_FLAGS,
/* 0 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SSREFLECTION | MATERIAL_FEATURE_MASK_FLAGS,
/* 3 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 4 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 3 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SSREFLECTION | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 4 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SSREFLECTION | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 8 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 9 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 8 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SSREFLECTION | MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 9 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SSREFLECTION | MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 13 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_ANISOTROPY | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 14 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_ANISOTROPY | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 13 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SSREFLECTION | MATERIALFEATUREFLAGS_LIT_ANISOTROPY | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 14 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SSREFLECTION | MATERIALFEATUREFLAGS_LIT_ANISOTROPY | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 18 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 19 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 18 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SSREFLECTION | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 19 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SSREFLECTION | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 23 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_IRIDESCENCE | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 24 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_IRIDESCENCE | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 23 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SSREFLECTION | MATERIALFEATUREFLAGS_LIT_IRIDESCENCE | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 24 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SSREFLECTION | MATERIALFEATUREFLAGS_LIT_IRIDESCENCE | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 25 */ LIGHT_FEATURE_MASK_FLAGS_OPAQUE | MATERIALFEATUREFLAGS_LIT_IRIDESCENCE | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 26 */ LIGHT_FEATURE_MASK_FLAGS_OPAQUE | MATERIAL_FEATURE_MASK_FLAGS, // Catch all case with MATERIAL_FEATURE_MASK_FLAGS is needed in case we disable material classification

// Helper functions/variable specific to this material
//-----------------------------------------------------------------------------
// SSReflection
#include "HDRP/Lighting/LightDefinition.cs.hlsl"
#include "HDRP/Lighting/Reflection/VolumeProjection.hlsl"
#define SSRTID Reflection
#include "HDRP/Lighting/Reflection/ScreenSpaceTracing.hlsl"
#undef SSRTID
#include "HDRP/Lighting/LightDefinition.cs.hlsl"
#include "HDRP/Lighting/Reflection/VolumeProjection.hlsl"
#define SSRTID Refraction
#include "HDRP/Lighting/Reflection/ScreenSpaceTracing.hlsl"
#undef SSRTID

#elif defined(_REFRACTION_SPHERE)
#define REFRACTION_MODEL(V, posInputs, bsdfData) RefractionModelSphere(V, posInputs.positionWS, bsdfData.normalWS, bsdfData.ior, bsdfData.thickness)
#endif
#if defined(_REFRACTION_SSRAY_PROXY)
#define REFRACTION_SSRAY_IN ScreenSpaceProxyRaycastInput
#define REFRACTION_SSRAY_QUERY(input, hit) ScreenSpaceProxyRaycastRefraction(input, hit)
#elif defined(_REFRACTION_SSRAY_HIZ)
#define REFRACTION_SSRAY_IN ScreenSpaceHiZRaymarchInput
#define REFRACTION_SSRAY_QUERY(input, hit) ScreenSpaceHiZRaymarchRefraction(input, hit)
#endif
#endif
// This method allows us to know at compile time what material features should be removed from the code by Tile (Indepenently of the value of material feature flag per pixel).

// TODO: We need a better hack.
preLightData.iblPerceptualRoughness *= saturate(1.2 - abs(bsdfData.anisotropy));
// Corretion of reflected direction for better handling of rough material
preLightData.iblR = GetSpecularDominantDir(N, iblR, preLightData.iblPerceptualRoughness, NdotV);
preLightData.iblR = iblR;
#ifdef LIT_USE_GGX_ENERGY_COMPENSATION
// Ref: Practical multiple scattering compensation for microfacet models.

IndirectLighting lighting;
ZERO_INITIALIZE(IndirectLighting, lighting);
switch (GPUImageBasedLightingType)
// -------------------------------
// Early out
// -------------------------------
#if !HAS_REFRACTION
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION)
case GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION:
{
// No refraction, no need to go further
hierarchyWeight = 1.0;
return lighting;
}
#endif
// -------------------------------
// Choose projection model
// -------------------------------
int projectionModel = PROJECTIONMODEL_NONE;
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION)
{
#if defined(_REFRACTION_SSRAY_HIZ)
projectionModel = PROJECTIONMODEL_HI_Z;
#elif defined(_REFRACTION_SSRAY_PROXY)
projectionModel = PROJECTIONMODEL_PROXY;
#endif
}
#else
if (_SSReflectionEnabled != 0)
projectionModel = _SSReflectionProjectionModel;
#endif
// Refraction process:
// 1. Depending on the shape model, we calculate the refracted point in world space and the optical depth
// 2. We calculate the screen space position of the refracted point
// 3. If this point is available (ie: in color buffer and point is not in front of the object)
// a. Get the corresponding color depending on the roughness from the gaussian pyramid of the color buffer
// b. Multiply by the transmittance for absorption (depends on the optical depth)
if (projectionModel == PROJECTIONMODEL_NONE)
return lighting;
// -------------------------------
// Initialize screen space tracing
// -------------------------------
float3 rayOriginWS = float3(0, 0, 0);
float3 rayDirWS = float3(0, 0, 0);
float mipLevel = 0;
#if DEBUG_DISPLAY
int debugMode = 0;
#endif
float invScreenWeightDistance = 0;
float temporalFilteringWeight = 0.1;
#if HAS_REFRACTION
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION)
{
// Refraction process:
// 1. Depending on the shape model, we calculate the refracted point in world space and the optical depth
// 2. We calculate the screen space position of the refracted point
// 3. If this point is available (ie: in color buffer and point is not in front of the object)
// a. Get the corresponding color depending on the roughness from the gaussian pyramid of the color buffer
// b. Multiply by the transmittance for absorption (depends on the optical depth)
float3 rayOriginWS = preLightData.transparentPositionWS;
float3 rayDirWS = preLightData.transparentRefractV;
#ifdef DEBUG_DISPLAY
int debugMode = DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFRACTION;
rayOriginWS = preLightData.transparentPositionWS;
rayDirWS = preLightData.transparentRefractV;
mipLevel = preLightData.transparentSSMipLevel;
invScreenWeightDistance = _SSRefractionInvScreenWeightDistance;
#if DEBUG_DISPLAY
debugMode = DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFRACTION;
#endif
}
else
#endif
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
{
rayOriginWS = posInput.positionWS;
rayDirWS = preLightData.iblR;
mipLevel = PositivePow(preLightData.iblPerceptualRoughness, 0.8) * uint(max(_ColorPyramidScale.z - 1, 0));
invScreenWeightDistance = _SSReflectionInvScreenWeightDistance;
#if DEBUG_DISPLAY
debugMode = DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFLECTION;
#endif
}
#if DEBUG_DISPLAY
// Initialize screen space tracing
REFRACTION_SSRAY_IN ssRayInput;
ZERO_INITIALIZE(REFRACTION_SSRAY_IN, ssRayInput);
// -------------------------------
// Screen space tracing query
// -------------------------------
ScreenSpaceRayHit hit;
ZERO_INITIALIZE(ScreenSpaceRayHit, hit);
bool hitSuccessful = false;
float hitWeight = 1;
// Common initialization
// -------------------------------
// Proxy raycasting
// -------------------------------
if (projectionModel == PROJECTIONMODEL_PROXY)
{
ScreenSpaceProxyRaycastInput ssRayInput;
ZERO_INITIALIZE(ScreenSpaceProxyRaycastInput, ssRayInput);
// Algorithm specific initialization
#ifdef _REFRACTION_SSRAY_HIZ
ssRayInput.maxIterations = uint(-1);
#elif _REFRACTION_SSRAY_PROXY
#if HAS_REFRACTION
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION)
hitSuccessful = ScreenSpaceProxyRaycastRefraction(ssRayInput, hit);
else
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
hitSuccessful = ScreenSpaceProxyRaycastReflection(ssRayInput, hit);
}
// Perform ray query
ScreenSpaceRayHit hit;
ZERO_INITIALIZE(ScreenSpaceRayHit, hit);
bool hitSuccessful = REFRACTION_SSRAY_QUERY(ssRayInput, hit);
// -------------------------------
// HiZ raymarching
// -------------------------------
else if (projectionModel == PROJECTIONMODEL_HI_Z)
{
ScreenSpaceRaymarchInput ssRayInput;
ZERO_INITIALIZE(ScreenSpaceRaymarchInput, ssRayInput);
// Jitter the ray origin to trade some noise instead of banding effect
ssRayInput.rayOriginWS = rayOriginWS + rayDirWS * SampleBayer4(posInput.positionSS + uint2(_FrameCount, uint(_FrameCount) / 4u)) * 0.1;
ssRayInput.rayDirWS = rayDirWS;
#if DEBUG_DISPLAY
ssRayInput.debug = debug;
#endif
#if HAS_REFRACTION
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION)
hitSuccessful = ScreenSpaceHiZRaymarchRefraction(ssRayInput, hit, hitWeight);
else
#endif
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
hitSuccessful = ScreenSpaceHiZRaymarchReflection(ssRayInput, hit, hitWeight);
}
if (_DebugLightingMode == debugMode
&& _DebugLightingSubMode != DEBUGSCREENSPACETRACING_COLOR)
{
float weight = 1.0;
UpdateLightingHierarchyWeights(hierarchyWeight, weight);
lighting.specularTransmitted = hit.debugOutput;
return lighting;
}
if (_DebugLightingMode == debugMode
&& _DebugLightingSubMode != DEBUGSCREENSPACETRACING_COLOR
&& _DebugLightingSubMode != DEBUGSCREENSPACETRACING_LINEAR_SAMPLED_COLOR
&& _DebugLightingSubMode != DEBUGSCREENSPACETRACING_HI_ZSAMPLED_COLOR
)
{
float weight = 1.0;
UpdateLightingHierarchyWeights(hierarchyWeight, weight);
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION)
lighting.specularTransmitted = hit.debugOutput;
else if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
lighting.specularReflected = hit.debugOutput;
return lighting;
}
if (!hitSuccessful)
return lighting;
if (!hitSuccessful)
return lighting;
float2 weightNDC = clamp(min(hit.positionNDC, 1 - hit.positionNDC) * _SSRefractionInvScreenWeightDistance, 0, 1);
// -------------------------------
// Resolve weight and color
// -------------------------------
// Fade pixels near the texture buffers' borders
float2 weightNDC = clamp(min(hit.positionNDC, 1 - hit.positionNDC) * invScreenWeightDistance, 0, 1);
float weight = weightNDC.x * weightNDC.y;
// TODO: Fade pixels with normal non facing the ray direction
// 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);
// Exit if texel is out of color buffer
// Or if the texel is from an object in front of the object
if (hitLinearDepth < posInput.linearDepth
|| weight == 0)
{
// Do nothing and don't update the hierarchy weight so we can fall back on refraction probe
return lighting;
}
// Exit if texel is discarded
if (weight == 0)
// Do nothing and don't update the hierarchy weight so we can fall back on refraction probe
return lighting;
UpdateLightingHierarchyWeights(hierarchyWeight, weight); // Shouldn't be needed, but safer in case we decide to change hierarchy priority
UpdateLightingHierarchyWeights(hierarchyWeight, weight); // Shouldn't be needed, but safer in case we decide to change hierarchy priority
float3 preLD = SAMPLE_TEXTURE2D_LOD(
_ColorPyramidTexture,
s_trilinear_clamp_sampler,
hit.positionNDC * _ColorPyramidScale.xy,
preLightData.transparentSSMipLevel
).rgb;
// Reproject color pyramid
float4 hitVelocityBuffer = LOAD_TEXTURE2D_LOD(
_CameraMotionVectorsTexture,
hit.positionSS,
0.0
);
// We use specularFGD as an approximation of the fresnel effect (that also handle smoothness), so take the remaining for transmission
float3 F = preLightData.specularFGD;
lighting.specularTransmitted = (1.0 - F) * preLD.rgb * preLightData.transparentTransmittance * weight;
#else
// No refraction, no need to go further
hierarchyWeight = 1.0;
float2 hitVelocityNDC;
DecodeVelocity(hitVelocityBuffer, hitVelocityNDC);
float3 preLD = SAMPLE_TEXTURE2D_LOD(
_ColorPyramidTexture,
s_trilinear_clamp_sampler,
// Offset by half a texel to properly interpolate between this pixel and its mips
(hit.positionNDC - hitVelocityNDC) * _ColorPyramidScale.xy + _ColorPyramidSize.zw * 0.5,
mipLevel
).rgb;
// With HiZ, we use a temporal filtering to reduce the noise from the ray origin jittering
if (projectionModel == PROJECTIONMODEL_HI_Z)
{
float4 currentVelocityBuffer = LOAD_TEXTURE2D_LOD(
_CameraMotionVectorsTexture,
posInput.positionSS,
0.0
);
float2 currentVelocityNDC;
DecodeVelocity(currentVelocityBuffer, currentVelocityNDC);
float3 currentLD = LOAD_TEXTURE2D_LOD(
_ColorPyramidTexture,
int2(posInput.positionSS) - int2(currentVelocityNDC * _ScreenSize.xy),
0
).rgb;
preLD = preLD * (1.0 - temporalFilteringWeight) + currentLD * temporalFilteringWeight;
}
// We use specularFGD as an approximation of the fresnel effect (that also handle smoothness)
float3 F = preLightData.specularFGD;
// -------------------------------
// Assign color
// -------------------------------
#if HAS_REFRACTION
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION)
lighting.specularTransmitted = (1.0 - F) * preLD.rgb * preLightData.transparentTransmittance * weight;
else
break;
}
case GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION:
{
break;
}
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
lighting.specularReflected = F * preLD.rgb * weight;
#ifdef DEBUG_DISPLAY
if (debug)
{
ScreenSpaceTracingDebug debug = _DebugScreenSpaceTracingData[0];
debug.lightingSampledColor = preLD;
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION)
debug.lightingSpecularFGD = 1.0 - F;
else if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
debug.lightingSpecularFGD = F;
debug.lightingWeight = weight;
_DebugScreenSpaceTracingData[0] = debug;
if (_DebugLightingMode == debugMode
&& (_DebugLightingSubMode == DEBUGSCREENSPACETRACING_LINEAR_SAMPLED_COLOR
|| _DebugLightingSubMode == DEBUGSCREENSPACETRACING_HI_ZSAMPLED_COLOR))
{
float weight = 1.0;
UpdateLightingHierarchyWeights(hierarchyWeight, weight);
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION)
lighting.specularTransmitted = preLD.rgb;
else if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
lighting.specularReflected = preLD.rgb;
return lighting;
}
#endif
return lighting;
}

positionWS = preLightData.transparentPositionWS;
R = preLightData.transparentRefractV;
}
else
{
if ((lightData.envIndex & 1) == ENVCACHETYPE_CUBEMAP)
{
R = GetSpecularDominantDir(bsdfData.normalWS, R, preLightData.iblPerceptualRoughness, ClampNdotV(preLightData.NdotV));
// When we are rough, we tend to see outward shifting of the reflection when at the boundary of the projection volume
// Also it appear like more sharp. To avoid these artifact and at the same time get better match to reference we lerp to original unmodified reflection.
// Formula is empirical.
float roughness = PerceptualRoughnessToRoughness(preLightData.iblPerceptualRoughness);
R = lerp(R, preLightData.iblR, saturate(smoothstep(0, 1, roughness * roughness)));
}
}
// Note: using influenceShapeType and projectionShapeType instead of (lightData|proxyData).shapeType allow to make compiler optimization in case the type is know (like for sky)
EvaluateLight_EnvIntersection(positionWS, bsdfData.normalWS, lightData, influenceShapeType, R, weight);

float unusedWeight = 0.0;
EvaluateLight_EnvIntersection(positionWS, bsdfData.normalWS, lightData, influenceShapeType, coatR, unusedWeight);
}
// When we are rough, we tend to see outward shifting of the reflection when at the boundary of the projection volume
// Also it appear like more sharp. To avoid these artifact and at the same time get better match to reference we lerp to original unmodified reflection.
// Formula is empirical.
float roughness = PerceptualRoughnessToRoughness(preLightData.iblPerceptualRoughness);
R = lerp(R, preLightData.iblR, saturate(smoothstep(0, 1, roughness * roughness)));
float3 F = preLightData.specularFGD;

if (_DebugLightingMode != 0)
{
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
bool keepSpecular = false;
switch (_DebugLightingMode)
{

case DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFRACTION:
if (_DebugLightingSubMode != DEBUGSCREENSPACETRACING_COLOR)
diffuseLighting = lighting.indirect.specularTransmitted;
else
keepSpecular = true;
break;
case DEBUGLIGHTINGMODE_SCREEN_SPACE_TRACING_REFLECTION:
if (_DebugLightingSubMode != DEBUGSCREENSPACETRACING_COLOR)
diffuseLighting = lighting.indirect.specularReflected;
else
keepSpecular = true;
if (!keepSpecular)
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
}
else if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE)
{

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


// Transparency
[Enum(None, 0, Plane, 1, Sphere, 2)]_RefractionModel("Refraction Model", Int) = 0
[Enum(Proxy, 1, HiZ, 2)]_RefractionSSRayModel("Refraction SSRay Model", Int) = 0
[Enum(Proxy, 1, HiZ, 2)]_SSRefractionProjectionModel("Refraction Projection Model", Int) = 0
_Ior("Index Of Refraction", Range(1.0, 2.5)) = 1.0
_ThicknessMultiplier("Thickness Multiplier", Float) = 1.0
_TransmittanceColor("Transmittance Color", Color) = (1.0, 1.0, 1.0)

[ToggleUI] _DisplacementLockObjectScale("displacement lock object scale", Float) = 1.0
[ToggleUI] _DisplacementLockTilingScale("displacement lock tiling scale", Float) = 1.0
[ToggleUI] _DepthOffsetEnable("Depth Offset View space", Float) = 0.0
[ToggleUI] _EnableGeometricSpecularAA("EnableGeometricSpecularAA", Float) = 0.0
_SpecularAAScreenSpaceVariance("SpecularAAScreenSpaceVariance", Range(0.0, 1.0)) = 0.1
_SpecularAAThreshold("SpecularAAThreshold", Range(0.0, 1.0)) = 0.2
[ToggleUI] _EnableMotionVectorForVertexAnimation("EnableMotionVectorForVertexAnimation", Float) = 0.0

#pragma shader_feature _TRANSMITTANCECOLORMAP
#pragma shader_feature _DISABLE_DBUFFER
#pragma shader_feature _ENABLE_GEOMETRIC_SPECULAR_AA
// Keyword for transparent
#pragma shader_feature _SURFACE_TYPE_TRANSPARENT

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


}
#endif
#ifdef _ENABLE_GEOMETRIC_SPECULAR_AA
// Specular AA
surfaceData.perceptualSmoothness = GeometricFilterPerceptualSmoothness(surfaceData.perceptualSmoothness, input.worldToTangent[2], _SpecularAAScreenSpaceVariance, _SpecularAAThreshold);
#endif
// Caution: surfaceData must be fully initialize before calling GetBuiltinData
GetBuiltinData(input, surfaceData, alpha, bentNormalWS, depthOffset, builtinData);
}

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


float _ShiverDrag;
float _ShiverDirectionality;
// Specular AA
float _EnableGeometricSpecularAA;
float _SpecularAAScreenSpaceVariance;
float _SpecularAAThreshold;
#ifndef LAYERED_LIT_SHADER
// Set of users variables

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


// Transparency
[Enum(None, 0, Plane, 1, Sphere, 2)]_RefractionModel("Refraction Model", Int) = 0
[Enum(Proxy, 1, HiZ, 2)]_RefractionSSRayModel("Refraction SSRay Model", Int) = 0
[Enum(Proxy, 1, HiZ, 2)]_SSRefractionProjectionModel("Refraction Projection Model", Int) = 0
_Ior("Index Of Refraction", Range(1.0, 2.5)) = 1.0
_ThicknessMultiplier("Thickness Multiplier", Float) = 1.0
_TransmittanceColor("Transmittance Color", Color) = (1.0, 1.0, 1.0)

[ToggleUI] _DisplacementLockObjectScale("displacement lock object scale", Float) = 1.0
[ToggleUI] _DisplacementLockTilingScale("displacement lock tiling scale", Float) = 1.0
[ToggleUI] _DepthOffsetEnable("Depth Offset View space", Float) = 0.0
[ToggleUI] _EnableGeometricSpecularAA("EnableGeometricSpecularAA", Float) = 0.0
_SpecularAAScreenSpaceVariance("SpecularAAScreenSpaceVariance", Range(0.0, 1.0)) = 0.1
_SpecularAAThreshold("SpecularAAThreshold", Range(0.0, 1.0)) = 0.2
[ToggleUI] _EnableMotionVectorForVertexAnimation("EnableMotionVectorForVertexAnimation", Float) = 0.0

#pragma shader_feature _TRANSMITTANCECOLORMAP
#pragma shader_feature _DISABLE_DBUFFER
#pragma shader_feature _ENABLE_GEOMETRIC_SPECULAR_AA
// Keyword for transparent
#pragma shader_feature _SURFACE_TYPE_TRANSPARENT

19
com.unity.render-pipelines.high-definition/HDRP/ShaderVariables.hlsl


float4 _SinTime; // { sin(t/8), sin(t/4), sin(t/2), sin(t) }
float4 _CosTime; // { cos(t/8), cos(t/4), cos(t/2), cos(t) }
float4 unity_DeltaTime; // { dt, 1/dt, smoothdt, 1/smoothdt }
int _FrameCount;
// Volumetric lighting.
float4 _AmbientProbeCoeffs[7]; // 3 bands of SH, packed, rescaled and convolved with the phase function

CBUFFER_START(UnityLightingParameters)
// Buffer pyramid
float4 _ColorPyramidSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size
float4 _DepthPyramidSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size
float4 _ColorPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused
float4 _DepthPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused
float4 _ColorPyramidSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size
float4 _DepthPyramidSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size
float4 _CameraMotionVectorsSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size
float4 _ColorPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused
float4 _DepthPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused
float4 _CameraMotionVectorsScale; // (x,y) = Screen Scale, z = lod count, w = unused
float _SSRefractionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback
float _SSRefractionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback
float _SSReflectionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback
int _SSReflectionEnabled;
int _SSReflectionProjectionModel;
int _SSReflectionHiZRayMarchBehindObject;
int _SSRefractionHiZRayMarchBehindObject;
// Ambiant occlusion
float4 _AmbientOcclusionParam; // xyz occlusion color, w directLightStrenght

TEXTURE2D(_DepthPyramidTexture);
// Ambient occlusion texture
TEXTURE2D(_AmbientOcclusionTexture);
TEXTURE2D(_CameraMotionVectorsTexture);
// Custom generated by HDRP, not from Unity Engine (passed in via HDCamera)
#if defined(USING_STEREO_MATRICES)

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


public class LightweightPipelineAsset : RenderPipelineAsset, ISerializationCallbackReceiver
{
private Shader m_DefaultShader;
public static readonly string m_SearchPathProject = "Assets";
public static readonly string m_SearchPathPackage = "Packages/com.unity.render-pipelines.lightweight";
public static readonly string s_SearchPathProject = "Assets";
public static readonly string s_SearchPathPackage = "Packages/com.unity.render-pipelines.lightweight";
Shader m_DefaultShader;
[SerializeField] private int kAssetVersion = 3;
[SerializeField] private int m_MaxPixelLights = 4;
[SerializeField] private bool m_SupportsVertexLight = false;
[SerializeField] private bool m_RequireDepthTexture = false;
[SerializeField] private bool m_RequireSoftParticles = false;
[SerializeField] private bool m_RequireOpaqueTexture = false;
[SerializeField] private Downsampling m_OpaqueDownsampling = Downsampling._2xBilinear;
[SerializeField] private bool m_SupportsHDR = false;
[SerializeField] private MSAAQuality m_MSAA = MSAAQuality._4x;
[SerializeField] private float m_RenderScale = 1.0f;
[SerializeField] int k_AssetVersion = 3;
[SerializeField] int m_MaxPixelLights = 4;
[SerializeField] bool m_SupportsVertexLight = false;
[SerializeField] bool m_RequireDepthTexture = false;
[SerializeField] bool m_RequireSoftParticles = false;
[SerializeField] bool m_RequireOpaqueTexture = false;
[SerializeField] Downsampling m_OpaqueDownsampling = Downsampling._2xBilinear;
[SerializeField] bool m_SupportsHDR = false;
[SerializeField] MSAAQuality m_MSAA = MSAAQuality._4x;
[SerializeField] float m_RenderScale = 1.0f;
[SerializeField] bool m_SupportsDynamicBatching = true;
[SerializeField] private bool m_DirectionalShadowsSupported = true;
[SerializeField] private ShadowResolution m_ShadowAtlasResolution = ShadowResolution._2048;
[SerializeField] private float m_ShadowDistance = 50.0f;
[SerializeField] private ShadowCascades m_ShadowCascades = ShadowCascades.FOUR_CASCADES;
[SerializeField] private float m_Cascade2Split = 0.25f;
[SerializeField] private Vector3 m_Cascade4Split = new Vector3(0.067f, 0.2f, 0.467f);
[SerializeField] private bool m_LocalShadowsSupported = true;
[SerializeField] private ShadowResolution m_LocalShadowsAtlasResolution = ShadowResolution._512;
[SerializeField] private bool m_SoftShadowsSupported = false;
[SerializeField] bool m_DirectionalShadowsSupported = true;
[SerializeField] ShadowResolution m_ShadowAtlasResolution = ShadowResolution._2048;
[SerializeField] float m_ShadowDistance = 50.0f;
[SerializeField] ShadowCascades m_ShadowCascades = ShadowCascades.FOUR_CASCADES;
[SerializeField] float m_Cascade2Split = 0.25f;
[SerializeField] Vector3 m_Cascade4Split = new Vector3(0.067f, 0.2f, 0.467f);
[SerializeField] bool m_LocalShadowsSupported = true;
[SerializeField] ShadowResolution m_LocalShadowsAtlasResolution = ShadowResolution._512;
[SerializeField] bool m_SoftShadowsSupported = false;
[SerializeField] bool m_CustomShaderVariantStrippingSettings = false;
[SerializeField] bool m_KeepAdditionalLightVariants = true;
[SerializeField] bool m_KeepVertexLightVariants = true;
[SerializeField] bool m_KeepDirectionalShadowVariants = true;
[SerializeField] bool m_KeepLocalShadowVariants = true;
[SerializeField] bool m_KeepSoftShadowVariants = true;
[SerializeField]
private LightweightPipelineResources m_ResourcesAsset;
[SerializeField] LightweightPipelineResources m_ResourcesAsset;
[SerializeField] private ShadowType m_ShadowType = ShadowType.HARD_SHADOWS;
[SerializeField] ShadowType m_ShadowType = ShadowType.HARD_SHADOWS;
private LightweightPipelineEditorResources m_EditorResourcesAsset;
LightweightPipelineEditorResources m_EditorResourcesAsset;
[MenuItem("Assets/Create/Rendering/Lightweight Pipeline Asset", priority = CoreUtils.assetCreateMenuPriority1)]
static void CreateLightweightPipeline()

}
}
private static T LoadResourceFile<T>() where T : ScriptableObject
static T LoadResourceFile<T>() where T : ScriptableObject
var guids = AssetDatabase.FindAssets(typeof(T).Name + " t:scriptableobject", new[] {m_SearchPathProject});
var guids = AssetDatabase.FindAssets(typeof(T).Name + " t:scriptableobject", new[] {s_SearchPathProject});
foreach (string guid in guids)
{
string path = AssetDatabase.GUIDToAssetPath(guid);

// There's currently an issue that prevents FindAssets from find resources withing the package folder.
if (resourceAsset == null)
{
string path = m_SearchPathPackage + "/LWRP/Data/" + typeof(T).Name + ".asset";
string path = s_SearchPathPackage + "/LWRP/Data/" + typeof(T).Name + ".asset";
resourceAsset = AssetDatabase.LoadAssetAtPath<T>(path);
}
return resourceAsset;

return new LightweightPipeline(this);
}
private Material GetMaterial(DefaultMaterialType materialType)
Material GetMaterial(DefaultMaterialType materialType)
{
#if UNITY_EDITOR
if (editorResources == null)

public int GetAssetVersion()
{
return kAssetVersion;
return k_AssetVersion;
public int MaxPixelLights
public int maxPixelLights
public bool SupportsVertexLight
public bool supportsVertexLight
public bool RequireDepthTexture
public bool supportsCameraDepthTexture
public bool RequireSoftParticles
public bool supportsSoftParticles
public bool RequireOpaqueTexture
public bool supportsCameraOpaqueTexture
public Downsampling OpaqueDownsampling
public Downsampling opaqueDownsampling
public bool SupportsHDR
public bool supportsHDR
public int MSAASampleCount
public int msaaSampleCount
public float RenderScale
public float renderScale
set { m_RenderScale = value; }
public bool SupportsDirectionalShadows
public bool supportsDynamicBatching
{
get { return m_SupportsDynamicBatching; }
}
public bool supportsDirectionalShadows
public int DirectionalShadowAtlasResolution
public int directionalShadowAtlasResolution
public float ShadowDistance
public float shadowDistance
set { m_ShadowDistance = value; }
public int CascadeCount
public int cascadeCount
{
get
{

}
}
public float Cascade2Split
public float cascade2Split
public Vector3 Cascade4Split
public Vector3 cascade4Split
public bool SupportsLocalShadows
public bool supportsLocalShadows
public int LocalShadowAtlasResolution
public int localShadowAtlasResolution
public bool SupportsSoftShadows
public bool supportsSoftShadows
public bool customShaderVariantStripping
{
get { return m_CustomShaderVariantStrippingSettings; }
}
public bool keepAdditionalLightVariants
{
get { return m_KeepAdditionalLightVariants; }
}
public bool keepVertexLightVariants
{
get { return m_KeepVertexLightVariants; }
}
public bool keepDirectionalShadowVariants
{
get { return m_KeepDirectionalShadowVariants; }
}
public bool keepLocalShadowVariants
{
get { return m_KeepLocalShadowVariants; }
}
public bool keepSoftShadowVariants
{
get { return m_KeepSoftShadowVariants; }
}
public override Material GetDefaultMaterial()
{
return GetMaterial(DefaultMaterialType.Standard);

return m_DefaultShader;
}
public Shader BlitShader
public Shader blitShader
public Shader CopyDepthShader
public Shader copyDepthShader
public Shader ScreenSpaceShadowShader
public Shader screenSpaceShadowShader
public Shader SamplingShader
public Shader samplingShader
{
get { return resources != null ? resources.SamplingShader : null; }
}

public void OnAfterDeserialize()
{
if (kAssetVersion < 3)
if (k_AssetVersion < 3)
kAssetVersion = 3;
k_AssetVersion = 3;
m_SoftShadowsSupported = (m_ShadowType == ShadowType.SOFT_SHADOWS);
}
}

130
com.unity.render-pipelines.lightweight/LWRP/Editor/LightweightCameraEditor.cs


public readonly string mssaDisabledWarning = "Anti Aliasing is disabled in Lightweight Pipeline settings.";
};
private static readonly int[] kRenderingPathValues = {0};
private static Styles s_Styles;
private LightweightPipelineAsset lightweightPipeline;
public Camera camera { get { return target as Camera; } }
private Camera camera { get { return target as Camera; } }
// Animation Properties
public bool isSameClearFlags { get { return !settings.clearFlags.hasMultipleDifferentValues; } }
public bool isSameOrthographic { get { return !settings.orthographic.hasMultipleDifferentValues; } }
// Animation Properties
private bool IsSameClearFlags { get { return !settings.clearFlags.hasMultipleDifferentValues; } }
private bool IsSameOrthographic { get { return !settings.orthographic.hasMultipleDifferentValues; } }
static readonly int[] s_RenderingPathValues = {0};
static Styles s_Styles;
LightweightPipelineAsset m_LightweightPipeline;
readonly AnimBool showBGColorAnim = new AnimBool();
readonly AnimBool showOrthoAnim = new AnimBool();
readonly AnimBool showTargetEyeAnim = new AnimBool();
readonly AnimBool m_ShowBGColorAnim = new AnimBool();
readonly AnimBool m_ShowOrthoAnim = new AnimBool();
readonly AnimBool m_ShowTargetEyeAnim = new AnimBool();
void SetAnimationTarget(AnimBool anim, bool initialize, bool targetValue)
{

void UpdateAnimationValues(bool initialize)
{
SetAnimationTarget(showBGColorAnim, initialize, IsSameClearFlags && (camera.clearFlags == CameraClearFlags.SolidColor || camera.clearFlags == CameraClearFlags.Skybox));
SetAnimationTarget(showOrthoAnim, initialize, IsSameOrthographic && camera.orthographic);
SetAnimationTarget(showTargetEyeAnim, initialize, settings.targetEye.intValue != (int)StereoTargetEyeMask.Both || PlayerSettings.virtualRealitySupported);
SetAnimationTarget(m_ShowBGColorAnim, initialize, isSameClearFlags && (camera.clearFlags == CameraClearFlags.SolidColor || camera.clearFlags == CameraClearFlags.Skybox));
SetAnimationTarget(m_ShowOrthoAnim, initialize, isSameOrthographic && camera.orthographic);
SetAnimationTarget(m_ShowTargetEyeAnim, initialize, settings.targetEye.intValue != (int)StereoTargetEyeMask.Both || PlayerSettings.virtualRealitySupported);
lightweightPipeline = GraphicsSettings.renderPipelineAsset as LightweightPipelineAsset;
m_LightweightPipeline = GraphicsSettings.renderPipelineAsset as LightweightPipelineAsset;
settings.OnEnable();
UpdateAnimationValues(true);

{
showBGColorAnim.valueChanged.RemoveListener(Repaint);
showOrthoAnim.valueChanged.RemoveListener(Repaint);
showTargetEyeAnim.valueChanged.RemoveListener(Repaint);
m_ShowBGColorAnim.valueChanged.RemoveListener(Repaint);
m_ShowOrthoAnim.valueChanged.RemoveListener(Repaint);
m_ShowTargetEyeAnim.valueChanged.RemoveListener(Repaint);
lightweightPipeline = null;
m_LightweightPipeline = null;
private void DrawRenderingPath()
public override void OnInspectorGUI()
{
if (s_Styles == null)
s_Styles = new Styles();
settings.Update();
UpdateAnimationValues(false);
settings.DrawClearFlags();
using (var group = new EditorGUILayout.FadeGroupScope(m_ShowBGColorAnim.faded))
if (group.visible) settings.DrawBackgroundColor();
settings.DrawCullingMask();
EditorGUILayout.Space();
settings.DrawProjection();
settings.DrawClippingPlanes();
settings.DrawNormalizedViewPort();
EditorGUILayout.Space();
settings.DrawDepth();
DrawRenderingPath();
DrawTargetTexture();
settings.DrawOcclusionCulling();
DrawHDR();
DrawMSAA();
settings.DrawVR();
settings.DrawMultiDisplay();
using (var group = new EditorGUILayout.FadeGroupScope(m_ShowTargetEyeAnim.faded))
if (group.visible) settings.DrawTargetEye();
settings.ApplyModifiedProperties();
}
void DrawRenderingPath()
EditorGUILayout.IntPopup(s_Styles.renderingPathLabel, 0, s_Styles.renderingPathOptions, kRenderingPathValues);
EditorGUILayout.IntPopup(s_Styles.renderingPathLabel, 0, s_Styles.renderingPathOptions, s_RenderingPathValues);
private void DrawHDR()
void DrawHDR()
if (settings.HDR.boolValue && !lightweightPipeline.SupportsHDR)
if (settings.HDR.boolValue && !m_LightweightPipeline.supportsHDR)
private void DrawTargetTexture()
void DrawTargetTexture()
{
EditorGUILayout.PropertyField(settings.targetTexture);

int pipelineSamplesCount = lightweightPipeline.MSAASampleCount;
int pipelineSamplesCount = m_LightweightPipeline.msaaSampleCount;
if (texture && texture.antiAliasing > pipelineSamplesCount)
{

MessageType.Warning, true);
if (GUILayout.Button(s_Styles.fixNow))
lightweightPipeline.MSAASampleCount = texture.antiAliasing;
m_LightweightPipeline.msaaSampleCount = texture.antiAliasing;
private void DrawMSAA()
void DrawMSAA()
if (settings.allowMSAA.boolValue && lightweightPipeline.MSAASampleCount <= 1)
if (settings.allowMSAA.boolValue && m_LightweightPipeline.msaaSampleCount <= 1)
lightweightPipeline.MSAASampleCount = 4;
m_LightweightPipeline.msaaSampleCount = 4;
}
public override void OnInspectorGUI()
{
if (s_Styles == null)
s_Styles = new Styles();
settings.Update();
UpdateAnimationValues(false);
settings.DrawClearFlags();
using (var group = new EditorGUILayout.FadeGroupScope(showBGColorAnim.faded))
if (group.visible) settings.DrawBackgroundColor();
settings.DrawCullingMask();
EditorGUILayout.Space();
settings.DrawProjection();
settings.DrawClippingPlanes();
settings.DrawNormalizedViewPort();
EditorGUILayout.Space();
settings.DrawDepth();
DrawRenderingPath();
DrawTargetTexture();
settings.DrawOcclusionCulling();
DrawHDR();
DrawMSAA();
settings.DrawVR();
settings.DrawMultiDisplay();
using (var group = new EditorGUILayout.FadeGroupScope(showTargetEyeAnim.faded))
if (group.visible) settings.DrawTargetEye();
settings.ApplyModifiedProperties();
}
}
}

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


[CustomEditorForRenderPipeline(typeof(Light), typeof(LightweightPipelineAsset))]
class LightweightLightEditor : LightEditor
{
AnimBool animShowSpotOptions = new AnimBool();
AnimBool animShowPointOptions = new AnimBool();
AnimBool animShowDirOptions = new AnimBool();
AnimBool animShowAreaOptions = new AnimBool();
AnimBool animShowRuntimeOptions = new AnimBool();
AnimBool animShowShadowOptions = new AnimBool();
AnimBool animBakedShadowAngleOptions = new AnimBool();
AnimBool animBakedShadowRadiusOptions = new AnimBool();
AnimBool animShowLightBounceIntensity = new AnimBool();
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();
class Styles
{

static Styles s_Styles;
private bool TypeIsSame { get { return !settings.lightType.hasMultipleDifferentValues; } }
private bool ShadowTypeIsSame { get { return !settings.shadowsType.hasMultipleDifferentValues; } }
private bool LightmappingTypeIsSame { get { return !settings.lightmapping.hasMultipleDifferentValues; } }
private Light LightProperty { get { return target as Light; } }
public bool typeIsSame { get { return !settings.lightType.hasMultipleDifferentValues; } }
public bool shadowTypeIsSame { get { return !settings.shadowsType.hasMultipleDifferentValues; } }
public bool lightmappingTypeIsSame { get { return !settings.lightmapping.hasMultipleDifferentValues; } }
public Light lightProperty { get { return target as Light; } }
private bool SpotOptionsValue { get { return TypeIsSame && LightProperty.type == LightType.Spot; } }
private bool PointOptionsValue { get { return TypeIsSame && LightProperty.type == LightType.Point; } }
private bool DirOptionsValue { get { return TypeIsSame && LightProperty.type == LightType.Directional; } }
private bool AreaOptionsValue { get { return TypeIsSame && LightProperty.type == LightType.Area; } }
public bool spotOptionsValue { get { return typeIsSame && lightProperty.type == LightType.Spot; } }
public bool pointOptionsValue { get { return typeIsSame && lightProperty.type == LightType.Point; } }
public bool dirOptionsValue { get { return typeIsSame && lightProperty.type == LightType.Directional; } }
public bool areaOptionsValue { get { return typeIsSame && lightProperty.type == LightType.Area; } }
private bool RuntimeOptionsValue { get { return TypeIsSame && (LightProperty.type != LightType.Area && LightProperty.type != LightType.Point && !settings.isCompletelyBaked); } }
private bool BakedShadowRadius { get { return TypeIsSame && (LightProperty.type == LightType.Point || LightProperty.type == LightType.Spot) && settings.isBakedOrMixed; } }
private bool BakedShadowAngle { get { return TypeIsSame && LightProperty.type == LightType.Directional && settings.isBakedOrMixed; } }
private bool ShadowOptionsValue { get { return ShadowTypeIsSame && LightProperty.shadows != LightShadows.None; } }
public bool runtimeOptionsValue { get { return typeIsSame && (lightProperty.type != LightType.Area && lightProperty.type != LightType.Point && !settings.isCompletelyBaked); } }
public bool bakedShadowRadius { get { return typeIsSame && (lightProperty.type == LightType.Point || lightProperty.type == LightType.Spot) && settings.isBakedOrMixed; } }
public bool bakedShadowAngle { get { return typeIsSame && lightProperty.type == LightType.Directional && settings.isBakedOrMixed; } }
public bool shadowOptionsValue { get { return shadowTypeIsSame && lightProperty.shadows != LightShadows.None; } }
private bool BakingWarningValue { get { return !UnityEditor.Lightmapping.bakedGI && LightmappingTypeIsSame && settings.isBakedOrMixed; } }
private bool ShowLightBounceIntensity { get { return true; } }
private bool CookieWarningValue
public bool bakingWarningValue { get { return !UnityEditor.Lightmapping.bakedGI && lightmappingTypeIsSame && settings.isBakedOrMixed; } }
public bool showLightBounceIntensity { get { return true; } }
public bool cookieWarningValue
return TypeIsSame && LightProperty.type == LightType.Spot &&
return typeIsSame && lightProperty.type == LightType.Spot &&
private bool IsShadowEnabled { get { return settings.shadowsType.intValue != 0; } }
public bool isShadowEnabled { get { return settings.shadowsType.intValue != 0; } }
private bool RealtimeShadowsWarningValue
public bool realtimeShadowsWarningValue
return TypeIsSame && LightProperty.type == LightType.Point &&
ShadowTypeIsSame && IsShadowEnabled &&
LightmappingTypeIsSame && !settings.isCompletelyBaked;
return typeIsSame && lightProperty.type == LightType.Point &&
shadowTypeIsSame && isShadowEnabled &&
lightmappingTypeIsSame && !settings.isCompletelyBaked;
private void SetOptions(AnimBool animBool, bool initialize, bool targetValue)
{
if (initialize)
{
animBool.value = targetValue;
animBool.valueChanged.AddListener(Repaint);
}
else
{
animBool.target = targetValue;
}
}
private void UpdateShowOptions(bool initialize)
{
SetOptions(animShowSpotOptions, initialize, SpotOptionsValue);
SetOptions(animShowPointOptions, initialize, PointOptionsValue);
SetOptions(animShowDirOptions, initialize, DirOptionsValue);
SetOptions(animShowAreaOptions, initialize, AreaOptionsValue);
SetOptions(animShowShadowOptions, initialize, ShadowOptionsValue);
SetOptions(animShowRuntimeOptions, initialize, RuntimeOptionsValue);
SetOptions(animBakedShadowAngleOptions, initialize, BakedShadowAngle);
SetOptions(animBakedShadowRadiusOptions, initialize, BakedShadowRadius);
SetOptions(animShowLightBounceIntensity, initialize, ShowLightBounceIntensity);
}
protected override void OnEnable()
{
settings.OnEnable();

public void DrawSpotAngle()
{
EditorGUILayout.Slider(settings.spotAngle, 1f, 179f, s_Styles.SpotAngle);
}
public void DrawCookie()
{
EditorGUILayout.PropertyField(settings.cookieProp, s_Styles.Cookie);
if (CookieWarningValue)
{
// warn on spotlights if the cookie is set to repeat
EditorGUILayout.HelpBox(s_Styles.CookieWarning.text, MessageType.Warning);
}
}
public void DrawCookieSize()
{
EditorGUILayout.PropertyField(settings.cookieSize, s_Styles.CookieSize);
}
public override void OnInspectorGUI()
{
if (s_Styles == null)

// 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 - animShowDirOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(1.0f - m_AnimShowDirOptions.faded))
settings.DrawRange(animShowAreaOptions.target);
settings.DrawRange(m_AnimShowAreaOptions.target);
using (var group = new EditorGUILayout.FadeGroupScope(animShowSpotOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(m_AnimShowSpotOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(animShowAreaOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(m_AnimShowAreaOptions.faded))
if (group.visible)
settings.DrawArea();

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

serializedObject.ApplyModifiedProperties();
}
void SetOptions(AnimBool animBool, bool initialize, bool targetValue)
{
if (initialize)
{
animBool.value = targetValue;
animBool.valueChanged.AddListener(Repaint);
}
else
{
animBool.target = targetValue;
}
}
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);
}
void DrawSpotAngle()
{
EditorGUILayout.Slider(settings.spotAngle, 1f, 179f, s_Styles.SpotAngle);
}
void DrawCookie()
{
EditorGUILayout.PropertyField(settings.cookieProp, s_Styles.Cookie);
if (cookieWarningValue)
{
// warn on spotlights if the cookie is set to repeat
EditorGUILayout.HelpBox(s_Styles.CookieWarning.text, MessageType.Warning);
}
}
void DrawCookieSize()
{
EditorGUILayout.PropertyField(settings.cookieSize, s_Styles.CookieSize);
}
float show = 1.0f - animShowAreaOptions.faded;
float show = 1.0f - m_AnimShowAreaOptions.faded;
show *= animShowShadowOptions.faded;
show *= m_AnimShowShadowOptions.faded;
using (var group = new EditorGUILayout.FadeGroupScope(show * animBakedShadowRadiusOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(show * m_AnimBakedShadowRadiusOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(show * animBakedShadowAngleOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(show * m_AnimBakedShadowAngleOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(show * animShowRuntimeOptions.faded))
using (var group = new EditorGUILayout.FadeGroupScope(show * m_AnimShowRuntimeOptions.faded))
if (BakingWarningValue)
if (bakingWarningValue)
if (RealtimeShadowsWarningValue)
if (realtimeShadowsWarningValue)
EditorGUILayout.HelpBox(s_Styles.ShadowsNotSupportedWarning.text, MessageType.Warning);
EditorGUILayout.Space();

978
com.unity.render-pipelines.lightweight/LWRP/LightweightPipeline.cs
文件差异内容过多而无法显示
查看文件

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


using System;
using System.Collections.Generic;
using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.XR;
public enum FrameRenderingConfiguration
{
None = (0 << 0),
Stereo = (1 << 0),
Msaa = (1 << 1),
BeforeTransparentPostProcess = (1 << 2),
PostProcess = (1 << 3),
DepthPrePass = (1 << 4),
DepthCopy = (1 << 5),
DefaultViewport = (1 << 6),
IntermediateTexture = (1 << 7)
}
[Flags]
public enum PipelineCapabilities
{
AdditionalLights = (1 << 0),

SoftShadows = (1 << 4),
}
public enum MixedLightingSetup
{
None,
ShadowMask,
Subtractive,
};
public struct RenderingData
{
public CameraData cameraData;
public LightData lightData;
public ShadowData shadowData;
public bool supportsDynamicBatching;
}
public struct LightData
{
public int pixelAdditionalLightsCount;
public int totalAdditionalLightsCount;
public int mainLightIndex;
public List<VisibleLight> visibleLights;
public List<int> visibleLocalLightIndices;
}
public struct CameraData
{
public Camera camera;
public float renderScale;
public int msaaSamples;
public bool isSceneViewCamera;
public bool isDefaultViewport;
public bool isOffscreenRender;
public bool isHdrEnabled;
public bool requiresDepthTexture;
public bool requiresSoftParticles;
public bool requiresOpaqueTexture;
public Downsampling opaqueTextureDownsampling;
public bool isStereoEnabled;
public float maxShadowDistance;
public bool postProcessEnabled;
public PostProcessLayer postProcessLayer;
}
public struct ShadowData
{
public bool renderDirectionalShadows;
public bool requiresScreenSpaceShadowResolve;
public int directionalShadowAtlasWidth;
public int directionalShadowAtlasHeight;
public int directionalLightCascadeCount;
public Vector3 directionalLightCascades;
public bool renderLocalShadows;
public int localShadowAtlasWidth;
public int localShadowAtlasHeight;
public bool supportsSoftShadows;
public int bufferBitCount;
public LightShadows renderedDirectionalShadowQuality;
public LightShadows renderedLocalShadowQuality;
}
public class CameraComparer : IComparer<Camera>

}
}
public class LightweightKeywords
public static class LightweightKeywords
{
public static readonly string AdditionalLightsText = "_ADDITIONAL_LIGHTS";
public static readonly string VertexLightsText = "_VERTEX_LIGHTS";

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 DepthNoMsaa = "_DEPTH_NO_MSAA";
public static readonly string DepthMsaa2 = "_DEPTH_MSAA_2";
public static readonly string DepthMsaa4 = "_DEPTH_MSAA_4";
#if UNITY_2018_2_OR_NEWER
public static readonly ShaderKeyword AdditionalLights = new ShaderKeyword(AdditionalLightsText);

{
s_PipelineCapabilities = 0U;
if (pipelineAsset.MaxPixelLights > 1 || pipelineAsset.SupportsVertexLight)
s_PipelineCapabilities |= PipelineCapabilities.AdditionalLights;
// Strip variants based on selected pipeline features
if (!pipelineAsset.customShaderVariantStripping)
{
if (pipelineAsset.maxPixelLights > 1 || pipelineAsset.supportsVertexLight)
s_PipelineCapabilities |= PipelineCapabilities.AdditionalLights;
if (pipelineAsset.SupportsVertexLight)
s_PipelineCapabilities |= PipelineCapabilities.VertexLights;
if (pipelineAsset.supportsVertexLight)
s_PipelineCapabilities |= PipelineCapabilities.VertexLights;
if (pipelineAsset.SupportsDirectionalShadows)
s_PipelineCapabilities |= PipelineCapabilities.DirectionalShadows;
if (pipelineAsset.supportsDirectionalShadows)
s_PipelineCapabilities |= PipelineCapabilities.DirectionalShadows;
if (pipelineAsset.SupportsLocalShadows)
s_PipelineCapabilities |= PipelineCapabilities.LocalShadows;
if (pipelineAsset.supportsLocalShadows)
s_PipelineCapabilities |= PipelineCapabilities.LocalShadows;
bool anyShadows = pipelineAsset.SupportsDirectionalShadows || pipelineAsset.SupportsLocalShadows;
if (pipelineAsset.SupportsSoftShadows && anyShadows)
s_PipelineCapabilities |= PipelineCapabilities.SoftShadows;
bool anyShadows = pipelineAsset.supportsDirectionalShadows || pipelineAsset.supportsLocalShadows;
if (pipelineAsset.supportsSoftShadows && anyShadows)
s_PipelineCapabilities |= PipelineCapabilities.SoftShadows;
}
else
{
if (pipelineAsset.keepAdditionalLightVariants)
s_PipelineCapabilities |= PipelineCapabilities.AdditionalLights;
if (pipelineAsset.keepVertexLightVariants)
s_PipelineCapabilities |= PipelineCapabilities.VertexLights;
if (pipelineAsset.keepDirectionalShadowVariants)
s_PipelineCapabilities |= PipelineCapabilities.DirectionalShadows;
if (pipelineAsset.keepLocalShadowVariants)
s_PipelineCapabilities |= PipelineCapabilities.LocalShadows;
if (pipelineAsset.keepSoftShadowVariants)
s_PipelineCapabilities |= PipelineCapabilities.SoftShadows;
}
}
public static void DrawFullScreen(CommandBuffer commandBuffer, Material material,

}
public static void StartStereoRendering(Camera camera, ref ScriptableRenderContext context, FrameRenderingConfiguration renderingConfiguration)
{
if (CoreUtils.HasFlag(renderingConfiguration, FrameRenderingConfiguration.Stereo))
context.StartMultiEye(camera);
}
public static void StopStereoRendering(Camera camera, ref ScriptableRenderContext context, FrameRenderingConfiguration renderingConfiguration)
{
if (CoreUtils.HasFlag(renderingConfiguration, FrameRenderingConfiguration.Stereo))
context.StopMultiEye(camera);
}
public static void GetLightCookieMatrix(VisibleLight light, out Matrix4x4 cookieMatrix)

// Remaining light types don't support cookies
}
public static bool IsSupportedShadowType(LightType lightType)
public static void CopyTexture(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier dest, Material material)
return lightType == LightType.Directional || lightType == LightType.Spot;
// TODO: In order to issue a copyTexture we need to also check if source and dest have same size
//if (SystemInfo.copyTextureSupport != CopyTextureSupport.None)
// cmd.CopyTexture(source, dest);
//else
cmd.Blit(source, dest, material);
public static bool IsSupportedCookieType(LightType lightType)
public static bool IsSupportedShadowType(LightType lightType)
public static bool PlatformSupportsMSAABackBuffer()
public static bool IsSupportedCookieType(LightType lightType)
#if UNITY_ANDROID || UNITY_IPHONE || UNITY_TVOS || UNITY_SAMSUNGTV
return true;
#else
return false;
#endif
return lightType == LightType.Directional || lightType == LightType.Spot;
}
}
}

10
com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Core.hlsl


// Stereo-related bits
#if defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
#define SCREENSPACE_TEXTURE TEXTURE2D_ARRAY
#define SCREENSPACE_TEXTURE TEXTURE2D_ARRAY
#define SCREENSPACE_TEXTURE_FLOAT TEXTURE2D_ARRAY_FLOAT
#define SCREENSPACE_TEXTURE_HALF TEXTURE2D_ARRAY_HALF
#define SCREENSPACE_TEXTURE TEXTURE2D
#endif // defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
#define SCREENSPACE_TEXTURE TEXTURE2D
#define SCREENSPACE_TEXTURE_FLOAT TEXTURE2D_FLOAT
#define SCREENSPACE_TEXTURE_HALF TEXTURE2D_HALF
#endif
#if defined(UNITY_SINGLE_PASS_STEREO)
float2 TransformStereoScreenSpaceTex(float2 uv, float w)

64
com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/DepthCopy.hlsl


}
#if defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
#define DEPTH_TEXTURE_MS Texture2DMSArray
#define DEPTH_TEXTURE(name) TEXTURE2D_ARRAY(name)
#define LOAD(uv, sampleIndex) LOAD_TEXTURE2D_ARRAY_MSAA(_CameraDepthTexture, uv, unity_StereoEyeIndex, sampleIndex)
#define SAMPLE(uv) SAMPLE_TEXTURE2D_ARRAY(_CameraDepthTexture, sampler_CameraDepthTexture, uv, unity_StereoEyeIndex).r
#define DEPTH_TEXTURE_MS(name, samples) Texture2DMSArray<float, samples> name
#define DEPTH_TEXTURE(name) TEXTURE2D_ARRAY_FLOAT(name)
#define LOAD(uv, sampleIndex) LOAD_TEXTURE2D_ARRAY_MSAA(_CameraDepthAttachment, uv, unity_StereoEyeIndex, sampleIndex)
#define SAMPLE(uv) SAMPLE_TEXTURE2D_ARRAY(_CameraDepthAttachment, sampler_CameraDepthAttachment, uv, unity_StereoEyeIndex).r
#define DEPTH_TEXTURE_MS Texture2DMS
#define DEPTH_TEXTURE(name) TEXTURE2D(name)
#define LOAD(uv, sampleIndex) LOAD_TEXTURE2D_MSAA(_CameraDepthTexture, uv, sampleIndex)
#define SAMPLE(uv) SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, sampler_CameraDepthTexture, uv)
#define DEPTH_TEXTURE_MS(name, samples) Texture2DMS<float, samples> name
#define DEPTH_TEXTURE(name) TEXTURE2D_FLOAT(name)
#define LOAD(uv, sampleIndex) LOAD_TEXTURE2D_MSAA(_CameraDepthAttachment, uv, sampleIndex)
#define SAMPLE(uv) SAMPLE_DEPTH_TEXTURE(_CameraDepthAttachment, sampler_CameraDepthAttachment, uv)
#ifdef _MSAA_DEPTH
DEPTH_TEXTURE_MS<float> _CameraDepthTexture;
float _SampleCount;
float4 _CameraDepthTexture_TexelSize;
#ifdef _DEPTH_MSAA_2
#define MSAA_SAMPLES 2
#elif _DEPTH_MSAA_4
#define MSAA_SAMPLES 4
#endif
#ifdef _DEPTH_NO_MSAA
DEPTH_TEXTURE(_CameraDepthAttachment);
SAMPLER(sampler_CameraDepthAttachment);
DEPTH_TEXTURE(_CameraDepthTexture);
SAMPLER(sampler_CameraDepthTexture);
DEPTH_TEXTURE_MS(_CameraDepthAttachment, MSAA_SAMPLES);
float4 _CameraDepthAttachment_TexelSize;
#endif
#if UNITY_REVERSED_Z
#define DEPTH_DEFAULT_VALUE 1.0
#define DEPTH_OP min
#else
#define DEPTH_DEFAULT_VALUE 0.0
#define DEPTH_OP max
#ifdef _MSAA_DEPTH
int2 coord = int2(uv * _CameraDepthTexture_TexelSize.zw);
int samples = (int)_SampleCount;
#if UNITY_REVERSED_Z
float outDepth = 1.0;
#define DEPTH_OP min
#else
float outDepth = 0.0;
#define DEPTH_OP max
#endif
#ifdef _DEPTH_NO_MSAA
return SAMPLE(uv);
#else
int2 coord = int2(uv * _CameraDepthAttachment_TexelSize.zw);
float outDepth = DEPTH_DEFAULT_VALUE;
for (int i = 0; i < samples; ++i)
outDepth = DEPTH_OP(LOAD(uv, i), outDepth);
UNITY_UNROLL
for (int i = 0; i < MSAA_SAMPLES; ++i)
outDepth = DEPTH_OP(LOAD(coord, i), outDepth);
#else
return SAMPLE(uv);
#endif
}

26
com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Shadows.hlsl


#define MAX_SHADOW_CASCADES 4
#ifndef SHADOWS_SCREEN
#endif
SCREENSPACE_TEXTURE(_ScreenSpaceShadowMap);
SAMPLER(sampler_ScreenSpaceShadowMap);
SCREENSPACE_TEXTURE(_ScreenSpaceShadowMapTexture);
SAMPLER(sampler_ScreenSpaceShadowMapTexture);
TEXTURE2D_SHADOW(_ShadowMap);
SAMPLER_CMP(sampler_ShadowMap);
TEXTURE2D_SHADOW(_DirectionalShadowmapTexture);
SAMPLER_CMP(sampler_DirectionalShadowmapTexture);
TEXTURE2D_SHADOW(_LocalShadowMapAtlas);
SAMPLER_CMP(sampler_LocalShadowMapAtlas);
TEXTURE2D_SHADOW(_LocalShadowmapTexture);
SAMPLER_CMP(sampler_LocalShadowmapTexture);
CBUFFER_START(_DirectionalShadowBuffer)
// Last cascade is initialized with a no-op matrix. It always transforms

shadowCoord.xy = UnityStereoTransformScreenSpaceTex(shadowCoord.xy);
#if defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
half attenuation = SAMPLE_TEXTURE2D_ARRAY(_ScreenSpaceShadowMap, sampler_ScreenSpaceShadowMap, shadowCoord.xy, unity_StereoEyeIndex).x;
half attenuation = SAMPLE_TEXTURE2D_ARRAY(_ScreenSpaceShadowMapTexture, sampler_ScreenSpaceShadowMapTexture, shadowCoord.xy, unity_StereoEyeIndex).x;
half attenuation = SAMPLE_TEXTURE2D(_ScreenSpaceShadowMap, sampler_ScreenSpaceShadowMap, shadowCoord.xy).x;
half attenuation = SAMPLE_TEXTURE2D(_ScreenSpaceShadowMapTexture, sampler_ScreenSpaceShadowMapTexture, shadowCoord.xy).x;
#endif
return attenuation;

{
#if !defined(_SHADOWS_ENABLED)
return 1.0h;
#elif SHADOWS_SCREEN
#endif
#if SHADOWS_SCREEN
return SampleShadowmap(shadowCoord, TEXTURE2D_PARAM(_ShadowMap, sampler_ShadowMap), shadowSamplingData, shadowStrength);
return SampleShadowmap(shadowCoord, TEXTURE2D_PARAM(_DirectionalShadowmapTexture, sampler_DirectionalShadowmapTexture), shadowSamplingData, shadowStrength);
#endif
}

float4 shadowCoord = mul(_LocalWorldToShadowAtlas[lightIndex], float4(positionWS, 1.0));
ShadowSamplingData shadowSamplingData = GetLocalLightShadowSamplingData();
half shadowStrength = GetLocalLightShadowStrenth(lightIndex);
return SampleShadowmap(shadowCoord, TEXTURE2D_PARAM(_LocalShadowMapAtlas, sampler_LocalShadowMapAtlas), shadowSamplingData, shadowStrength);
return SampleShadowmap(shadowCoord, TEXTURE2D_PARAM(_LocalShadowmapTexture, sampler_LocalShadowmapTexture), shadowSamplingData, shadowStrength);
#endif
}

7
com.unity.render-pipelines.lightweight/LWRP/Shaders/LightweightCopyDepth.shader


Shader "Hidden/LightweightPipeline/CopyDepth"
{
Properties
{
[HideInInspector] _SampleCount("MSAA sample count", Float) = 1.0
}
SubShader
{
Tags { "RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline"}

#pragma vertex vert
#pragma fragment frag
#pragma multi_compile __ _MSAA_DEPTH
#pragma multi_compile _DEPTH_NO_MSAA _DEPTH_MSAA_2 _DEPTH_MSAA_4
#include "LWRP/ShaderLibrary/DepthCopy.hlsl"

8
com.unity.render-pipelines.lightweight/LWRP/Shaders/LightweightScreenSpaceShadows.shader


#include "LWRP/ShaderLibrary/Shadows.hlsl"
#if defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
TEXTURE2D_ARRAY(_CameraDepthTexture);
TEXTURE2D_ARRAY_FLOAT(_CameraDepthTexture);
TEXTURE2D(_CameraDepthTexture);
#endif // defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
TEXTURE2D_FLOAT(_CameraDepthTexture);
#endif
SAMPLER(sampler_CameraDepthTexture);

// Screenspace shadowmap is only used for directional lights which use orthogonal projection.
ShadowSamplingData shadowSamplingData = GetMainLightShadowSamplingData();
half shadowStrength = GetMainLightShadowStrength();
return SampleShadowmap(coords, TEXTURE2D_PARAM(_ShadowMap, sampler_ShadowMap), shadowSamplingData, shadowStrength);
return SampleShadowmap(coords, TEXTURE2D_PARAM(_DirectionalShadowmapTexture, sampler_DirectionalShadowmapTexture), shadowSamplingData, shadowStrength);
}
ENDHLSL

2
com.unity.shadergraph/Editor/Data/Graphs/AbstractMaterialGraph.cs


set { m_PreviewData = value; }
}
public string name { get; set; }
[SerializeField]
string m_Path;

24
com.unity.shadergraph/Editor/Data/Graphs/MaterialSlot.cs


case ConcreteSlotValueType.SamplerState:
return "(SS)";
case ConcreteSlotValueType.Texture2D:
return "(T)";
return "(T2)";
case ConcreteSlotValueType.Texture2DArray:
return "(T2A)";
case ConcreteSlotValueType.Texture3D:
return "(T3)";
case ConcreteSlotValueType.Cubemap:
return "(C)";
case ConcreteSlotValueType.Gradient:

return slotType == SlotType.Input
? new Texture2DInputMaterialSlot(slotId, displayName, shaderOutputName, shaderStageCapability, hidden)
: new Texture2DMaterialSlot(slotId, displayName, shaderOutputName, slotType, shaderStageCapability, hidden);
case SlotValueType.Texture2DArray:
return slotType == SlotType.Input
? new Texture2DArrayInputMaterialSlot(slotId, displayName, shaderOutputName, shaderStageCapability, hidden)
: new Texture2DArrayMaterialSlot(slotId, displayName, shaderOutputName, slotType, shaderStageCapability, hidden);
case SlotValueType.Texture3D:
return slotType == SlotType.Input
? new Texture3DInputMaterialSlot(slotId, displayName, shaderOutputName, shaderStageCapability, hidden)
: new Texture3DMaterialSlot(slotId, displayName, shaderOutputName, slotType, shaderStageCapability, hidden);
case SlotValueType.Cubemap:
return slotType == SlotType.Input
? new CubemapInputMaterialSlot(slotId, displayName, shaderOutputName, shaderStageCapability, hidden)

|| inputType == SlotValueType.Dynamic;
case SlotValueType.Texture2D:
return inputType == SlotValueType.Texture2D;
case SlotValueType.Texture2DArray:
return inputType == SlotValueType.Texture2DArray;
case SlotValueType.Texture3D:
return inputType == SlotValueType.Texture3D;
case SlotValueType.Cubemap:
return inputType == SlotValueType.Cubemap;
case SlotValueType.Gradient:

switch (slotValue)
{
case ConcreteSlotValueType.Texture2D:
return PropertyType.Texture;
return PropertyType.Texture2D;
case ConcreteSlotValueType.Texture2DArray:
return PropertyType.Texture2DArray;
case ConcreteSlotValueType.Texture3D:
return PropertyType.Texture3D;
case ConcreteSlotValueType.Cubemap:
return PropertyType.Cubemap;
case ConcreteSlotValueType.Gradient:

12
com.unity.shadergraph/Editor/Data/Graphs/PreviewProperty.cs


{
get
{
if (propType != PropertyType.Texture)
throw new ArgumentException(string.Format(k_GetErrorMessage, PropertyType.Texture, propType));
if (propType != PropertyType.Texture2D && propType != PropertyType.Texture2DArray && propType != PropertyType.Texture3D)
throw new ArgumentException(string.Format(k_GetErrorMessage, PropertyType.Texture2D, propType));
if (propType != PropertyType.Texture)
throw new ArgumentException(string.Format(k_SetErrorMessage, PropertyType.Texture, propType));
if (propType != PropertyType.Texture2D && propType != PropertyType.Texture2DArray && propType != PropertyType.Texture3D)
throw new ArgumentException(string.Format(k_SetErrorMessage, PropertyType.Texture2D, propType));
m_Data.textureValue = value;
}
}

}
set
{
if (propType != PropertyType.Vector2 && propType != PropertyType.Vector3 && propType != PropertyType.Vector4
if (propType != PropertyType.Vector2 && propType != PropertyType.Vector3 && propType != PropertyType.Vector4
&& propType != PropertyType.Matrix2 && propType != PropertyType.Matrix3 && propType != PropertyType.Matrix4)
throw new ArgumentException(string.Format(k_SetErrorMessage, PropertyType.Vector4, propType));
m_Data.vector4Value = value;

public void SetMaterialPropertyBlockValue(MaterialPropertyBlock block)
{
if (propType == PropertyType.Texture && textureValue != null)
if ((propType == PropertyType.Texture2D || propType == PropertyType.Texture2DArray || propType == PropertyType.Texture3D) && textureValue != null)
block.SetTexture(name, m_Data.textureValue);
else if (propType == PropertyType.Cubemap && cubemapValue != null)
block.SetTexture(name, m_Data.cubemapValue);

2
com.unity.shadergraph/Editor/Data/Graphs/Texture2DInputMaterialSlot.cs


public override void GetPreviewProperties(List<PreviewProperty> properties, string name)
{
var pp = new PreviewProperty(PropertyType.Texture)
var pp = new PreviewProperty(PropertyType.Texture2D)
{
name = name,
textureValue = texture,

6
com.unity.shadergraph/Editor/Data/Graphs/TextureShaderProperty.cs


public TextureShaderProperty()
{
value = new SerializableTexture();
displayName = "Texture";
displayName = "Texture2D";
get { return PropertyType.Texture; }
get { return PropertyType.Texture2D; }
}
public bool modifiable

public override PreviewProperty GetPreviewMaterialProperty()
{
return new PreviewProperty(PropertyType.Texture)
return new PreviewProperty(PropertyType.Texture2D)
{
name = referenceName,
textureValue = value.texture

4
com.unity.shadergraph/Editor/Data/Implementation/NodeUtils.cs


return p + "4";
case ConcreteSlotValueType.Texture2D:
return "Texture2D";
case ConcreteSlotValueType.Texture2DArray:
return "Texture2DArray";
case ConcreteSlotValueType.Texture3D:
return "Texture3D";
case ConcreteSlotValueType.Cubemap:
return "Cubemap";
case ConcreteSlotValueType.Gradient:

14
com.unity.shadergraph/Editor/Data/Nodes/CodeFunctionNode.cs


protected struct Texture2D
{}
protected struct Texture2DArray
{}
protected struct Texture3D
{}
protected struct SamplerState
{}

if (t == typeof(Texture2D))
{
return SlotValueType.Texture2D;
}
if (t == typeof(Texture2DArray))
{
return SlotValueType.Texture2DArray;
}
if (t == typeof(Texture3D))
{
return SlotValueType.Texture3D;
}
if (t == typeof(Cubemap))
{

15
com.unity.shadergraph/Editor/Data/Nodes/Input/PropertyNode.cs


AddSlot(new Texture2DMaterialSlot(OutputSlotId, property.displayName, "Out", SlotType.Output));
RemoveSlotsNameNotMatching(new[] {OutputSlotId});
}
else if (property is Texture2DArrayShaderProperty)
{
AddSlot(new Texture2DArrayMaterialSlot(OutputSlotId, property.displayName, "Out", SlotType.Output));
RemoveSlotsNameNotMatching(new[] {OutputSlotId});
}
else if (property is Texture3DShaderProperty)
{
AddSlot(new Texture3DMaterialSlot(OutputSlotId, property.displayName, "Out", SlotType.Output));
RemoveSlotsNameNotMatching(new[] {OutputSlotId});
}
else if (property is CubemapShaderProperty)
{
AddSlot(new CubemapMaterialSlot(OutputSlotId, property.displayName, "Out", SlotType.Output));

var graph = owner as AbstractMaterialGraph;
var property = graph.properties.FirstOrDefault(x => x.guid == propertyGuid);
if (!(property is TextureShaderProperty) && !(property is CubemapShaderProperty))
if (!(property is TextureShaderProperty) &&
!(property is Texture2DArrayShaderProperty) &&
!(property is Texture3DShaderProperty) &&
!(property is CubemapShaderProperty))
return base.GetVariableNameForSlot(slotId);
return property.referenceName;

2
com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs


public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{
properties.Add(new PreviewProperty(PropertyType.Texture)
properties.Add(new PreviewProperty(PropertyType.Texture2D)
{
name = GetVariableNameForSlot(OutputSlotId),
textureValue = texture

4
com.unity.shadergraph/Editor/Data/Nodes/PropertyType.cs


public enum PropertyType
{
Color,
Texture,
Texture2D,
Texture2DArray,
Texture3D,
Cubemap,
Gradient,
Boolean,

6
com.unity.shadergraph/Editor/Data/Nodes/SlotValue.cs


Matrix3,
Matrix2,
Texture2D,
Texture2DArray,
Texture3D,
Cubemap,
Gradient,
DynamicVector,

Matrix3,
Matrix2,
Texture2D,
Texture2DArray,
Texture3D,
Cubemap,
Gradient,
Vector4,

"typeMatrix",
"typeMatrix",
"typeTexture2D",
"typeTexture2DArray",
"typeTexture3D",
"typeCubemap",
"typeGradient",
"typeFloat4",

30
com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs


if (prop is TextureShaderProperty)
arguments.Add(string.Format("TEXTURE2D_PARAM({0}, sampler{0})", GetSlotValue(inSlotId, generationMode)));
if (prop is Texture2DArrayShaderProperty)
arguments.Add(string.Format("TEXTURE2D_PARAM({0}, sampler{0})", GetSlotValue(inSlotId, generationMode)));
if (prop is Texture3DShaderProperty)
arguments.Add(string.Format("TEXTURE3D_PARAM({0}, sampler{0})", GetSlotValue(inSlotId, generationMode)));
else if (prop is CubemapShaderProperty)
arguments.Add(string.Format("TEXTURECUBE_PARAM({0}, sampler{0})", GetSlotValue(inSlotId, generationMode)));
else

case PropertyType.Color:
slotType = SlotValueType.Vector4;
break;
case PropertyType.Texture:
case PropertyType.Texture2D:
case PropertyType.Texture2DArray:
slotType = SlotValueType.Texture2DArray;
break;
case PropertyType.Texture3D:
slotType = SlotValueType.Texture3D;
break;
case PropertyType.Cubemap:
slotType = SlotValueType.Cubemap;
break;

var id = prop.guid.GetHashCode();
MaterialSlot slot = MaterialSlot.CreateMaterialSlot(slotType, id, prop.displayName, prop.referenceName, SlotType.Input, prop.defaultValue, ShaderStageCapability.Fragment);
// copy default for texture for niceness
if (slotType == SlotValueType.Texture2D && propType == PropertyType.Texture)
if (slotType == SlotValueType.Texture2D && propType == PropertyType.Texture2D)
if (tSlot != null && tProp != null)
tSlot.texture = tProp.value.texture;
}
// copy default for texture array for niceness
else if (slotType == SlotValueType.Texture2DArray && propType == PropertyType.Texture2DArray)
{
var tSlot = slot as Texture2DArrayInputMaterialSlot;
var tProp = prop as Texture2DArrayShaderProperty;
if (tSlot != null && tProp != null)
tSlot.textureArray = tProp.value.textureArray;
}
// copy default for texture 3d for niceness
else if (slotType == SlotValueType.Texture3D && propType == PropertyType.Texture3D)
{
var tSlot = slot as Texture3DInputMaterialSlot;
var tProp = prop as Texture3DShaderProperty;
if (tSlot != null && tProp != null)
tSlot.texture = tProp.value.texture;
}

40
com.unity.shadergraph/Editor/Data/Util/GraphContext.cs


using System;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
public class GraphContext
{
public GraphContext(string inputStructName)
{
graphInputStructName = inputStructName;
}
public string graphInputStructName
{
get { return m_GraphInputStructName; }
set { m_GraphInputStructName = value; }
}
string m_GraphInputStructName;
}
using System;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
public class GraphContext
{
public GraphContext(string inputStructName)
{
graphInputStructName = inputStructName;
}
public string graphInputStructName
{
get { return m_GraphInputStructName; }
set { m_GraphInputStructName = value; }
}
string m_GraphInputStructName;
}
}

37
com.unity.shadergraph/Editor/Data/Util/GraphUtil.cs


using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using UnityEditorInternal;
using Debug = UnityEngine.Debug;
using System.Text.RegularExpressions;
namespace UnityEditor.ShaderGraph
{

}
return string.Format(duplicateFormat, name, duplicateNumber);
}
public static bool WriteToFile(string path, string content)
{
try
{
File.WriteAllText(path, content);
return true;
}
catch (Exception e)
{
Debug.LogError(e);
return false;
}
}
public static void OpenFile(string path)
{
if (!File.Exists(Path.GetFullPath(path)))
{
Debug.LogError(string.Format("Path {0} doesn't exists", path));
return;
}
string file = Path.GetFullPath(path);
ProcessStartInfo pi = new ProcessStartInfo(file);
pi.Arguments = Path.GetFileName(file);
pi.UseShellExecute = true;
pi.WorkingDirectory = Path.GetDirectoryName(file);
pi.FileName = ScriptEditorUtility.GetExternalScriptEditor();
pi.Verb = "OPEN";
Process.Start(pi);
}
}
}

28
com.unity.shadergraph/Editor/Data/Util/PropertyCollector.cs


}
}
foreach (var prop in m_Properties.OfType<Texture2DArrayShaderProperty>())
{
if (prop.referenceName != null)
{
var textureInfo = new TextureInfo
{
name = prop.referenceName,
textureId = prop.value.textureArray != null ? prop.value.textureArray.GetInstanceID() : 0,
modifiable = prop.modifiable
};
result.Add(textureInfo);
}
}
foreach (var prop in m_Properties.OfType<Texture3DShaderProperty>())
{
if (prop.referenceName != null)
{
var textureInfo = new TextureInfo
{
name = prop.referenceName,
textureId = prop.value.texture != null ? prop.value.texture.GetInstanceID() : 0,
modifiable = prop.modifiable
};
result.Add(textureInfo);
}
}
foreach (var prop in m_Properties.OfType<CubemapShaderProperty>())
{
if (prop.referenceName != null)

22
com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardFieldPropertyView.cs


});
AddRow("Default", field);
}
else if (property is Texture2DArrayShaderProperty)
{
var textureProperty = (Texture2DArrayShaderProperty)property;
var field = new ObjectField { value = textureProperty.value.textureArray, objectType = typeof(Texture2DArray) };
field.OnValueChanged(evt =>
{
textureProperty.value.textureArray = (Texture2DArray)evt.newValue;
DirtyNodes();
});
AddRow("Default", field);
}
else if (property is Texture3DShaderProperty)
{
var textureProperty = (Texture3DShaderProperty)property;
var field = new ObjectField { value = textureProperty.value.texture, objectType = typeof(Texture3D) };
field.OnValueChanged(evt =>
{
textureProperty.value.texture = (Texture3D)evt.newValue;
DirtyNodes();
});
AddRow("Default", field);
}
else if (property is CubemapShaderProperty)
{
var cubemapProperty = (CubemapShaderProperty)property;

4
com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs


gm.AddItem(new GUIContent("Vector3"), false, () => AddProperty(new Vector3ShaderProperty(), true));
gm.AddItem(new GUIContent("Vector4"), false, () => AddProperty(new Vector4ShaderProperty(), true));
gm.AddItem(new GUIContent("Color"), false, () => AddProperty(new ColorShaderProperty(), true));
gm.AddItem(new GUIContent("Texture"), false, () => AddProperty(new TextureShaderProperty(), true));
gm.AddItem(new GUIContent("Texture2D"), false, () => AddProperty(new TextureShaderProperty(), true));
gm.AddItem(new GUIContent("Texture2D Array"), false, () => AddProperty(new Texture2DArrayShaderProperty(), true));
gm.AddItem(new GUIContent("Texture3D"), false, () => AddProperty(new Texture3DShaderProperty(), true));
gm.AddItem(new GUIContent("Cubemap"), false, () => AddProperty(new CubemapShaderProperty(), true));
gm.AddItem(new GUIContent("Boolean"), false, () => AddProperty(new BooleanShaderProperty(), true));
gm.ShowAsContext();

4
com.unity.shadergraph/Editor/Drawing/Controls/DefaultControl.cs


return new EnumControlView(null, node, propertyInfo);
if (propertyInfo.PropertyType == typeof(Texture2D))
return new TextureControlView(null, node, propertyInfo);
if (propertyInfo.PropertyType == typeof(Texture2DArray))
return new TextureArrayControlView(null, node, propertyInfo);
if (propertyInfo.PropertyType == typeof(Texture3D))
return new Texture3DControlView(null, node, propertyInfo);
if (MultiFloatControlView.validTypes.Contains(propertyInfo.PropertyType))
return new MultiFloatControlView(null, "X", "Y", "Z", "W", node, propertyInfo);
if (typeof(Object).IsAssignableFrom(propertyInfo.PropertyType))

8
com.unity.shadergraph/Editor/Drawing/MaterialGraphEditWindow.cs


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

using UnityEditor.Graphing;
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;
using Edge = UnityEditor.Experimental.UIElements.GraphView.Edge;
#if UNITY_2018_1

{
case ConcreteSlotValueType.Texture2D:
prop = new TextureShaderProperty();
break;
case ConcreteSlotValueType.Texture2DArray:
prop = new Texture2DArrayShaderProperty();
break;
case ConcreteSlotValueType.Texture3D:
prop = new Texture3DShaderProperty();
break;
case ConcreteSlotValueType.Cubemap:
prop = new CubemapShaderProperty();

4
com.unity.shadergraph/Editor/Drawing/Views/GraphEditorView.cs


if (showInProjectRequested != null)
showInProjectRequested();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
graph.name = assetName;
m_GraphView = new MaterialGraphView(graph) { name = "GraphView", persistenceKey = "MaterialGraphView" };
m_GraphView.SetupZoom(0.05f, ContentZoomer.DefaultMaxScale);
m_GraphView.AddManipulator(new ContentDragger());

m_GraphView.AddManipulator(new GraphDropTarget(graph));
m_GraphView.RegisterCallback<KeyDownEvent>(OnSpaceDown);
content.Add(m_GraphView);

174
com.unity.shadergraph/Editor/Drawing/Views/MaterialGraphView.cs


using UnityEngine.Experimental.UIElements;
using Edge = UnityEditor.Experimental.UIElements.GraphView.Edge;
using Node = UnityEditor.Experimental.UIElements.GraphView.Node;
using Object = UnityEngine.Object;
#if !UNITY_2018_1
using UnityEditor.Graphs;
#endif

#region Drag and drop
static bool ValidateObjectForDrop(Object obj)
{
return EditorUtility.IsPersistent(obj) && (obj is Texture2D || obj is Cubemap || obj is MaterialSubGraphAsset || obj is Texture2DArray || obj is Texture3D);
}
bool dragging = false;
if (selection != null)
{
// Blackboard
if (selection.OfType<BlackboardField>().Any())
dragging = true;
}
else
{
// Handle unity objects
var objects = DragAndDrop.objectReferences;
foreach (Object obj in objects)
{
if (ValidateObjectForDrop(obj))
{
dragging = true;
break;
}
}
}
if (selection != null && (selection.OfType<BlackboardField>().Any() ))
if (dragging)
DragAndDrop.visualMode = e.ctrlKey ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Move;
DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
Vector2 localPos = (e.currentTarget as VisualElement).ChangeCoordinatesTo(contentViewContainer, e.localMousePosition);
if (selection == null)
return;
if (selection != null)
{
// Blackboard
if (selection.OfType<BlackboardField>().Any())
{
IEnumerable<BlackboardField> fields = selection.OfType<BlackboardField>();
foreach (BlackboardField field in fields)
{
CreateNode(field, localPos);
}
}
}
else
{
// Handle unity objects
var objects = DragAndDrop.objectReferences;
foreach (Object obj in objects)
{
if (ValidateObjectForDrop(obj))
{
CreateNode(obj, localPos);
}
}
}
}
void CreateNode(object obj, Vector2 nodePosition)
{
var texture2D = obj as Texture2D;
if (texture2D != null)
{
graph.owner.RegisterCompleteObjectUndo("Drag Texture");
bool isNormalMap = false;
if (EditorUtility.IsPersistent(texture2D) && !string.IsNullOrEmpty(AssetDatabase.GetAssetPath(texture2D)))
{
var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture2D)) as TextureImporter;
if (importer != null)
isNormalMap = importer.textureType == TextureImporterType.NormalMap;
}
var node = new SampleTexture2DNode();
if (isNormalMap)
node.textureType = TextureType.Normal;
var drawState = node.drawState;
drawState.position = new Rect(nodePosition, drawState.position.size);
node.drawState = drawState;
graph.AddNode(node);
IEnumerable<BlackboardField> fields = selection.OfType<BlackboardField>();
if (!fields.Any())
return;
var inputslot = node.FindInputSlot<Texture2DInputMaterialSlot>(SampleTexture2DNode.TextureInputId);
if (inputslot != null)
inputslot.texture = texture2D;
}
Vector2 localPos = (e.currentTarget as VisualElement).ChangeCoordinatesTo(contentViewContainer, e.localMousePosition);
var textureArray = obj as Texture2DArray;
if (textureArray != null)
{
graph.owner.RegisterCompleteObjectUndo("Drag Texture Array");
var property = new Texture2DArrayShaderProperty { displayName = textureArray.name, value = { textureArray = textureArray } };
graph.AddShaderProperty(property);
var node = new SampleTexture2DArrayNode();
var drawState = node.drawState;
drawState.position = new Rect(nodePosition, drawState.position.size);
node.drawState = drawState;
graph.AddNode(node);
var inputslot = node.FindSlot<Texture2DArrayInputMaterialSlot>(SampleTexture2DArrayNode.TextureInputId);
if (inputslot != null)
inputslot.textureArray = textureArray;
}
foreach (BlackboardField field in fields)
var texture3D = obj as Texture3D;
if (texture3D != null)
IShaderProperty property = field.userData as IShaderProperty;
if (property == null)
continue;
graph.owner.RegisterCompleteObjectUndo("Drag Texture 3D");
var property = new Texture3DShaderProperty { displayName = texture3D.name, value = { texture = texture3D } };
graph.AddShaderProperty(property);
var node = new SampleTexture3DNode();
var drawState = node.drawState;
drawState.position = new Rect(nodePosition, drawState.position.size);
node.drawState = drawState;
graph.AddNode(node);
var inputslot = node.FindSlot<Texture3DInputMaterialSlot>(SampleTexture3DNode.TextureInputId);
if (inputslot != null)
inputslot.texture = texture3D;
}
var node = new PropertyNode();
var cubemap = obj as Cubemap;
if (cubemap != null)
{
graph.owner.RegisterCompleteObjectUndo("Drag Cubemap");
var property = new CubemapShaderProperty { displayName = cubemap.name, value = { cubemap = cubemap } };
graph.AddShaderProperty(property);
var node = new SampleCubemapNode();
var position = drawState.position;
position.x = localPos.x;
position.y = localPos.y;
drawState.position = position;
drawState.position = new Rect(nodePosition, drawState.position.size);
graph.AddNode(node);
graph.owner.RegisterCompleteObjectUndo("Added Property");
var inputslot = node.FindInputSlot<CubemapInputMaterialSlot>(SampleCubemapNode.CubemapInputId);
if (inputslot != null)
inputslot.cubemap = cubemap;
}
var subGraphAsset = obj as MaterialSubGraphAsset;
if (subGraphAsset != null)
{
graph.owner.RegisterCompleteObjectUndo("Drag Sub-Graph");
var node = new SubGraphNode();
var drawState = node.drawState;
drawState.position = new Rect(nodePosition, drawState.position.size);
node.drawState = drawState;
node.subGraphAsset = subGraphAsset;
node.propertyGuid = property.guid;
}
var blackboardField = obj as BlackboardField;
if (blackboardField != null)
{
IShaderProperty property = blackboardField.userData as IShaderProperty;
if (property != null)
{
graph.owner.RegisterCompleteObjectUndo("Drag Property");
var node = new PropertyNode();
var drawState = node.drawState;
drawState.position = new Rect(nodePosition, drawState.position.size);
node.drawState = drawState;
graph.AddNode(node);
node.propertyGuid = property.guid;
}
}
}

41
com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs


public override void BuildContextualMenu(ContextualMenuPopulateEvent evt)
{
if (evt.target is Node)
evt.menu.AppendAction("Copy shader", ConvertToShader, node.hasPreview ? ContextualMenu.MenuAction.StatusFlags.Normal : ContextualMenu.MenuAction.StatusFlags.Hidden);
{
evt.menu.AppendAction("Copy Shader", CopyToClipboard, node.hasPreview ? ContextualMenu.MenuAction.StatusFlags.Normal : ContextualMenu.MenuAction.StatusFlags.Hidden);
evt.menu.AppendAction("Show Generated Code", ShowGeneratedCode, node.hasPreview ? ContextualMenu.MenuAction.StatusFlags.Normal : ContextualMenu.MenuAction.StatusFlags.Hidden);
}
void ConvertToShader()
void CopyToClipboard()
{
GUIUtility.systemCopyBuffer = ConvertToShader();
}
public string SanitizeName(string name)
{
return new string(name.Where( c => !Char.IsWhiteSpace(c) ).ToArray());
}
public void ShowGeneratedCode()
{
var graph = (AbstractMaterialGraph)node.owner;
string path = String.Format("Temp/GeneratedFromGraph-{0}-{1}-{2}.shader", SanitizeName(graph.name), SanitizeName(node.name), node.guid );
if( GraphUtil.WriteToFile(path, ConvertToShader()) )
GraphUtil.OpenFile(path);
}
string ConvertToShader()
{
var shader = masterNode.GetShader(GenerationMode.ForReals, node.name, out textureInfo);
GUIUtility.systemCopyBuffer = shader;
}
else
{
var graph = (AbstractMaterialGraph)node.owner;
GUIUtility.systemCopyBuffer = graph.GetShader(node, GenerationMode.ForReals, node.name).shader;
}
return masterNode.GetShader(GenerationMode.ForReals, node.name, out textureInfo);
var graph = (AbstractMaterialGraph)node.owner;
return graph.GetShader(node, GenerationMode.ForReals, node.name).shader;
}
void UpdateSettingsExpandedState()

6
com.unity.shadergraph/Editor/Resources/Styles/PortInputView.uss


edge-color: #8FC1DF;
}
PortInputView.typeTexture2D > #container > #slot > #dot,
PortInputView.typeTexture2D > #container > #slot > #dot,
PortInputView.typeTexture2DArray > #container > #slot > #dot,
PortInputView.typeTexture3D > #container > #slot > #dot,
PortInputView.typeTexture2DArray,
PortInputView.typeTexture3D,
PortInputView.typeCubemap {
edge-color: #FF8B8B;
}

10
com.unity.shadergraph/Editor/Resources/Styles/ShaderPort.uss


port-color:#FF8B8B;
}
ShaderPort.typeTexture2DArray {
/* Same as typeTexture */
port-color:#FF8B8B;
}
ShaderPort.typeTexture3D {
/* Same as typeTexture */
port-color:#FF8B8B;
}
ShaderPort.typeCubemap {
/* Same as typeTexture */
port-color:#FF8B8B;

1001
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/ShaderGraph/HDPBRSubShader.cs
文件差异内容过多而无法显示
查看文件

888
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/ShaderGraph/HDSubShaderUtilities.cs


using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor.Graphing;
using UnityEngine; // Vector3,4
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph
{
public static class HDRPShaderStructs
{
struct AttributesMesh
{
[Semantic("POSITION")] Vector3 positionOS;
[Semantic("NORMAL")][Optional] Vector3 normalOS;
[Semantic("TANGENT")][Optional] Vector4 tangentOS; // Stores bi-tangent sign in w
[Semantic("TEXCOORD0")][Optional] Vector2 uv0;
[Semantic("TEXCOORD1")][Optional] Vector2 uv1;
[Semantic("TEXCOORD2")][Optional] Vector2 uv2;
[Semantic("TEXCOORD3")][Optional] Vector2 uv3;
[Semantic("COLOR")][Optional] Vector4 color;
};
struct VaryingsMeshToPS
{
[Semantic("SV_Position")] Vector4 positionCS;
[Optional] Vector3 positionWS;
[Optional] Vector3 normalWS;
[Optional] Vector4 tangentWS; // w contain mirror sign
[Optional] Vector2 texCoord0;
[Optional] Vector2 texCoord1;
[Optional] Vector2 texCoord2;
[Optional] Vector2 texCoord3;
[Optional] Vector4 color;
[Optional] [Semantic("FRONT_FACE_SEMANTIC")] [OverrideType("FRONT_FACE_TYPE")] [PreprocessorIf("SHADER_STAGE_FRAGMENT")]
bool cullFace;
public static Dependency[] tessellationDependencies = new Dependency[]
{
new Dependency("VaryingsMeshToPS.positionWS", "VaryingsMeshToDS.positionWS"),
new Dependency("VaryingsMeshToPS.normalWS", "VaryingsMeshToDS.normalWS"),
new Dependency("VaryingsMeshToPS.tangentWS", "VaryingsMeshToDS.tangentWS"),
new Dependency("VaryingsMeshToPS.texCoord0", "VaryingsMeshToDS.texCoord0"),
new Dependency("VaryingsMeshToPS.texCoord1", "VaryingsMeshToDS.texCoord1"),
new Dependency("VaryingsMeshToPS.texCoord2", "VaryingsMeshToDS.texCoord2"),
new Dependency("VaryingsMeshToPS.texCoord3", "VaryingsMeshToDS.texCoord3"),
new Dependency("VaryingsMeshToPS.color", "VaryingsMeshToDS.color"),
};
public static Dependency[] standardDependencies = new Dependency[]
{
new Dependency("VaryingsMeshToPS.positionWS", "AttributesMesh.positionOS"),
new Dependency("VaryingsMeshToPS.normalWS", "AttributesMesh.normalOS"),
new Dependency("VaryingsMeshToPS.tangentWS", "AttributesMesh.tangentOS"),
new Dependency("VaryingsMeshToPS.texCoord0", "AttributesMesh.uv0"),
new Dependency("VaryingsMeshToPS.texCoord1", "AttributesMesh.uv1"),
new Dependency("VaryingsMeshToPS.texCoord2", "AttributesMesh.uv2"),
new Dependency("VaryingsMeshToPS.texCoord3", "AttributesMesh.uv3"),
new Dependency("VaryingsMeshToPS.color", "AttributesMesh.color"),
};
};
struct VaryingsMeshToDS
{
Vector3 positionWS;
Vector3 normalWS;
[Optional] Vector4 tangentWS;
[Optional] Vector2 texCoord0;
[Optional] Vector2 texCoord1;
[Optional] Vector2 texCoord2;
[Optional] Vector2 texCoord3;
[Optional] Vector4 color;
public static Dependency[] tessellationDependencies = new Dependency[]
{
new Dependency("VaryingsMeshToDS.tangentWS", "VaryingsMeshToPS.tangentWS"),
new Dependency("VaryingsMeshToDS.texCoord0", "VaryingsMeshToPS.texCoord0"),
new Dependency("VaryingsMeshToDS.texCoord1", "VaryingsMeshToPS.texCoord1"),
new Dependency("VaryingsMeshToDS.texCoord2", "VaryingsMeshToPS.texCoord2"),
new Dependency("VaryingsMeshToDS.texCoord3", "VaryingsMeshToPS.texCoord3"),
new Dependency("VaryingsMeshToDS.color", "VaryingsMeshToPS.color"),
};
};
struct FragInputs
{
public static Dependency[] dependencies = new Dependency[]
{
new Dependency("FragInputs.positionWS", "VaryingsMeshToPS.positionWS"),
new Dependency("FragInputs.worldToTangent", "VaryingsMeshToPS.tangentWS"),
new Dependency("FragInputs.worldToTangent", "VaryingsMeshToPS.normalWS"),
new Dependency("FragInputs.texCoord0", "VaryingsMeshToPS.texCoord0"),
new Dependency("FragInputs.texCoord1", "VaryingsMeshToPS.texCoord1"),
new Dependency("FragInputs.texCoord2", "VaryingsMeshToPS.texCoord2"),
new Dependency("FragInputs.texCoord3", "VaryingsMeshToPS.texCoord3"),
new Dependency("FragInputs.color", "VaryingsMeshToPS.color"),
new Dependency("FragInputs.isFrontFace", "VaryingsMeshToPS.cullFace"),
};
};
struct SurfaceDescriptionInputs
{
[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[]
{
new Dependency("SurfaceDescriptionInputs.WorldSpaceNormal", "FragInputs.worldToTangent"),
new Dependency("SurfaceDescriptionInputs.ObjectSpaceNormal", "SurfaceDescriptionInputs.WorldSpaceNormal"),
new Dependency("SurfaceDescriptionInputs.ViewSpaceNormal", "SurfaceDescriptionInputs.WorldSpaceNormal"),
new Dependency("SurfaceDescriptionInputs.WorldSpaceTangent", "FragInputs.worldToTangent"),
new Dependency("SurfaceDescriptionInputs.ObjectSpaceTangent", "SurfaceDescriptionInputs.WorldSpaceTangent"),
new Dependency("SurfaceDescriptionInputs.ViewSpaceTangent", "SurfaceDescriptionInputs.WorldSpaceTangent"),
new Dependency("SurfaceDescriptionInputs.WorldSpaceBiTangent", "FragInputs.worldToTangent"),
new Dependency("SurfaceDescriptionInputs.ObjectSpaceBiTangent", "SurfaceDescriptionInputs.WorldSpaceBiTangent"),
new Dependency("SurfaceDescriptionInputs.ViewSpaceBiTangent", "SurfaceDescriptionInputs.WorldSpaceBiTangent"),
new Dependency("SurfaceDescriptionInputs.WorldSpacePosition", "FragInputs.positionWS"),
new Dependency("SurfaceDescriptionInputs.ObjectSpacePosition", "FragInputs.positionWS"),
new Dependency("SurfaceDescriptionInputs.ViewSpacePosition", "FragInputs.positionWS"),
new Dependency("SurfaceDescriptionInputs.WorldSpaceViewDirection", "FragInputs.positionWS"), // we build WorldSpaceViewDirection using FragInputs.positionWS in GetWorldSpaceNormalizeViewDir()
new Dependency("SurfaceDescriptionInputs.ObjectSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceViewDirection"),
new Dependency("SurfaceDescriptionInputs.ViewSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceViewDirection"),
new Dependency("SurfaceDescriptionInputs.TangentSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceViewDirection"),
new Dependency("SurfaceDescriptionInputs.TangentSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceTangent"),
new Dependency("SurfaceDescriptionInputs.TangentSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceBiTangent"),
new Dependency("SurfaceDescriptionInputs.TangentSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceNormal"),
new Dependency("SurfaceDescriptionInputs.screenPosition", "FragInputs.positionSS"),
new Dependency("SurfaceDescriptionInputs.uv0", "FragInputs.texCoord0"),
new Dependency("SurfaceDescriptionInputs.uv1", "FragInputs.texCoord1"),
new Dependency("SurfaceDescriptionInputs.uv2", "FragInputs.texCoord2"),
new Dependency("SurfaceDescriptionInputs.uv3", "FragInputs.texCoord3"),
new Dependency("SurfaceDescriptionInputs.vertexColor", "FragInputs.color"),
};
};
static void AddActiveFieldsFromGraphRequirements(HashSet<string> activeFields, ShaderGraphRequirements requirements)
{
if (requirements.requiresScreenPosition)
{
activeFields.Add("SurfaceDescriptionInputs.screenPosition");
}
if (requirements.requiresVertexColor)
{
activeFields.Add("SurfaceDescriptionInputs.vertexColor");
}
if (requirements.requiresNormal != 0)
{
if ((requirements.requiresNormal & NeededCoordinateSpace.Object) > 0)
activeFields.Add("SurfaceDescriptionInputs.ObjectSpaceNormal");
if ((requirements.requiresNormal & NeededCoordinateSpace.View) > 0)
activeFields.Add("SurfaceDescriptionInputs.ViewSpaceNormal");
if ((requirements.requiresNormal & NeededCoordinateSpace.World) > 0)
activeFields.Add("SurfaceDescriptionInputs.WorldSpaceNormal");
if ((requirements.requiresNormal & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("SurfaceDescriptionInputs.TangentSpaceNormal");
}
if (requirements.requiresTangent != 0)
{
if ((requirements.requiresTangent & NeededCoordinateSpace.Object) > 0)
activeFields.Add("SurfaceDescriptionInputs.ObjectSpaceTangent");
if ((requirements.requiresTangent & NeededCoordinateSpace.View) > 0)
activeFields.Add("SurfaceDescriptionInputs.ViewSpaceTangent");
if ((requirements.requiresTangent & NeededCoordinateSpace.World) > 0)
activeFields.Add("SurfaceDescriptionInputs.WorldSpaceTangent");
if ((requirements.requiresTangent & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("SurfaceDescriptionInputs.TangentSpaceTangent");
}
if (requirements.requiresBitangent != 0)
{
if ((requirements.requiresBitangent & NeededCoordinateSpace.Object) > 0)
activeFields.Add("SurfaceDescriptionInputs.ObjectSpaceBiTangent");
if ((requirements.requiresBitangent & NeededCoordinateSpace.View) > 0)
activeFields.Add("SurfaceDescriptionInputs.ViewSpaceBiTangent");
if ((requirements.requiresBitangent & NeededCoordinateSpace.World) > 0)
activeFields.Add("SurfaceDescriptionInputs.WorldSpaceBiTangent");
if ((requirements.requiresBitangent & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("SurfaceDescriptionInputs.TangentSpaceBiTangent");
}
if (requirements.requiresViewDir != 0)
{
if ((requirements.requiresViewDir & NeededCoordinateSpace.Object) > 0)
activeFields.Add("SurfaceDescriptionInputs.ObjectSpaceViewDirection");
if ((requirements.requiresViewDir & NeededCoordinateSpace.View) > 0)
activeFields.Add("SurfaceDescriptionInputs.ViewSpaceViewDirection");
if ((requirements.requiresViewDir & NeededCoordinateSpace.World) > 0)
activeFields.Add("SurfaceDescriptionInputs.WorldSpaceViewDirection");
if ((requirements.requiresViewDir & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("SurfaceDescriptionInputs.TangentSpaceViewDirection");
}
if (requirements.requiresPosition != 0)
{
if ((requirements.requiresPosition & NeededCoordinateSpace.Object) > 0)
activeFields.Add("SurfaceDescriptionInputs.ObjectSpacePosition");
if ((requirements.requiresPosition & NeededCoordinateSpace.View) > 0)
activeFields.Add("SurfaceDescriptionInputs.ViewSpacePosition");
if ((requirements.requiresPosition & NeededCoordinateSpace.World) > 0)
activeFields.Add("SurfaceDescriptionInputs.WorldSpacePosition");
if ((requirements.requiresPosition & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("SurfaceDescriptionInputs.TangentSpacePosition");
}
foreach (var channel in requirements.requiresMeshUVs.Distinct())
{
activeFields.Add("SurfaceDescriptionInputs." + channel.GetUVName());
}
}
// TODO : split this function into buildActiveFields and buildHLSLTypeDeclaration functions
public static void Generate(
ShaderGenerator codeResult,
ShaderGenerator graphInputsResult,
ShaderGraphRequirements graphRequirements,
List<string> passRequiredFields, // fields the pass requires
CoordinateSpace preferedCoordinateSpace,
HashSet<string> activeFields)
{
if (preferedCoordinateSpace == CoordinateSpace.Tangent)
preferedCoordinateSpace = CoordinateSpace.World;
// build initial requirements
AddActiveFieldsFromGraphRequirements(activeFields, graphRequirements);
if (passRequiredFields != null)
{
foreach (var requiredField in passRequiredFields)
{
activeFields.Add(requiredField);
}
}
// propagate requirements using dependencies
{
ShaderSpliceUtil.ApplyDependencies(
activeFields,
new List<Dependency[]>()
{
FragInputs.dependencies,
VaryingsMeshToPS.standardDependencies,
SurfaceDescriptionInputs.dependencies,
});
}
// generate code based on requirements
ShaderSpliceUtil.BuildType(typeof(AttributesMesh), activeFields, codeResult);
ShaderSpliceUtil.BuildType(typeof(VaryingsMeshToPS), activeFields, codeResult);
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 struct Pass
{
public string Name;
public string LightMode;
public string ShaderPassName;
public List<string> Includes;
public string TemplateName;
public List<string> ExtraDefines;
public List<int> VertexShaderSlots; // These control what slots are used by the pass vertex shader
public List<int> PixelShaderSlots; // These control what slots are used by the pass pixel shader
public string CullOverride;
public string BlendOverride;
public string BlendOpOverride;
public string ZTestOverride;
public string ZWriteOverride;
public string ColorMaskOverride;
public List<string> StencilOverride;
public List<string> RequiredFields; // feeds into the dependency analysis
public ShaderGraphRequirements requirements;
};
public static class HDSubShaderUtilities
{
public static void BuildRenderStatesFromPassAndMaterialOptions(
Pass pass,
SurfaceMaterialOptions materialOptions,
ShaderStringBuilder blendCode,
ShaderStringBuilder cullCode,
ShaderStringBuilder zTestCode,
ShaderStringBuilder zWriteCode,
ShaderStringBuilder stencilCode,
ShaderStringBuilder colorMaskCode)
{
if (pass.BlendOverride != null)
{
blendCode.AppendLine(pass.BlendOverride);
}
else
{
materialOptions.GetBlend(blendCode);
}
if (pass.BlendOpOverride != null)
{
blendCode.AppendLine(pass.BlendOpOverride);
}
if (pass.CullOverride != null)
{
cullCode.AppendLine(pass.CullOverride);
}
else
{
materialOptions.GetCull(cullCode);
}
if (pass.ZTestOverride != null)
{
zTestCode.AppendLine(pass.ZTestOverride);
}
else
{
materialOptions.GetDepthTest(zTestCode);
}
if (pass.ZWriteOverride != null)
{
zWriteCode.AppendLine(pass.ZWriteOverride);
}
else
{
materialOptions.GetDepthWrite(zWriteCode);
}
if (pass.ColorMaskOverride != null)
{
colorMaskCode.AppendLine(pass.ColorMaskOverride);
}
else
{
// material option default is to not declare anything for color mask
}
if (pass.StencilOverride != null)
{
foreach (var str in pass.StencilOverride)
{
stencilCode.AppendLine(str);
}
}
else
{
stencilCode.AppendLine("// Default Stencil");
}
}
public static SurfaceMaterialOptions BuildMaterialOptions(SurfaceType surfaceType, AlphaMode alphaMode, bool twoSided)
{
SurfaceMaterialOptions materialOptions = new SurfaceMaterialOptions();
if (surfaceType == SurfaceType.Opaque)
{
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.Zero;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.On;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Geometry;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Opaque;
}
else
{
switch (alphaMode)
{
case AlphaMode.Alpha:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.SrcAlpha;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.OneMinusSrcAlpha;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
case AlphaMode.Additive:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
// TODO: other blend modes
}
}
materialOptions.cullMode = twoSided ? SurfaceMaterialOptions.CullMode.Off : SurfaceMaterialOptions.CullMode.Back;
return materialOptions;
}
}
}
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor.Graphing;
using UnityEngine; // Vector3,4
using UnityEditor.ShaderGraph;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
public static class HDRPShaderStructs
{
struct AttributesMesh
{
[Semantic("POSITION")] Vector3 positionOS;
[Semantic("NORMAL")][Optional] Vector3 normalOS;
[Semantic("TANGENT")][Optional] Vector4 tangentOS; // Stores bi-tangent sign in w
[Semantic("TEXCOORD0")][Optional] Vector2 uv0;
[Semantic("TEXCOORD1")][Optional] Vector2 uv1;
[Semantic("TEXCOORD2")][Optional] Vector2 uv2;
[Semantic("TEXCOORD3")][Optional] Vector2 uv3;
[Semantic("COLOR")][Optional] Vector4 color;
};
struct VaryingsMeshToPS
{
[Semantic("SV_Position")] Vector4 positionCS;
[Optional] Vector3 positionWS;
[Optional] Vector3 normalWS;
[Optional] Vector4 tangentWS; // w contain mirror sign
[Optional] Vector2 texCoord0;
[Optional] Vector2 texCoord1;
[Optional] Vector2 texCoord2;
[Optional] Vector2 texCoord3;
[Optional] Vector4 color;
[Optional] [Semantic("FRONT_FACE_SEMANTIC")] [OverrideType("FRONT_FACE_TYPE")] [PreprocessorIf("SHADER_STAGE_FRAGMENT")]
bool cullFace;
public static Dependency[] tessellationDependencies = new Dependency[]
{
new Dependency("VaryingsMeshToPS.positionWS", "VaryingsMeshToDS.positionWS"),
new Dependency("VaryingsMeshToPS.normalWS", "VaryingsMeshToDS.normalWS"),
new Dependency("VaryingsMeshToPS.tangentWS", "VaryingsMeshToDS.tangentWS"),
new Dependency("VaryingsMeshToPS.texCoord0", "VaryingsMeshToDS.texCoord0"),
new Dependency("VaryingsMeshToPS.texCoord1", "VaryingsMeshToDS.texCoord1"),
new Dependency("VaryingsMeshToPS.texCoord2", "VaryingsMeshToDS.texCoord2"),
new Dependency("VaryingsMeshToPS.texCoord3", "VaryingsMeshToDS.texCoord3"),
new Dependency("VaryingsMeshToPS.color", "VaryingsMeshToDS.color"),
};
public static Dependency[] standardDependencies = new Dependency[]
{
new Dependency("VaryingsMeshToPS.positionWS", "AttributesMesh.positionOS"),
new Dependency("VaryingsMeshToPS.normalWS", "AttributesMesh.normalOS"),
new Dependency("VaryingsMeshToPS.tangentWS", "AttributesMesh.tangentOS"),
new Dependency("VaryingsMeshToPS.texCoord0", "AttributesMesh.uv0"),
new Dependency("VaryingsMeshToPS.texCoord1", "AttributesMesh.uv1"),
new Dependency("VaryingsMeshToPS.texCoord2", "AttributesMesh.uv2"),
new Dependency("VaryingsMeshToPS.texCoord3", "AttributesMesh.uv3"),
new Dependency("VaryingsMeshToPS.color", "AttributesMesh.color"),
};
};
struct VaryingsMeshToDS
{
Vector3 positionWS;
Vector3 normalWS;
[Optional] Vector4 tangentWS;
[Optional] Vector2 texCoord0;
[Optional] Vector2 texCoord1;
[Optional] Vector2 texCoord2;
[Optional] Vector2 texCoord3;
[Optional] Vector4 color;
public static Dependency[] tessellationDependencies = new Dependency[]
{
new Dependency("VaryingsMeshToDS.tangentWS", "VaryingsMeshToPS.tangentWS"),
new Dependency("VaryingsMeshToDS.texCoord0", "VaryingsMeshToPS.texCoord0"),
new Dependency("VaryingsMeshToDS.texCoord1", "VaryingsMeshToPS.texCoord1"),
new Dependency("VaryingsMeshToDS.texCoord2", "VaryingsMeshToPS.texCoord2"),
new Dependency("VaryingsMeshToDS.texCoord3", "VaryingsMeshToPS.texCoord3"),
new Dependency("VaryingsMeshToDS.color", "VaryingsMeshToPS.color"),
};
};
struct FragInputs
{
public static Dependency[] dependencies = new Dependency[]
{
new Dependency("FragInputs.positionWS", "VaryingsMeshToPS.positionWS"),
new Dependency("FragInputs.worldToTangent", "VaryingsMeshToPS.tangentWS"),
new Dependency("FragInputs.worldToTangent", "VaryingsMeshToPS.normalWS"),
new Dependency("FragInputs.texCoord0", "VaryingsMeshToPS.texCoord0"),
new Dependency("FragInputs.texCoord1", "VaryingsMeshToPS.texCoord1"),
new Dependency("FragInputs.texCoord2", "VaryingsMeshToPS.texCoord2"),
new Dependency("FragInputs.texCoord3", "VaryingsMeshToPS.texCoord3"),
new Dependency("FragInputs.color", "VaryingsMeshToPS.color"),
new Dependency("FragInputs.isFrontFace", "VaryingsMeshToPS.cullFace"),
};
};
struct SurfaceDescriptionInputs
{
[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[]
{
new Dependency("SurfaceDescriptionInputs.WorldSpaceNormal", "FragInputs.worldToTangent"),
new Dependency("SurfaceDescriptionInputs.ObjectSpaceNormal", "SurfaceDescriptionInputs.WorldSpaceNormal"),
new Dependency("SurfaceDescriptionInputs.ViewSpaceNormal", "SurfaceDescriptionInputs.WorldSpaceNormal"),
new Dependency("SurfaceDescriptionInputs.WorldSpaceTangent", "FragInputs.worldToTangent"),
new Dependency("SurfaceDescriptionInputs.ObjectSpaceTangent", "SurfaceDescriptionInputs.WorldSpaceTangent"),
new Dependency("SurfaceDescriptionInputs.ViewSpaceTangent", "SurfaceDescriptionInputs.WorldSpaceTangent"),
new Dependency("SurfaceDescriptionInputs.WorldSpaceBiTangent", "FragInputs.worldToTangent"),
new Dependency("SurfaceDescriptionInputs.ObjectSpaceBiTangent", "SurfaceDescriptionInputs.WorldSpaceBiTangent"),
new Dependency("SurfaceDescriptionInputs.ViewSpaceBiTangent", "SurfaceDescriptionInputs.WorldSpaceBiTangent"),
new Dependency("SurfaceDescriptionInputs.WorldSpacePosition", "FragInputs.positionWS"),
new Dependency("SurfaceDescriptionInputs.ObjectSpacePosition", "FragInputs.positionWS"),
new Dependency("SurfaceDescriptionInputs.ViewSpacePosition", "FragInputs.positionWS"),
new Dependency("SurfaceDescriptionInputs.WorldSpaceViewDirection", "FragInputs.positionWS"), // we build WorldSpaceViewDirection using FragInputs.positionWS in GetWorldSpaceNormalizeViewDir()
new Dependency("SurfaceDescriptionInputs.ObjectSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceViewDirection"),
new Dependency("SurfaceDescriptionInputs.ViewSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceViewDirection"),
new Dependency("SurfaceDescriptionInputs.TangentSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceViewDirection"),
new Dependency("SurfaceDescriptionInputs.TangentSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceTangent"),
new Dependency("SurfaceDescriptionInputs.TangentSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceBiTangent"),
new Dependency("SurfaceDescriptionInputs.TangentSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceNormal"),
new Dependency("SurfaceDescriptionInputs.screenPosition", "FragInputs.positionSS"),
new Dependency("SurfaceDescriptionInputs.uv0", "FragInputs.texCoord0"),
new Dependency("SurfaceDescriptionInputs.uv1", "FragInputs.texCoord1"),
new Dependency("SurfaceDescriptionInputs.uv2", "FragInputs.texCoord2"),
new Dependency("SurfaceDescriptionInputs.uv3", "FragInputs.texCoord3"),
new Dependency("SurfaceDescriptionInputs.vertexColor", "FragInputs.color"),
};
};
static void AddActiveFieldsFromGraphRequirements(HashSet<string> activeFields, ShaderGraphRequirements requirements)
{
if (requirements.requiresScreenPosition)
{
activeFields.Add("SurfaceDescriptionInputs.screenPosition");
}
if (requirements.requiresVertexColor)
{
activeFields.Add("SurfaceDescriptionInputs.vertexColor");
}
if (requirements.requiresNormal != 0)
{
if ((requirements.requiresNormal & NeededCoordinateSpace.Object) > 0)
activeFields.Add("SurfaceDescriptionInputs.ObjectSpaceNormal");
if ((requirements.requiresNormal & NeededCoordinateSpace.View) > 0)
activeFields.Add("SurfaceDescriptionInputs.ViewSpaceNormal");
if ((requirements.requiresNormal & NeededCoordinateSpace.World) > 0)
activeFields.Add("SurfaceDescriptionInputs.WorldSpaceNormal");
if ((requirements.requiresNormal & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("SurfaceDescriptionInputs.TangentSpaceNormal");
}
if (requirements.requiresTangent != 0)
{
if ((requirements.requiresTangent & NeededCoordinateSpace.Object) > 0)
activeFields.Add("SurfaceDescriptionInputs.ObjectSpaceTangent");
if ((requirements.requiresTangent & NeededCoordinateSpace.View) > 0)
activeFields.Add("SurfaceDescriptionInputs.ViewSpaceTangent");
if ((requirements.requiresTangent & NeededCoordinateSpace.World) > 0)
activeFields.Add("SurfaceDescriptionInputs.WorldSpaceTangent");
if ((requirements.requiresTangent & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("SurfaceDescriptionInputs.TangentSpaceTangent");
}
if (requirements.requiresBitangent != 0)
{
if ((requirements.requiresBitangent & NeededCoordinateSpace.Object) > 0)
activeFields.Add("SurfaceDescriptionInputs.ObjectSpaceBiTangent");
if ((requirements.requiresBitangent & NeededCoordinateSpace.View) > 0)
activeFields.Add("SurfaceDescriptionInputs.ViewSpaceBiTangent");
if ((requirements.requiresBitangent & NeededCoordinateSpace.World) > 0)
activeFields.Add("SurfaceDescriptionInputs.WorldSpaceBiTangent");
if ((requirements.requiresBitangent & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("SurfaceDescriptionInputs.TangentSpaceBiTangent");
}
if (requirements.requiresViewDir != 0)
{
if ((requirements.requiresViewDir & NeededCoordinateSpace.Object) > 0)
activeFields.Add("SurfaceDescriptionInputs.ObjectSpaceViewDirection");
if ((requirements.requiresViewDir & NeededCoordinateSpace.View) > 0)
activeFields.Add("SurfaceDescriptionInputs.ViewSpaceViewDirection");
if ((requirements.requiresViewDir & NeededCoordinateSpace.World) > 0)
activeFields.Add("SurfaceDescriptionInputs.WorldSpaceViewDirection");
if ((requirements.requiresViewDir & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("SurfaceDescriptionInputs.TangentSpaceViewDirection");
}
if (requirements.requiresPosition != 0)
{
if ((requirements.requiresPosition & NeededCoordinateSpace.Object) > 0)
activeFields.Add("SurfaceDescriptionInputs.ObjectSpacePosition");
if ((requirements.requiresPosition & NeededCoordinateSpace.View) > 0)
activeFields.Add("SurfaceDescriptionInputs.ViewSpacePosition");
if ((requirements.requiresPosition & NeededCoordinateSpace.World) > 0)
activeFields.Add("SurfaceDescriptionInputs.WorldSpacePosition");
if ((requirements.requiresPosition & NeededCoordinateSpace.Tangent) > 0)
activeFields.Add("SurfaceDescriptionInputs.TangentSpacePosition");
}
foreach (var channel in requirements.requiresMeshUVs.Distinct())
{
activeFields.Add("SurfaceDescriptionInputs." + channel.GetUVName());
}
}
// TODO : split this function into buildActiveFields and buildHLSLTypeDeclaration functions
public static void Generate(
ShaderGenerator codeResult,
ShaderGenerator graphInputsResult,
ShaderGraphRequirements graphRequirements,
List<string> passRequiredFields, // fields the pass requires
CoordinateSpace preferedCoordinateSpace,
HashSet<string> activeFields)
{
if (preferedCoordinateSpace == CoordinateSpace.Tangent)
preferedCoordinateSpace = CoordinateSpace.World;
// build initial requirements
AddActiveFieldsFromGraphRequirements(activeFields, graphRequirements);
if (passRequiredFields != null)
{
foreach (var requiredField in passRequiredFields)
{
activeFields.Add(requiredField);
}
}
// propagate requirements using dependencies
{
ShaderSpliceUtil.ApplyDependencies(
activeFields,
new List<Dependency[]>()
{
FragInputs.dependencies,
VaryingsMeshToPS.standardDependencies,
SurfaceDescriptionInputs.dependencies,
});
}
// generate code based on requirements
ShaderSpliceUtil.BuildType(typeof(AttributesMesh), activeFields, codeResult);
ShaderSpliceUtil.BuildType(typeof(VaryingsMeshToPS), activeFields, codeResult);
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 struct Pass
{
public string Name;
public string LightMode;
public string ShaderPassName;
public List<string> Includes;
public string TemplateName;
public List<string> ExtraDefines;
public List<int> VertexShaderSlots; // These control what slots are used by the pass vertex shader
public List<int> PixelShaderSlots; // These control what slots are used by the pass pixel shader
public string CullOverride;
public string BlendOverride;
public string BlendOpOverride;
public string ZTestOverride;
public string ZWriteOverride;
public string ColorMaskOverride;
public List<string> StencilOverride;
public List<string> RequiredFields; // feeds into the dependency analysis
public ShaderGraphRequirements requirements;
};
public static class HDSubShaderUtilities
{
public static void BuildRenderStatesFromPassAndMaterialOptions(
Pass pass,
SurfaceMaterialOptions materialOptions,
ShaderStringBuilder blendCode,
ShaderStringBuilder cullCode,
ShaderStringBuilder zTestCode,
ShaderStringBuilder zWriteCode,
ShaderStringBuilder stencilCode,
ShaderStringBuilder colorMaskCode)
{
if (pass.BlendOverride != null)
{
blendCode.AppendLine(pass.BlendOverride);
}
else
{
materialOptions.GetBlend(blendCode);
}
if (pass.BlendOpOverride != null)
{
blendCode.AppendLine(pass.BlendOpOverride);
}
if (pass.CullOverride != null)
{
cullCode.AppendLine(pass.CullOverride);
}
else
{
materialOptions.GetCull(cullCode);
}
if (pass.ZTestOverride != null)
{
zTestCode.AppendLine(pass.ZTestOverride);
}
else
{
materialOptions.GetDepthTest(zTestCode);
}
if (pass.ZWriteOverride != null)
{
zWriteCode.AppendLine(pass.ZWriteOverride);
}
else
{
materialOptions.GetDepthWrite(zWriteCode);
}
if (pass.ColorMaskOverride != null)
{
colorMaskCode.AppendLine(pass.ColorMaskOverride);
}
else
{
// material option default is to not declare anything for color mask
}
if (pass.StencilOverride != null)
{
foreach (var str in pass.StencilOverride)
{
stencilCode.AppendLine(str);
}
}
else
{
stencilCode.AppendLine("// Default Stencil");
}
}
public static SurfaceMaterialOptions BuildMaterialOptions(SurfaceType surfaceType, AlphaMode alphaMode, bool twoSided)
{
SurfaceMaterialOptions materialOptions = new SurfaceMaterialOptions();
if (surfaceType == SurfaceType.Opaque)
{
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.Zero;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.On;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Geometry;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Opaque;
}
else
{
switch (alphaMode)
{
case AlphaMode.Alpha:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.SrcAlpha;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.OneMinusSrcAlpha;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
case AlphaMode.Additive:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
// TODO: other blend modes
}
}
materialOptions.cullMode = twoSided ? SurfaceMaterialOptions.CullMode.Off : SurfaceMaterialOptions.CullMode.Back;
return materialOptions;
}
}
}

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/ShaderGraph/HDUnlitSubShader.cs


using System.IO;
using System.Linq;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
// [Serializable] ??
public class HDUnlitSubShader : IUnlitSubShader

return subShader.GetShaderString(0);
}
}
}
}

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

正在加载...
取消
保存