浏览代码

Merge remote-tracking branch 'refs/remotes/origin/master' into hdrp-xr-clustered

/main
sebastienlagarde 6 年前
当前提交
aa772a18
共有 272 个文件被更改,包括 1518 次插入1412 次删除
  1. 6
      README.md
  2. 12
      ScriptableRenderPipeline/Core/CoreRP/CoreUtils.cs
  3. 8
      ScriptableRenderPipeline/Core/CoreRP/Debugging/DebugManager.cs
  4. 15
      ScriptableRenderPipeline/Core/CoreRP/Debugging/Prefabs/Scripts/UIFoldout.cs
  5. 259
      ScriptableRenderPipeline/Core/CoreRP/Editor/CoreEditorUtils.cs
  6. 6
      ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugState.cs
  7. 36
      ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugUIDrawer.Builtins.cs
  8. 1
      ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugUIDrawer.cs
  9. 35
      ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugWindow.cs
  10. 29
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/EntityLighting.hlsl
  11. 5
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Packing.hlsl
  12. 22
      ScriptableRenderPipeline/Core/CoreRP/Shadow/Shadow.cs
  13. 8
      ScriptableRenderPipeline/Core/CoreRP/Shadow/ShadowBase.cs
  14. 23
      ScriptableRenderPipeline/Core/CoreRP/TextureCache.cs
  15. 2
      ScriptableRenderPipeline/Core/package.json
  16. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDAdditionalCameraData.cs
  17. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.cs
  18. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.hlsl
  19. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/MaterialDebug.cs
  20. 32
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalProjectorComponent.cs
  21. 143
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalSystem.cs
  22. 15
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraEditor.cs
  23. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraUI.cs
  24. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDAssetFactory.cs
  25. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.Styles.cs
  26. 19
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.cs
  27. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.ProbeUtility.cs
  28. 17
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs
  29. 17
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.Drawers.cs
  30. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.cs
  31. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Drawers.cs
  32. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/SerializedHDReflectionProbe.cs
  33. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/SerializedPlanarReflectionProbe.cs
  34. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Unlit/BaseUnlitUI.cs
  35. 28
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/FrameSettingsUI.cs
  36. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/LightLoopSettingsUI.cs
  37. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/RenderPipelineSettingsUI.cs
  38. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/SerializedFrameSettings.cs
  39. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Sky/HDRISky/HDRISkyEditor.cs
  40. 61
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs
  41. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipelineAsset.asset
  42. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDAdditionalLightData.cs
  43. 263
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightDefinition.cs
  44. 301
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightDefinition.cs.hlsl
  45. 114
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs
  46. 40
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopSettings.cs
  47. 19
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/Shadow.hlsl
  48. 22
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/ShadowContext.hlsl
  49. 24
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtilities.hlsl
  50. 33
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtils.cs
  51. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/HDAdditionalReflectionData.cs
  52. 13
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/PlanarReflectionProbe.cs
  53. 23
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/PlanarReflectionProbeCache.cs
  54. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ProbeWrapper.cs
  55. 25
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ReflectionProbeCache.cs
  56. 48
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/VolumeProjection.hlsl
  57. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/MRTBufferManager.cs
  58. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs.hlsl
  59. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalUtilities.hlsl
  60. 21
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GBufferManager.cs
  61. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/RuntimeFilterIBL.cs
  62. 47
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLit.shader
  63. 50
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitTessellation.shader
  64. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.cs
  65. 31
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl
  66. 50
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.shader
  67. 53
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitTessellation.shader
  68. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/MaterialUtilities.hlsl
  69. 105
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipeline/FrameSettings.cs
  70. 13
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/DefaultHDMaterial.mat
  71. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset
  72. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/RenderPipelineResources.cs
  73. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassForward.hlsl
  74. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassGBuffer.hlsl
  75. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISky.cs
  76. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISkyRenderer.cs
  77. 29
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/ProceduralSky/ProceduralSkyRenderer.cs
  78. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyManager.cs
  79. 29
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyRenderingContext.cs
  80. 2
      ScriptableRenderPipeline/HDRenderPipeline/package.json
  81. 33
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/LightweightAssetEditor.cs
  82. 23
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGraph/lightweightPBRForwardPass.template
  83. 55
      ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs
  84. 50
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Core.hlsl
  85. 3
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputBuiltin.hlsl
  86. 40
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurface.hlsl
  87. 53
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Lighting.hlsl
  88. 74
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassLit.hlsl
  89. 2
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMeta.hlsl
  90. 4
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassShadow.hlsl
  91. 104
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Particles.hlsl
  92. 25
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Shadows.hlsl
  93. 8
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightScreenSpaceShadows.shader
  94. 2
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandard.shader
  95. 18
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardParticles.shader
  96. 50
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardParticlesUnlit.shader
  97. 5
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardSimpleLighting.shader
  98. 2
      ScriptableRenderPipeline/LightweightPipeline/package.json
  99. 2
      ScriptableRenderPipeline/master-package.json
  100. 13
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/3DObjects/CornelBox/Materials/Cornell Box.mat

6
README.md


__Note: The Master branch is our current development branch and may not work on the latest publicly available version of Unity. You should always use the latest release tag and latest Unity beta version for testing purposes.__
To use the latest version of the SRP, follow the instructions below:
This repository consists of a folder that needs to be placed in the Assets\ folder of your Unity project. We recommend creating a new project to test SRP. Do not clone this repo into an existing project unless you want to break it, or unless you are updating to a newer version of the SRP repo.
This repository consists of a folder that needs to be placed in the Assets\ folder of your Unity project. We recommend creating a new project to test SRP. Do not clone this repo into an existing project unless you want to break it, or unless you are updating to a newer version of the SRP repo. Your project's `packages.json` file (in either `UnityPackageManager/` or `Packages/`) does not have a dependency on any of the packages in this repository or the contained submodules.
You can use the GitHub desktop app to clone the latest version of the SRP repo or you can use GitHub console commands.

```
> git checkout Unity-2018.1.0b2 (or the latest tag)
> git submodule update --init --recursive --remote (This command fetches the Postprocessing module, which is needed to use SRP)
> git submodule update --init (This command fetches the Postprocessing module, which is needed to use SRP)
```
### To download the repo using console commands:

> git clone https://github.com/Unity-Technologies/ScriptableRenderPipeline
> cd ScriptableRenderPipeline
> git checkout Unity-2018.1.0b2 (or the latest tag)
> git submodule update --init --recursive --remote (This command fetches the Postprocessing module, which is needed to use SRP)
> git submodule update --init (This command fetches the Postprocessing module, which is needed to use SRP)
```
## Scriptable Render Pipeline Assets

12
ScriptableRenderPipeline/Core/CoreRP/CoreUtils.cs


return temp;
}
public static string GetTextureAutoName(int width, int height, TextureFormat format, TextureDimension dim = TextureDimension.None, string name = "", bool mips = false, int depth = 0)
{
string temp;
if(depth == 0)
temp = string.Format("{0}x{1}_{2}{3}", width, height, format, mips ? "_Mips" : "");
else
temp = string.Format("{0}x{1}x{2}_{3}{4}", width, height, depth, format, mips ? "_Mips" : "");
temp = String.Format("{0}_{1}_{2}", name == "" ? "Texture" : name, (dim == TextureDimension.None) ? "" : dim.ToString(), temp);
return temp;
}
public static void ClearCubemap(CommandBuffer cmd, RenderTexture renderTexture, Color clearColor, bool clearMips = false)
{
int mipCount = 1;

8
ScriptableRenderPipeline/Core/CoreRP/Debugging/DebugManager.cs


{
get
{
var uiManager = UnityObject.FindObjectOfType<DebugUIHandlerCanvas>();
// Might be needed to update the reference after domain reload
if (uiManager != null)
{
m_Root = uiManager.gameObject;
}
return m_Root != null && m_Root.activeInHierarchy;
}
set

15
ScriptableRenderPipeline/Core/CoreRP/Debugging/Prefabs/Scripts/UIFoldout.cs


public GameObject arrowOpened;
public GameObject arrowClosed;
protected override void Awake()
protected override void Start()
base.Awake();
base.Start();
onValueChanged.AddListener(SetState);
SetState(isOn);
}

if (arrowOpened == null || arrowClosed == null || content == null)
return;
arrowOpened.SetActive(state);
arrowClosed.SetActive(!state);
content.SetActive(state);
if (arrowOpened.activeSelf != state)
arrowOpened.SetActive(state);
if (arrowClosed.activeSelf == state)
arrowClosed.SetActive(!state);
if (content.activeSelf != state)
content.SetActive(state);
if (rebuildLayout)
LayoutRebuilder.ForceRebuildLayoutImmediate(transform.parent as RectTransform);

259
ScriptableRenderPipeline/Core/CoreRP/Editor/CoreEditorUtils.cs


return value;
}
public static void DrawPopup(GUIContent label, SerializedProperty property, string[] options)
{
var mode = property.intValue;
EditorGUI.BeginChangeCheck();
if (mode >= options.Length)
Debug.LogError(string.Format("Invalid option while trying to set {0}", label.text));
mode = EditorGUILayout.Popup(label, mode, options);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(property.objectReferenceValue, property.name);
property.intValue = mode;
}
}
public static void DrawCascadeSplitGUI<T>(ref SerializedProperty shadowCascadeSplit)
{
float[] cascadePartitionSizes = null;
System.Type type = typeof(T);
if (type == typeof(float))
{
cascadePartitionSizes = new float[] { shadowCascadeSplit.floatValue };
}
else if (type == typeof(Vector3))
{
Vector3 splits = shadowCascadeSplit.vector3Value;
cascadePartitionSizes = new float[]
{
Mathf.Clamp(splits[0], 0.0f, 1.0f),
Mathf.Clamp(splits[1] - splits[0], 0.0f, 1.0f),
Mathf.Clamp(splits[2] - splits[1], 0.0f, 1.0f)
};
}
if (cascadePartitionSizes != null)
{
EditorGUI.BeginChangeCheck();
ShadowCascadeSplitGUI.HandleCascadeSliderGUI(ref cascadePartitionSizes);
if (EditorGUI.EndChangeCheck())
{
if (type == typeof(float))
shadowCascadeSplit.floatValue = cascadePartitionSizes[0];
else
{
Vector3 updatedValue = new Vector3();
updatedValue[0] = cascadePartitionSizes[0];
updatedValue[1] = updatedValue[0] + cascadePartitionSizes[1];
updatedValue[2] = updatedValue[1] + cascadePartitionSizes[2];
shadowCascadeSplit.vector3Value = updatedValue;
}
}
}
}
public static void RemoveMaterialKeywords(Material material)
{
material.shaderKeywords = null;

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

6
ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugState.cs


[SerializeField]
protected string m_QueryPath;
// We need this to keep track of the state modified in the current frame.
// This helps reduces the cost of re-applying states to original widgets and is also needed
// when two states point to the same value (e.g. when using split enums like HDRP does for
// the `fullscreenDebugMode`.
internal static DebugState m_CurrentDirtyState;
public string queryPath
{
get { return m_QueryPath; }

36
ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugUIDrawer.Builtins.cs


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

EditorGUI.BeginChangeCheck();
var rect = PrepareControlRect();
bool value = EditorGUI.Toggle(rect, CoreEditorUtils.GetContent(w.displayName), s.value);
bool value = EditorGUI.Toggle(rect, CoreEditorUtils.GetContent(w.displayName), w.GetValue());
if (EditorGUI.EndChangeCheck())
Apply(w, s, value);

var rect = PrepareControlRect();
int value = w.min != null && w.max != null
? EditorGUI.IntSlider(rect, CoreEditorUtils.GetContent(w.displayName), s.value, w.min(), w.max())
: EditorGUI.IntField(rect, CoreEditorUtils.GetContent(w.displayName), s.value);
? EditorGUI.IntSlider(rect, CoreEditorUtils.GetContent(w.displayName), w.GetValue(), w.min(), w.max())
: EditorGUI.IntField(rect, CoreEditorUtils.GetContent(w.displayName), w.GetValue());
if (EditorGUI.EndChangeCheck())
Apply(w, s, value);

// No UIntField so we need to max to 0 ourselves or the value will wrap around
var rect = PrepareControlRect();
int tmp = w.min != null && w.max != null
? EditorGUI.IntSlider(rect, CoreEditorUtils.GetContent(w.displayName), Mathf.Max(0, (int)s.value), Mathf.Max(0, (int)w.min()), Mathf.Max(0, (int)w.max()))
: EditorGUI.IntField(rect, CoreEditorUtils.GetContent(w.displayName), Mathf.Max(0, (int)s.value));
? EditorGUI.IntSlider(rect, CoreEditorUtils.GetContent(w.displayName), Mathf.Max(0, (int)w.GetValue()), Mathf.Max(0, (int)w.min()), Mathf.Max(0, (int)w.max()))
: EditorGUI.IntField(rect, CoreEditorUtils.GetContent(w.displayName), Mathf.Max(0, (int)w.GetValue()));
uint value = (uint)Mathf.Max(0, tmp);

var rect = PrepareControlRect();
float value = w.min != null && w.max != null
? EditorGUI.Slider(rect, CoreEditorUtils.GetContent(w.displayName), s.value, w.min(), w.max())
: EditorGUI.FloatField(rect, CoreEditorUtils.GetContent(w.displayName), s.value);
? EditorGUI.Slider(rect, CoreEditorUtils.GetContent(w.displayName), w.GetValue(), w.min(), w.max())
: EditorGUI.FloatField(rect, CoreEditorUtils.GetContent(w.displayName), w.GetValue());
if (EditorGUI.EndChangeCheck())
Apply(w, s, value);

EditorGUI.BeginChangeCheck();
int value = s.value;
int value = w.GetValue();
if (w.enumNames == null || w.enumValues == null)
{
EditorGUILayout.LabelField("Can't draw an empty enumeration.");

var rect = PrepareControlRect();
value = EditorGUI.IntPopup(rect, CoreEditorUtils.GetContent(w.displayName), s.value, w.enumNames, w.enumValues);
int index = Array.IndexOf(w.enumValues, w.GetValue());
// Fallback just in case, we may be handling sub/sectionned enums here
if (index < 0)
value = w.enumValues[0];
value = EditorGUI.IntPopup(rect, CoreEditorUtils.GetContent(w.displayName), value, w.enumNames, w.enumValues);
}
if (EditorGUI.EndChangeCheck())

EditorGUI.BeginChangeCheck();
bool value = EditorGUILayout.Foldout(s.value, CoreEditorUtils.GetContent(w.displayName), true);
bool value = EditorGUILayout.Foldout(w.GetValue(), CoreEditorUtils.GetContent(w.displayName), true);
if (EditorGUI.EndChangeCheck())
Apply(w, s, value);

EditorGUI.BeginChangeCheck();
var rect = PrepareControlRect();
var value = EditorGUI.ColorField(rect, CoreEditorUtils.GetContent(w.displayName), s.value, w.showPicker, w.showAlpha, w.hdr);
var value = EditorGUI.ColorField(rect, CoreEditorUtils.GetContent(w.displayName), w.GetValue(), w.showPicker, w.showAlpha, w.hdr);
if (EditorGUI.EndChangeCheck())
Apply(w, s, value);

EditorGUI.BeginChangeCheck();
var value = EditorGUILayout.Vector2Field(w.displayName, s.value);
var value = EditorGUILayout.Vector2Field(w.displayName, w.GetValue());
if (EditorGUI.EndChangeCheck())
Apply(w, s, value);

EditorGUI.BeginChangeCheck();
var value = EditorGUILayout.Vector3Field(w.displayName, s.value);
var value = EditorGUILayout.Vector3Field(w.displayName, w.GetValue());
if (EditorGUI.EndChangeCheck())
Apply(w, s, value);

EditorGUI.BeginChangeCheck();
var value = EditorGUILayout.Vector4Field(w.displayName, s.value);
var value = EditorGUILayout.Vector4Field(w.displayName, w.GetValue());
if (EditorGUI.EndChangeCheck())
Apply(w, s, value);

1
ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugUIDrawer.cs


state.SetValue(value, widget);
widget.SetValue(value);
EditorUtility.SetDirty(state);
DebugState.m_CurrentDirtyState = state;
UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
}

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


void OnDestroy()
{
DebugManager.instance.onSetDirty -= MarkDirty;
Undo.ClearUndo(m_Settings);
if (m_WidgetStates != null)
{

}
}
public void ApplyStates()
public void ApplyStates(bool forceApplyAll = false)
if (!forceApplyAll && DebugState.m_CurrentDirtyState != null)
{
ApplyState(DebugState.m_CurrentDirtyState.queryPath, DebugState.m_CurrentDirtyState);
DebugState.m_CurrentDirtyState = null;
return;
}
{
var widget = DebugManager.instance.GetItem(state.Key) as DebugUI.IValueField;
ApplyState(state.Key, state.Value);
DebugState.m_CurrentDirtyState = null;
}
void ApplyState(string queryPath, DebugState state)
{
var widget = DebugManager.instance.GetItem(queryPath) as DebugUI.IValueField;
if (widget == null)
continue;
if (widget == null)
return;
widget.SetValue(state.Value.GetValue());
}
widget.SetValue(state.GetValue());
}
void OnUndoRedoPerformed()

// Something has been undone / redone, re-apply states to the debug tree
if (stateHash != m_Settings.currentStateHash)
{
ApplyStates();
ApplyStates(true);
m_Settings.currentStateHash = stateHash;
}

if (m_Settings.selectedPanel == i && Event.current.type == EventType.Repaint)
s_Styles.selected.Draw(elementRect, false, false, false, false);
if (GUI.Toggle(elementRect, m_Settings.selectedPanel == i, panel.displayName, s_Styles.sectionElement))
EditorGUI.BeginChangeCheck();
GUI.Toggle(elementRect, m_Settings.selectedPanel == i, panel.displayName, s_Styles.sectionElement);
if (EditorGUI.EndChangeCheck())
Undo.RecordObject(m_Settings, "Debug Panel Selection");
Undo.RegisterCompleteObjectUndo(m_Settings, "Debug Panel Selection");
m_Settings.selectedPanel = i;
}
}

29
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/EntityLighting.hlsl


// It is required for other platform that aren't supporting this format to implement variant of these functions
// (But these kind of platform should use regular render loop and not news shaders).
// RGBM lightmaps are currently always gamma encoded, so we use a constant of range^2.2 = 5^2.2
#define LIGHTMAP_RGBM_RANGE 34.493242
// DLDR lightmaps are currently always gamma encoded, so we use a constant of 2.0^2.2 = 4.59
#define LIGHTMAP_DLDR_RANGE 4.59
// TODO: This is the max value allowed for emissive (bad name - but keep for now to retrieve it) (It is 8^2.2 (gamma) and 8 is the limit of punctual light slider...), comme from UnityCg.cginc. Fix it!
// Ask Jesper if this can be change for HDRenderPipeline
#define EMISSIVE_RGBM_SCALE 97.0

return rgbm;
}
real3 UnpackLightmapRGBM(real4 rgbmInput)
real3 UnpackLightmapRGBM(real4 rgbmInput, real4 decodeInstructions)
// RGBM lightmaps are always gamma encoded for now, so decode with that in mind:
return rgbmInput.rgb * pow(rgbmInput.a, 2.2) * LIGHTMAP_RGBM_RANGE;
return rgbmInput.rgb * pow(rgbmInput.a, decodeInstructions.y) * decodeInstructions.x;
real3 UnpackLightmapDoubleLDR(real4 encodedColor)
real3 UnpackLightmapDoubleLDR(real4 encodedColor, real4 decodeInstructions)
return encodedColor.rgb * LIGHTMAP_DLDR_RANGE;
return encodedColor.rgb * decodeInstructions.x;
real3 DecodeLightmap(real4 encodedIlluminance)
real3 DecodeLightmap(real4 encodedIlluminance, real4 decodeInstructions)
return UnpackLightmapRGBM(encodedIlluminance);
return UnpackLightmapRGBM(encodedIlluminance, decodeInstructions);
return UnpackLightmapDoubleLDR(encodedIlluminance);
return UnpackLightmapDoubleLDR(encodedIlluminance, decodeInstructions);
#endif
}

return (decodeInstructions.x * pow(alpha, decodeInstructions.y)) * encodedIrradiance.rgb;
}
real3 SampleSingleLightmap(TEXTURE2D_ARGS(lightmapTex, lightmapSampler), float2 uv, float4 transform, bool encodedLightmap)
real3 SampleSingleLightmap(TEXTURE2D_ARGS(lightmapTex, lightmapSampler), float2 uv, float4 transform, bool encodedLightmap, real4 decodeInstructions)
{
// transform is scale and bias
uv = uv * transform.xy + transform.zw;

{
real4 encodedIlluminance = SAMPLE_TEXTURE2D(lightmapTex, lightmapSampler, uv).rgba;
illuminance = DecodeLightmap(encodedIlluminance);
illuminance = DecodeLightmap(encodedIlluminance, decodeInstructions);
}
else
{

}
real3 SampleDirectionalLightmap(TEXTURE2D_ARGS(lightmapTex, lightmapSampler), TEXTURE2D_ARGS(lightmapDirTex, lightmapDirSampler), float2 uv, float4 transform, float3 normalWS, bool encodedLightmap)
real3 SampleDirectionalLightmap(TEXTURE2D_ARGS(lightmapTex, lightmapSampler), TEXTURE2D_ARGS(lightmapDirTex, lightmapDirSampler), float2 uv, float4 transform, float3 normalWS, bool encodedLightmap, real4 decodeInstructions)
{
// In directional mode Enlighten bakes dominant light direction
// in a way, that using it for half Lambert and then dividing by a "rebalancing coefficient"

if (encodedLightmap)
{
real4 encodedIlluminance = SAMPLE_TEXTURE2D(lightmapTex, lightmapSampler, uv).rgba;
illuminance = DecodeLightmap(encodedIlluminance);
illuminance = DecodeLightmap(encodedIlluminance, decodeInstructions);
}
else
{

5
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Packing.hlsl


return normalize(normal);
}
real3 UnpackNormalRGBNoScale(real4 packedNormal)
{
return packedNormal.rgb * 2.0 - 1.0;
}
real3 UnpackNormalAG(real4 packedNormal, real scale = 1.0)
{
real3 normal;

22
ScriptableRenderPipeline/Core/CoreRP/Shadow/Shadow.cs


// UI stuff
protected struct ValRange
{
GUIContent Name;
#if UNITY_EDITOR
GUIContent Name;
float ValMax;
#endif
float ValMax;
public ValRange( string name, float valMin, float valDef, float valMax, float valScale ) { Name = new GUIContent( name ); ValMin = valMin; ValDef = valDef; ValMax = valMax; ValScale = valScale; }
public ValRange( string name, float valMin, float valDef, float valMax, float valScale )
{
#if UNITY_EDITOR
Name = new GUIContent( name );
ValMin = valMin;
ValMax = valMax;
#endif
ValDef = valDef;
ValScale = valScale;
}
#if UNITY_EDITOR
public void Slider( ref int currentVal ) { currentVal = ShadowUtils.Asint( ValScale * UnityEditor.EditorGUILayout.Slider( Name, ShadowUtils.Asfloat( currentVal ) / ValScale, ValMin, ValMax ) ); }
#else

int sa, sv, sp;
asd.GetShadowAlgorithm( out sa, out sv, out sp );
sreq.shadowAlgorithm = ShadowUtils.Pack( (ShadowAlgorithm) sa, (ShadowVariant) sv, (ShadowPrecision) sp );
GPUShadowAlgorithm packed_algo = ShadowUtils.Pack( (ShadowAlgorithm) sa, (ShadowVariant) sv, (ShadowPrecision) sp );
GetGlobalShadowOverride( shadowType, ref packed_algo );
sreq.shadowAlgorithm = packed_algo;
totalRequestCount += (uint) facecount;
requestsGranted.AddUnchecked( sreq );
totalSlots--;

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


{
m_GlobalOverrides[(int)shadowType].enabled = enabled;
}
public bool GetGlobalShadowOverride( GPUShadowType shadowType, ref GPUShadowAlgorithm algo )
{
if( m_GlobalOverrides[(int)shadowType].enabled )
algo = ShadowUtils.Pack( m_GlobalOverrides[(int)shadowType].algorithm, m_GlobalOverrides[(int)shadowType].variant, m_GlobalOverrides[(int)shadowType].precision );
return m_GlobalOverrides[(int)shadowType].enabled;
}
}
// This is the struct passed into shaders

23
ScriptableRenderPipeline/Core/CoreRP/TextureCache.cs


{
private Texture2DArray m_Cache;
public TextureCache2D(string cacheName = "")
: base(cacheName)
{
}
public override void TransferToSlice(CommandBuffer cmd, int sliceIndex, Texture texture)
{
var mismatch = (m_Cache.width != texture.width) || (m_Cache.height != texture.height);

m_Cache = new Texture2DArray(width, height, numTextures, format, isMipMapped)
{
hideFlags = HideFlags.HideAndDontSave,
wrapMode = TextureWrapMode.Clamp
wrapMode = TextureWrapMode.Clamp,
name = CoreUtils.GetTextureAutoName(width, height, format, TextureDimension.Tex2DArray, depth: numTextures, name: m_CacheName)
};
return res;

private int m_CubeMipLevelPropName;
private int m_cubeSrcTexPropName;
public TextureCacheCubemap(string cacheName = "")
: base(cacheName)
{
}
public override void TransferToSlice(CommandBuffer cmd, int sliceIndex, Texture texture)
{
if (!TextureCache.supportsCubemapArrayTextures)

wrapMode = TextureWrapMode.Repeat,
wrapModeV = TextureWrapMode.Clamp,
filterMode = FilterMode.Trilinear,
anisoLevel = 0
anisoLevel = 0,
name = CoreUtils.GetTextureAutoName(panoWidthTop, panoHeightTop, format, TextureDimension.Tex2DArray, depth: numCubeMaps, name: m_CacheName)
};
m_NumPanoMipLevels = isMipMapped ? GetNumMips(panoWidthTop, panoHeightTop) : 1;

hideFlags = HideFlags.HideAndDontSave,
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Trilinear,
anisoLevel = 0 // It is important to set 0 here, else unity force anisotropy filtering
anisoLevel = 0, // It is important to set 0 here, else unity force anisotropy filtering
name = CoreUtils.GetTextureAutoName(width, width, format, TextureDimension.CubeArray, depth: numCubeMaps, name: m_CacheName)
};
}

public abstract class TextureCache
{
protected int m_NumMipLevels;
protected string m_CacheName;
public static bool isMobileBuildTarget
{

// assert(m_SliceArray[m_SortedIdxArray[q-1]].CountLRU>=m_SliceArray[m_SortedIdxArray[q]].CountLRU);
}
protected TextureCache()
protected TextureCache(string cacheName)
m_CacheName = cacheName;
m_NumTextures = 0;
m_NumMipLevels = 0;
}

2
ScriptableRenderPipeline/Core/package.json


"version": "0.1.33",
"unity": "2018.1",
"dependencies": {
"com.unity.postprocessing": "0.2.0"
"com.unity.postprocessing": "2.0.2-preview"
}
}

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDAdditionalCameraData.cs


using UnityEngine.Serialization;
using UnityEngine.Serialization;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{

void UnRegisterDebug()
{
if (m_camera == null)
return;
if (m_IsDebugRegistered)
{
if (m_camera.cameraType != CameraType.Preview && m_camera.cameraType != CameraType.Reflection)

// When LDR, unity render in 8bitSRGB, then do a final shader with sRGB conversion
// What should be done is just in our Post process we convert to sRGB and store in a linear 10bit, but require C++ change...
m_camera = GetComponent<Camera>();
if (m_camera == null)
return;
m_camera.allowHDR = false;
// Tag as dirty so frameSettings are correctly initialize at next HDRenderPipeline.Render() call

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


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

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


}
// 4. Display leading 0
#pragma warning(disable : 3557) // loop only executes for 0 iteration(s)
for (int i = 0; i < leading0; ++i)
if (leading0 > 0)
DrawCharacter('0', fontColor, currentUnormCoord, fixedUnormCoord, flipY, color, -1);
for (int i = 0; i < leading0; ++i)
{
DrawCharacter('0', fontColor, currentUnormCoord, fixedUnormCoord, flipY, color, -1);
}
#pragma warning(default : 3557)
// 5. Display sign
if (intValue < 0 || forceNegativeSign)

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/MaterialDebug.cs


VertexNormalWS,
VertexColor,
VertexColorAlpha,
Last,
// if you add more values here, fix the first entry of next enum
};
// Number must be contiguous

None = 0,
Depth = DebugViewVarying.Last,
Depth = DebugViewVarying.VertexColorAlpha + 1,
Last,
// if you add more values here, fix the first entry of next enum
}
// Number must be contiguous

None = 0,
Tessellation = DebugViewGbuffer.Last,
Tessellation = DebugViewGbuffer.BakeShadowMask3 + 1,
PixelDisplacement,
VertexDisplacement,
TessellationDisplacement,

Last,
}
}

32
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalProjectorComponent.cs


public float m_DrawDistance = 1000.0f;
public float m_FadeScale = 0.9f;
private Material m_OldMaterial = null;
public const int kInvalidIndex = -1;
private int m_CullIndex = kInvalidIndex;
private DecalSystem.DecalHandle m_Handle = null;
public int CullIndex
public DecalSystem.DecalHandle Handle
return this.m_CullIndex;
return this.m_Handle;
this.m_CullIndex = value;
this.m_Handle = value;
}
}

m_Material = hdrp != null ? hdrp.GetDefaultDecalMaterial() : null;
}
DecalSystem.instance.AddDecal(this);
}
public void Start()
{
DecalSystem.instance.AddDecal(this);
if(m_Handle != null)
DecalSystem.instance.RemoveDecal(m_Handle);
m_Handle = DecalSystem.instance.AddDecal(transform, m_DrawDistance, m_FadeScale, m_Material);
DecalSystem.instance.RemoveDecal(this);
DecalSystem.instance.RemoveDecal(m_Handle);
m_Handle = null;
}
// Declare the method signature of the delegate to call.

// handle material changes
if (m_OldMaterial != m_Material)
{
Material tempMaterial = m_Material;
m_Material = m_OldMaterial;
if(m_Material != null)
DecalSystem.instance.RemoveDecal(this);
m_Material = tempMaterial;
DecalSystem.instance.AddDecal(this);
if( m_Handle != null)
DecalSystem.instance.RemoveDecal(m_Handle);
m_Handle = DecalSystem.instance.AddDecal(transform, m_DrawDistance, m_FadeScale, m_Material);
m_OldMaterial = m_Material;
// notify the editor that material has changed so it can update the shader foldout

{
DrawGizmo(true);
// if this object is selected there is a chance the transform was changed so update culling info
DecalSystem.instance.UpdateCachedData(this);
DecalSystem.instance.UpdateCachedData(transform, m_DrawDistance, m_FadeScale, m_Handle);
}
public void OnDrawGizmos()

143
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalSystem.cs


{
public class DecalSystem
{
public const int kInvalidIndex = -1;
public class DecalHandle
{
public DecalHandle(int index, int materialID)
{
m_MaterialID = materialID;
m_Index = index;
}
public static bool IsValid(DecalHandle handle)
{
if (handle == null)
return false;
if (handle.m_Index == kInvalidIndex)
return false;
return true;
}
public int m_MaterialID; // identifies decal set
public int m_Index; // identifies decal within the set
}
static DecalSystem m_Instance;
static public DecalSystem instance
{

{
if (m_DecalAtlas == null)
{
m_DecalAtlas = new TextureCache2D();
m_DecalAtlas = new TextureCache2D("DecalAtlas");
public Camera CurrentCamera
{

return res;
}
public void UpdateCachedData(DecalProjectorComponent decal)
public void UpdateCachedData(Transform transform, float drawDistance, float fadeScale, DecalHandle handle)
m_CachedDecalToWorld[decal.CullIndex] = decal.transform.localToWorldMatrix;
int index = handle.m_Index;
m_CachedDecalToWorld[index] = transform.localToWorldMatrix;
Matrix4x4 decalRotation = Matrix4x4.Rotate(decal.transform.rotation);
Matrix4x4 decalRotation = Matrix4x4.Rotate(transform.rotation);
// z/y axis swap for normal to decal space, Unity is column major
float y0 = decalRotation.m01;
float y1 = decalRotation.m11;

decalRotation.m12 = y1;
decalRotation.m22 = y2;
m_CachedNormalToWorld[decal.CullIndex] = decalRotation;
m_CachedNormalToWorld[index] = decalRotation;
m_CachedDrawDistances[decal.CullIndex].x = decal.m_DrawDistance < instance.DrawDistance
? decal.m_DrawDistance
m_CachedDrawDistances[index].x = drawDistance < instance.DrawDistance
? drawDistance
m_CachedDrawDistances[decal.CullIndex].y = decal.m_FadeScale;
m_BoundingSpheres[decal.CullIndex] = GetDecalProjectBoundingSphere(m_CachedDecalToWorld[decal.CullIndex]);
m_CachedDrawDistances[index].y = fadeScale;
m_BoundingSpheres[index] = GetDecalProjectBoundingSphere(m_CachedDecalToWorld[index]);
public void AddDecal(DecalProjectorComponent decal)
public DecalHandle AddDecal(Transform transform, float drawDistance, float fadeScale, int materialID)
if (m_DecalsCount == m_Decals.Length)
if (m_DecalsCount == m_Handles.Length)
DecalProjectorComponent[] newDecals = new DecalProjectorComponent[m_DecalsCount + kDecalBlockSize];
DecalHandle[] newHandles = new DecalHandle[m_DecalsCount + kDecalBlockSize];
BoundingSphere[] newSpheres = new BoundingSphere[m_DecalsCount + kDecalBlockSize];
Matrix4x4[] newCachedTransforms = new Matrix4x4[m_DecalsCount + kDecalBlockSize];
Matrix4x4[] newCachedNormalToWorld = new Matrix4x4[m_DecalsCount + kDecalBlockSize];

m_Decals.CopyTo(newDecals, 0);
m_Handles.CopyTo(newHandles, 0);
m_Decals = newDecals;
m_Handles = newHandles;
m_BoundingSpheres = newSpheres;
m_CachedDecalToWorld = newCachedTransforms;
m_CachedNormalToWorld = newCachedNormalToWorld;

m_Decals[m_DecalsCount] = decal;
m_Decals[m_DecalsCount].CullIndex = m_DecalsCount;
UpdateCachedData(m_Decals[m_DecalsCount]);
DecalHandle decalHandle = new DecalHandle(m_DecalsCount, materialID);
m_Handles[m_DecalsCount] = decalHandle;
UpdateCachedData(transform, drawDistance, fadeScale, decalHandle);
return decalHandle;
public void RemoveDecal(DecalProjectorComponent decal)
public void RemoveDecal(DecalHandle handle)
int removeAtIndex = decal.CullIndex;
int removeAtIndex = handle.m_Index;
m_Decals[removeAtIndex] = m_Decals[m_DecalsCount - 1]; // move the last decal in list
m_Decals[removeAtIndex].CullIndex = removeAtIndex;
m_Decals[m_DecalsCount - 1] = null;
m_Handles[removeAtIndex] = m_Handles[m_DecalsCount - 1]; // move the last decal in list
m_Handles[removeAtIndex].m_Index = removeAtIndex;
m_Handles[m_DecalsCount - 1] = null;
// update the bounding spheres array
// update cached data
decal.CullIndex = DecalProjectorComponent.kInvalidIndex;
handle.m_Index = kInvalidIndex;
}
public void BeginCull()

private void GetDecalVolumeDataAndBound(Matrix4x4 decalToWorld, Matrix4x4 worldToView)
{
var influenceX = decalToWorld.GetColumn(0) * 0.5f;
var influenceY = decalToWorld.GetColumn(1) * 0.5f;
var influenceZ = decalToWorld.GetColumn(2) * 0.5f;

normalToWorldBatch[instanceCount].m23 = m_NormalTexIndex;
normalToWorldBatch[instanceCount].m33 = m_MaskTexIndex;
// clustered forward data
m_DecalDatas[m_DecalDatasCount].worldToDecal = decalToWorldBatch[instanceCount].inverse;
m_DecalDatas[m_DecalDatasCount].normalToWorld = normalToWorldBatch[instanceCount];

void UpdateTextureCache(CommandBuffer cmd)
{
if (m_DiffuseTexture != null)
{
m_DiffuseTexIndex = instance.TextureAtlas.FetchSlice(cmd, m_DiffuseTexture);
}
else
{
m_DiffuseTexIndex = -1;
}
if (m_NormalTexture != null)
{
m_NormalTexIndex = instance.TextureAtlas.FetchSlice(cmd, m_NormalTexture);
}
else
{
m_NormalTexIndex = -1;
}
if (m_MaskTexture != null)
{
m_MaskTexIndex = instance.TextureAtlas.FetchSlice(cmd, m_MaskTexture);
}
else
{
m_MaskTexIndex = -1;
}
m_DiffuseTexIndex = (m_DiffuseTexture != null) ? instance.TextureAtlas.FetchSlice(cmd, m_DiffuseTexture) : -1;
m_NormalTexIndex = (m_NormalTexture != null) ? instance.TextureAtlas.FetchSlice(cmd, m_NormalTexture) : -1;
m_MaskTexIndex = (m_MaskTexture != null) ? instance.TextureAtlas.FetchSlice(cmd, m_MaskTexture) : -1;
}
public void RemoveFromTextureCache()

private CullingGroup m_CullingGroup = null;
private BoundingSphere[] m_BoundingSpheres = new BoundingSphere[kDecalBlockSize];
private DecalProjectorComponent[] m_Decals = new DecalProjectorComponent[kDecalBlockSize];
private DecalHandle[] m_Handles = new DecalHandle[kDecalBlockSize];
private int[] m_ResultIndices = new int[kDecalBlockSize];
private int m_NumResults = 0;
private int m_DecalsCount = 0;

private int m_MaskTexIndex = -1;
}
public void AddDecal(DecalProjectorComponent decal)
{
if (decal.CullIndex != DecalProjectorComponent.kInvalidIndex) //do not add the same decal more than once
return;
if(!decal.IsValid())
return;
public DecalHandle AddDecal(Transform transform, float drawDistance, float fadeScale, Material material)
{
int key = decal.m_Material.GetInstanceID();
int key = material.GetInstanceID();
decalSet = new DecalSet(decal.m_Material);
decalSet = new DecalSet(material);
decalSet.AddDecal(decal);
return decalSet.AddDecal(transform, drawDistance, fadeScale, key);
public void RemoveDecal(DecalProjectorComponent decal)
public void RemoveDecal(DecalHandle handle)
if (decal.CullIndex == DecalProjectorComponent.kInvalidIndex) // check if we have this decal
return;
if (!DecalHandle.IsValid(handle))
return;
int key = decal.m_Material.GetInstanceID();
int key = handle.m_MaterialID;
decalSet.RemoveDecal(decal);
decalSet.RemoveDecal(handle);
if (decalSet.Count == 0)
{
decalSet.RemoveFromTextureCache();

}
public void UpdateCachedData(DecalProjectorComponent decal)
public void UpdateCachedData(Transform transform, float drawDistance, float fadeScale, DecalHandle handle)
if (decal.CullIndex == DecalProjectorComponent.kInvalidIndex) // check if we have this decal
if(!DecalHandle.IsValid(handle))
int key = decal.m_Material.GetInstanceID();
int key = handle.m_MaterialID;
decalSet.UpdateCachedData(decal);
decalSet.UpdateCachedData(transform, drawDistance, fadeScale, handle);
}
}

pair.Value.EndCull();
}
}
// need a better way than passing light loop here
public void RenderIntoDBuffer(CommandBuffer cmd)
{
if (m_DecalMesh == null)

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


using System;
using System;
using UnityEngine.Assertions;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine.Rendering.PostProcessing;

[CanEditMultipleObjects]
partial class HDCameraEditor : Editor
{
[MenuItem("CONTEXT/Camera/Remove HD Camera", false, 0)]
static void RemoveLight(MenuCommand menuCommand)
{
GameObject go = ((Camera)menuCommand.context).gameObject;
Assert.IsNotNull(go);
Undo.SetCurrentGroupName("Remove HD Camera");
Undo.DestroyObjectImmediate(go.GetComponent<Camera>());
Undo.DestroyObjectImmediate(go.GetComponent<HDAdditionalCameraData>());
}
SerializedHDCamera m_SerializedCamera;
HDCameraUI m_UIState = new HDCameraUI();

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraUI.cs


Inspector = new []
{
SectionPrimarySettings,
SectionPhysicalSettings,
// Not used for now
//SectionPhysicalSettings,
SectionCaptureSettings,
SectionOutputSettings,
SectionXRSettings,

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDAssetFactory.cs


newAsset.computeGgxIblSampleData = Load<ComputeShader>(HDRenderPipelinePath + "Material/GGXConvolution/ComputeGgxIblSampleData.compute");
newAsset.GGXConvolve = Load<Shader>(HDRenderPipelinePath + "Material/GGXConvolution/GGXConvolve.shader");
newAsset.opaqueAtmosphericScattering = Load<Shader>(HDRenderPipelinePath + "Sky/OpaqueAtmosphericScattering.shader");
newAsset.hdriSky = Load<Shader>(HDRenderPipelinePath + "Sky/HDRISky/HDRISky.shader");
newAsset.proceduralSky = Load<Shader>(HDRenderPipelinePath + "Sky/ProceduralSky/ProceduralSky.shader");
// Utilities / Core
newAsset.encodeBC6HCS = Load<ComputeShader>(CorePath + "CoreResources/EncodeBC6H.compute");

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


public readonly GUIContent indirectBounceShadowWarning = new GUIContent("Realtime indirect bounce shadowing is not supported for Spot and Point lights.");
// Additional light data
public readonly GUIContent directionalIntensity = new GUIContent("Intensity (Lux)", "");
public readonly GUIContent punctualIntensity = new GUIContent("Intensity (Lumen)", "");
public readonly GUIContent areaIntensity = new GUIContent("Intensity (Lumen)", "");
public readonly GUIContent directionalIntensity = new GUIContent("Intensity (Lux)", "Illuminance of the directional light at ground level in lux.");
public readonly GUIContent punctualIntensity = new GUIContent("Intensity (Lumen)", "Luminous power of the light in lumen. Spotlight are considered as point light with barndoor so match intensity of a point light.");
public readonly GUIContent areaIntensity = new GUIContent("Intensity (Lumen)", "Luminous power of the light in lumen.");
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.");

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


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

[CustomEditorForRenderPipeline(typeof(Light), typeof(HDRenderPipelineAsset))]
sealed partial class HDLightEditor : LightEditor
{
[MenuItem("CONTEXT/Light/Remove HD Light", false,0)]
static void RemoveLight(MenuCommand menuCommand)
{
GameObject go = ( (Light) menuCommand.context ).gameObject;
Assert.IsNotNull(go);
Undo.IncrementCurrentGroup();
Undo.DestroyObjectImmediate(go.GetComponent<Light>());
Undo.DestroyObjectImmediate(go.GetComponent<HDAdditionalLightData>());
Undo.DestroyObjectImmediate(go.GetComponent<AdditionalShadowData>());
}
sealed class SerializedLightData
{
public SerializedProperty directionalIntensity;

case LightShape.Rectangle:
// TODO: Currently if we use Area type as it is offline light in legacy, the light will not exist at runtime
//m_BaseData.type.enumValueIndex = (int)LightType.Area;
// In case of change, think to update InitDefaultHDAdditionalLightData()
settings.lightType.enumValueIndex = (int)LightType.Point;
m_AdditionalLightData.lightTypeExtent.enumValueIndex = (int)LightTypeExtent.Rectangle;
EditorGUILayout.PropertyField(m_AdditionalLightData.shapeWidth, s_Styles.shapeWidthRect);

if (EditorGUI.EndChangeCheck())
{
m_AdditionalLightData.fadeDistance.floatValue = Mathf.Max(m_AdditionalLightData.fadeDistance.floatValue, 0.01f);
((Light)target).SetLightDirty(); // Should be apply only to parameter that's affect GI, but make the code cleaner
}
}

var type = settings.lightType;
// Special case for multi-selection: don't resolve light shape or it'll corrupt lights
if (type.hasMultipleDifferentValues)
if (type.hasMultipleDifferentValues
|| m_AdditionalLightData.lightTypeExtent.hasMultipleDifferentValues)
{
m_LightShape = (LightShape)(-1);
return;

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.ProbeUtility.cs


using UnityEngine;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using Object = UnityEngine.Object;

{
void ChangeVisibilityOfAllTargets(bool visibility)
{
if (targets.Length == 0) return;
var p = (ReflectionProbe)targets[i];
HDReflectionProbeEditorUtility.ChangeVisibility(p, visibility);
if (targets[i] != null)
{
var p = (ReflectionProbe)targets[i];
HDReflectionProbeEditorUtility.ChangeVisibility(p, visibility);
}
}
}

17
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs


using System.Collections.Generic;
using System.Collections.Generic;
using UnityEngine.Assertions;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine.Rendering;

[CanEditMultipleObjects]
partial class HDReflectionProbeEditor : Editor
{
[MenuItem("CONTEXT/ReflectionProbe/Remove HD Reflection Probe", false, 0)]
static void RemoveLight(MenuCommand menuCommand)
{
GameObject go = ((ReflectionProbe)menuCommand.context).gameObject;
Assert.IsNotNull(go);
Undo.SetCurrentGroupName("Remove HD Reflection Probe");
Undo.DestroyObjectImmediate(go.GetComponent<ReflectionProbe>());
Undo.DestroyObjectImmediate(go.GetComponent<HDAdditionalReflectionData>());
Undo.DestroyObjectImmediate(go.GetComponent<MeshRenderer>());
Undo.DestroyObjectImmediate(go.GetComponent<MeshFilter>());
}
static Dictionary<ReflectionProbe, HDReflectionProbeEditor> s_ReflectionProbeEditors = new Dictionary<ReflectionProbe, HDReflectionProbeEditor>();
static HDReflectionProbeEditor GetEditorFor(ReflectionProbe p)

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


static void Drawer_AdditionalSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.PropertyField(p.dimmer);
EditorGUILayout.PropertyField(p.weight);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(p.multiplier);
if (EditorGUI.EndChangeCheck())
p.multiplier.floatValue = Mathf.Max(0.0f, p.multiplier.floatValue);
if (p.so.targetObjects.Length == 1)
{

var blendDistance = p.blendDistancePositive.vector3Value.x;
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = p.blendDistancePositive.hasMultipleDifferentValues;
blendDistance = EditorGUILayout.Slider(CoreEditorUtils.GetContent("Blend Distance|Area around the probe where it is blended with other probes. Only used in deferred probes."), blendDistance, 0, maxBlendDistance);
if (EditorGUI.EndChangeCheck())
{

var blendNormalDistance = p.blendNormalDistancePositive.vector3Value.x;
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = p.blendNormalDistancePositive.hasMultipleDifferentValues;
blendNormalDistance = EditorGUILayout.Slider(CoreEditorUtils.GetContent("Blend Normal Distance|Area around the probe where the normals influence the probe. Only used in deferred probes."), blendNormalDistance, 0, maxBlendDistance);
if (EditorGUI.EndChangeCheck())
{

EditorGUI.showMixedValue = false;
EditorGUILayout.PropertyField(p.influenceSphereRadius, CoreEditorUtils.GetContent("Radius"));
EditorGUILayout.PropertyField(p.boxOffset, CoreEditorUtils.GetContent("Sphere Offset|The center of the sphere in which the reflections will be applied to objects. The value is relative to the position of the Game Object."));

{
EditorGUILayout.PropertyField(p.renderDynamicObjects, CoreEditorUtils.GetContent("Dynamic Objects|If enabled dynamic objects are also rendered into the cubemap"));
p.customBakedTexture.objectReferenceValue = EditorGUILayout.ObjectField(CoreEditorUtils.GetContent("Cubemap"), p.customBakedTexture.objectReferenceValue, typeof(Cubemap), false);
EditorGUI.showMixedValue = p.customBakedTexture.hasMultipleDifferentValues;
EditorGUI.BeginChangeCheck();
var customBakedTexture = EditorGUILayout.ObjectField(CoreEditorUtils.GetContent("Cubemap"), p.customBakedTexture.objectReferenceValue, typeof(Cubemap), false);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
p.customBakedTexture.objectReferenceValue = customBakedTexture;
}
static void Drawer_ModeSettingsRealtime(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)

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


{
operations = 0;
SetModeTarget(data.mode.intValue);
SetShapeTarget(data.influenceShape.intValue);
SetModeTarget(data.mode.hasMultipleDifferentValues ? -1 : data.mode.intValue);
SetShapeTarget(data.influenceShape.hasMultipleDifferentValues ? -1 : data.influenceShape.intValue);
isSectionExpandedSeparateProjection.value = data.useSeparateProjectionVolume.boolValue;
base.Update();

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Drawers.cs


static void Drawer_SectionInfluenceSettings(PlanarReflectionProbeUI s, SerializedPlanarReflectionProbe d, Editor o)
{
EditorGUILayout.PropertyField(d.dimmer, _.GetContent("Dimmer"));
EditorGUILayout.PropertyField(d.weight, _.GetContent("Weight"));
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(d.multiplier, _.GetContent("Multiplier"));
if (EditorGUI.EndChangeCheck())
d.multiplier.floatValue = Mathf.Max(0.0f, d.multiplier.floatValue);
}
static void Drawer_FieldCaptureType(PlanarReflectionProbeUI s, SerializedPlanarReflectionProbe d, Editor o)

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/SerializedHDReflectionProbe.cs


internal SerializedProperty blendNormalDistanceNegative;
internal SerializedProperty boxSideFadePositive;
internal SerializedProperty boxSideFadeNegative;
internal SerializedProperty dimmer;
internal SerializedProperty weight;
internal SerializedProperty multiplier;
internal SerializedProperty proxyVolumeComponent;

boxReprojectionVolumeSize = addso.Find((HDAdditionalReflectionData d) => d.boxReprojectionVolumeSize);
boxReprojectionVolumeCenter = addso.Find((HDAdditionalReflectionData d) => d.boxReprojectionVolumeCenter);
sphereReprojectionVolumeRadius = addso.Find((HDAdditionalReflectionData d) => d.sphereReprojectionVolumeRadius);
dimmer = addso.Find((HDAdditionalReflectionData d) => d.dimmer);
weight = addso.Find((HDAdditionalReflectionData d) => d.weight);
multiplier = addso.Find((HDAdditionalReflectionData d) => d.multiplier);
blendDistancePositive = addso.Find((HDAdditionalReflectionData d) => d.blendDistancePositive);
blendDistanceNegative = addso.Find((HDAdditionalReflectionData d) => d.blendDistanceNegative);
blendNormalDistancePositive = addso.Find((HDAdditionalReflectionData d) => d.blendNormalDistancePositive);

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/SerializedPlanarReflectionProbe.cs


public SerializedProperty capturePositionMode;
public SerializedProperty captureMirrorPlaneLocalPosition;
public SerializedProperty captureMirrorPlaneLocalNormal;
public SerializedProperty dimmer;
public SerializedProperty weight;
public SerializedProperty multiplier;
public SerializedProperty mode;
public SerializedProperty refreshMode;
public SerializedProperty customTexture;

capturePositionMode = serializedObject.Find((PlanarReflectionProbe p) => p.capturePositionMode);
captureMirrorPlaneLocalPosition = serializedObject.Find((PlanarReflectionProbe p) => p.captureMirrorPlaneLocalPosition);
captureMirrorPlaneLocalNormal = serializedObject.Find((PlanarReflectionProbe p) => p.captureMirrorPlaneLocalNormal);
dimmer = serializedObject.Find((PlanarReflectionProbe p) => p.dimmer);
weight = serializedObject.Find((PlanarReflectionProbe p) => p.weight);
multiplier = serializedObject.Find((PlanarReflectionProbe p) => p.multiplier);
mode = serializedObject.Find((PlanarReflectionProbe p) => p.mode);
refreshMode = serializedObject.Find((PlanarReflectionProbe p) => p.refreshMode);
customTexture = serializedObject.Find((PlanarReflectionProbe p) => p.customTexture);

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Unlit/BaseUnlitUI.cs


protected const string kEnableMotionVectorForVertexAnimation = "_EnableMotionVectorForVertexAnimation";
protected const string kZTestDepthEqualForOpaque = "_ZTestDepthEqualForOpaque";
protected const string kZTestGBuffer = "_ZTestGBuffer";
protected const string kZTestModeDistortion = "_ZTestModeDistortion";
// See comment in LitProperties.hlsl

CoreUtils.SetKeyword(material, "_BLENDMODE_ALPHA", false);
CoreUtils.SetKeyword(material, "_BLENDMODE_ADD", false);
CoreUtils.SetKeyword(material, "_BLENDMODE_PRE_MULTIPLY", false);
// Alpha tested materials always have a prepass where we perform the clip.
// Then during Gbuffer pass we don't perform the clip test, so we need to use depth equal in this case.
if (alphaTestEnable)
{
material.SetInt(kZTestGBuffer, (int)UnityEngine.Rendering.CompareFunction.Equal);
}
else
{
material.SetInt(kZTestGBuffer, (int)UnityEngine.Rendering.CompareFunction.LessEqual);
}
// If the material use the kZTestDepthEqualForOpaque it mean it require depth equal test for opaque but transparent are not affected
if (material.HasProperty(kZTestDepthEqualForOpaque))

28
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/FrameSettingsUI.cs


CED.FadeGroup(
(s, d, o, i) => s.isSectionExpandedUseForwardOnly,
FadeOption.None,
CED.Action(Drawer_FieldUseDepthPrepassWithDefferedRendering),
CED.FadeGroup(
(s, d, o, i) => s.isSectionExpandedUseDepthPrepass,
FadeOption.Indent,
CED.Action(Drawer_FieldRenderAlphaTestOnlyInDeferredPrepass))),
CED.Action(Drawer_FieldUseDepthPrepassWithDefferedRendering)
),
CED.Action(Drawer_SectionOtherRenderingSettings)
)
);

public AnimBool isSectionExpandedXRSettings { get { return m_AnimBools[3]; } }
public AnimBool isSectionExpandedXRSupported { get { return m_AnimBools[4]; } }
public AnimBool isSectionExpandedUseForwardOnly { get { return m_AnimBools[5]; } }
public AnimBool isSectionExpandedUseDepthPrepass { get { return m_AnimBools[6]; } }
public LightLoopSettingsUI lightLoopSettings = new LightLoopSettingsUI();

{
isSectionExpandedXRSupported.target = PlayerSettings.virtualRealitySupported;
isSectionExpandedUseForwardOnly.target = !data.enableForwardRenderingOnly.boolValue;
isSectionExpandedUseDepthPrepass.target = data.enableDepthPrepassWithDeferredRendering.boolValue;
lightLoopSettings.Update();
}

EditorGUILayout.PropertyField(p.enablePostprocess, _.GetContent("Enable Postprocess"));
}
static void Drawer_SectionRenderingSettings(FrameSettingsUI s, SerializedFrameSettings p, Editor owner)
{
EditorGUILayout.PropertyField(p.enableForwardRenderingOnly, _.GetContent("Enable Forward Rendering Only"));
EditorGUILayout.PropertyField(p.enableDepthPrepassWithDeferredRendering, _.GetContent("Enable Depth Prepass With Deferred Rendering"));
EditorGUILayout.PropertyField(p.enableAlphaTestOnlyInDeferredPrepass, _.GetContent("Enable Alpha Test Only In Deferred Prepass"));
EditorGUILayout.PropertyField(p.enableAsyncCompute, _.GetContent("Enable Async Compute"));
EditorGUILayout.PropertyField(p.enableOpaqueObjects, _.GetContent("Enable Opaque Objects"));
EditorGUILayout.PropertyField(p.enableTransparentObjects, _.GetContent("Enable Transparent Objects"));
EditorGUILayout.PropertyField(p.enableMSAA, _.GetContent("Enable MSAA"));
}
static void Drawer_FieldForwardRenderingOnly(FrameSettingsUI s, SerializedFrameSettings p, Editor owner)
{
EditorGUILayout.PropertyField(p.enableForwardRenderingOnly, _.GetContent("Enable Forward Rendering Only"));

{
EditorGUILayout.PropertyField(p.enableDepthPrepassWithDeferredRendering, _.GetContent("Enable Depth Prepass With Deferred Rendering"));
}
static void Drawer_FieldRenderAlphaTestOnlyInDeferredPrepass(FrameSettingsUI s, SerializedFrameSettings p, Editor owner)
{
EditorGUILayout.PropertyField(p.enableAlphaTestOnlyInDeferredPrepass, _.GetContent("Enable Alpha Test Only In Deferred Prepass"));
}
static void Drawer_SectionOtherRenderingSettings(FrameSettingsUI s, SerializedFrameSettings p, Editor owner)

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/LightLoopSettingsUI.cs


static void Drawer_SectionLightLoopSettings(LightLoopSettingsUI s, SerializedLightLoopSettings p, Editor owner)
{
EditorGUILayout.PropertyField(p.enableTileAndCluster, _.GetContent("Enable Tile And Cluster"));
// Uncomment if you re-enable LIGHTLOOP_SINGLE_PASS multi_compile in lit*.shader
//EditorGUILayout.PropertyField(p.enableTileAndCluster, _.GetContent("Enable Tile And Cluster"));
//EditorGUI.indentLevel++;
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(p.enableFptlForForwardOpaque, _.GetContent("Enable FPTL For Forward Opaque"));
EditorGUILayout.PropertyField(p.enableBigTilePrepass, _.GetContent("Enable Big Tile Prepass"));
EditorGUILayout.PropertyField(p.enableComputeLightEvaluation, _.GetContent("Enable Compute Light Evaluation"));

}
EditorGUILayout.EndFadeGroup();
GUILayout.EndVertical();
EditorGUI.indentLevel--;
//EditorGUI.indentLevel--;
}
}
}

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


EditorGUILayout.PropertyField(d.supportForwardOnly, _.GetContent("Support Forward Only"));
EditorGUILayout.PropertyField(d.supportMotionVectors, _.GetContent("Support Motion Vectors"));
EditorGUILayout.PropertyField(d.supportStereo, _.GetContent("Support Stereo Rendering"));
EditorGUILayout.PropertyField(d.enableUltraQualitySSS, _.GetContent("Enable Ultra Quality SSS"));
EditorGUILayout.PropertyField(d.enableUltraQualitySSS, _.GetContent("Increase SSS Sample Count"));
--EditorGUI.indentLevel;
}
}

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


public SerializedProperty enableForwardRenderingOnly;
public SerializedProperty enableDepthPrepassWithDeferredRendering;
public SerializedProperty enableAlphaTestOnlyInDeferredPrepass;
public SerializedProperty enableTransparentPrepass;
public SerializedProperty enableMotionVectors;

specularGlobalDimmer = root.Find((FrameSettings d) => d.specularGlobalDimmer);
enableForwardRenderingOnly = root.Find((FrameSettings d) => d.enableForwardRenderingOnly);
enableDepthPrepassWithDeferredRendering = root.Find((FrameSettings d) => d.enableDepthPrepassWithDeferredRendering);
enableAlphaTestOnlyInDeferredPrepass = root.Find((FrameSettings d) => d.enableAlphaTestOnlyInDeferredPrepass);
enableTransparentPrepass = root.Find((FrameSettings d) => d.enableTransparentPrepass);
enableMotionVectors = root.Find((FrameSettings d) => d.enableMotionVectors);
enableObjectMotionVectors = root.Find((FrameSettings d) => d.enableObjectMotionVectors);

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Sky/HDRISky/HDRISkyEditor.cs


public class HDRISkyEditor
: SkySettingsEditor
{
SerializedDataParameter m_SkyHDRI;
SerializedDataParameter m_hdriSky;
public override void OnEnable()
{

m_SkyHDRI = Unpack(o.Find(x => x.skyHDRI));
m_hdriSky = Unpack(o.Find(x => x.hdriSky));
PropertyField(m_SkyHDRI);
PropertyField(m_hdriSky);
EditorGUILayout.Space();

61
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs


}
RenderStateBlock m_DepthStateOpaque;
RenderStateBlock m_DepthStateOpaqueWithPrepass;
// Detect when windows size is changing
int m_CurrentWidth;

m_DebugDisplaySettings.RegisterDebug();
#if UNITY_EDITOR
// We don't need the debug of Default camera at runtime (each camera have its own debug settings)
FrameSettings.RegisterDebug("Default Camera", m_Asset.GetFrameSettings());
// We don't need the debug of Scene View at runtime (each camera have its own debug settings)
FrameSettings.RegisterDebug("Scene View", m_Asset.GetFrameSettings());
#endif
InitializeRenderTextures();

supportedLightmapsModes = LightmapsMode.NonDirectional | LightmapsMode.CombinedDirectional,
rendererSupportsLightProbeProxyVolumes = true,
rendererSupportsMotionVectors = true,
rendererSupportsReceiveShadows = true,
rendererSupportsReceiveShadows = false,
rendererSupportsReflectionProbes = true
};

depthState = new DepthState(true, CompareFunction.LessEqual),
mask = RenderStateMask.Depth
};
// When doing a prepass, we don't need to write the depth anymore.
// Moreover, we need to use DepthEqual because for alpha tested materials we don't do the clip in the shader anymore (otherwise HiZ does not work on PS4)
m_DepthStateOpaqueWithPrepass = new RenderStateBlock
{
depthState = new DepthState(false, CompareFunction.Equal),
mask = RenderStateMask.Depth
};
}
public void OnSceneLoad()

m_SSSBufferManager.Cleanup();
m_SkyManager.Cleanup();
m_VolumetricLightingModule.Cleanup();
m_IBLFilterGGX.Cleanup();
DestroyRenderTextures();

SceneViewDrawMode.ResetDrawMode();
FrameSettings.UnRegisterDebug("Scene View");
#endif
}

}
VolumeManager.instance.Update(camera.transform, layerMask);
}
}
// Disable postprocess if we enable debug mode
if (m_CurrentDebugDisplaySettings.fullScreenDebugMode == FullScreenDebugMode.None && m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled())
{
m_FrameSettings.enablePostprocess = false;
}
var postProcessLayer = camera.GetComponent<PostProcessLayer>();

// RenderDepthPrepass render both opaque and opaque alpha tested based on engine configuration.
// Forward only renderer: We always render everything
// Deferred renderer: We render a depth prepass only if engine request it. We can decide if we render everything or only opaque alpha tested object.
// Deferred renderer: We always render depth prepass for alpha tested (optimization), other object are render based on engine configuration.
// Forward opaque with deferred renderer (DepthForwardOnly pass): We always render everything
void RenderDepthPrepass(CullResults cull, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd, bool forcePrepass)
{

// Guidelines: In deferred by default there is no opaque in forward. However it is possible to force an opaque material to render in forward
// by using the pass "ForwardOnly". In this case the .shader should not have "Forward" but only a "ForwardOnly" pass.
// It must also have a "DepthForwardOnly" and no "DepthOnly" pass as forward material (either deferred or forward only rendering) have always a depth pass.
// In case of forward only rendering we have a depth prepass. In case of deferred renderer, it is optional
bool addFullDepthPrepass = m_FrameSettings.enableForwardRenderingOnly || m_FrameSettings.enableDepthPrepassWithDeferredRendering;
bool addAlphaTestedOnly = !m_FrameSettings.enableForwardRenderingOnly && m_FrameSettings.enableDepthPrepassWithDeferredRendering && m_FrameSettings.enableAlphaTestOnlyInDeferredPrepass;
// If a forward material have no depth prepass, then lighting can be incorrect (deferred sahdowing, SSAO), this may be acceptable depends on usage
bool addFullDepthPrepass = forcePrepass || m_FrameSettings.enableForwardRenderingOnly || m_FrameSettings.enableDepthPrepassWithDeferredRendering;
using (new ProfilingSample(cmd, addAlphaTestedOnly ? "Depth Prepass alpha test" : "Depth Prepass", CustomSamplerId.DepthPrepass.GetSampler()))
using (new ProfilingSample(cmd, !addFullDepthPrepass ? "Depth Prepass alpha test" : "Depth Prepass", CustomSamplerId.DepthPrepass.GetSampler()))
if (forcePrepass || (addFullDepthPrepass && !addAlphaTestedOnly)) // Always true in case of forward rendering, use in case of deferred rendering if requesting a full depth prepass
if (addFullDepthPrepass) // Always true in case of forward rendering, use in case of deferred rendering if requesting a full depth prepass
{
// We render first the opaque object as opaque alpha tested are more costly to render and could be reject by early-z (but not Hi-z as it is disable with clip instruction)
// This is handled automatically with the RenderQueue value (OpaqueAlphaTested have a different value and thus are sorted after Opaque)

// We always do a DepthForwardOnly pass with all the opaque (including alpha test)
RenderOpaqueRenderList(cull, camera, renderContext, cmd, m_DepthForwardOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
// Render Alpha test only if requested
if (addAlphaTestedOnly)
{
var renderQueueRange = new RenderQueueRange { min = (int)RenderQueue.AlphaTest, max = (int)RenderQueue.GeometryLast - 1 };
RenderOpaqueRenderList(cull, camera, renderContext, cmd, m_DepthOnlyPassNames, 0, renderQueueRange);
}
// Alpha tested materials always have a prepass.
var renderQueueRange = new RenderQueueRange { min = (int)RenderQueue.AlphaTest, max = (int)RenderQueue.GeometryLast - 1 };
RenderOpaqueRenderList(cull, camera, renderContext, cmd, m_DepthOnlyPassNames, 0, renderQueueRange);
}
}

{
// setup GBuffer for rendering
HDUtils.SetRenderTarget(cmd, hdCamera, m_GbufferManager.GetBuffersRTI(enableShadowMask), m_CameraDepthStencilBuffer);
// Render opaque objects into GBuffer
if (m_FrameSettings.enableDepthPrepassWithDeferredRendering)
{
// When using depth prepass for opaque alpha test only we need to use regular depth test for normal opaque objects.
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, m_currentRendererConfigurationBakedLighting, HDRenderQueue.k_RenderQueue_OpaqueNoAlphaTest, m_FrameSettings.enableAlphaTestOnlyInDeferredPrepass ? m_DepthStateOpaque : m_DepthStateOpaqueWithPrepass);
// but for opaque alpha tested object we use a depth equal and no depth write. And we rely on the shader pass GbufferWithDepthPrepass
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferWithPrepassName, m_currentRendererConfigurationBakedLighting, HDRenderQueue.k_RenderQueue_OpaqueAlphaTest, m_DepthStateOpaqueWithPrepass);
}
else
{
// No depth prepass, use regular depth test - Note that we will render opaque then opaque alpha tested (based on the RenderQueue system)
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, m_currentRendererConfigurationBakedLighting, HDRenderQueue.k_RenderQueue_AllOpaque, m_DepthStateOpaque);
}
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, m_currentRendererConfigurationBakedLighting, HDRenderQueue.k_RenderQueue_AllOpaque);
m_GbufferManager.BindBufferAsTextures(cmd);
}

Vector2 pyramidScale = m_BufferPyramid.GetPyramidToScreenScale(hdCamera);
PushFullScreenDebugTextureMip(cmd, m_BufferPyramid.depthPyramid, m_BufferPyramid.GetPyramidLodCount(hdCamera), new Vector4(pyramidScale.x, pyramidScale.y, 0.0f, 0.0f), hdCamera, debugMode);
cmd.SetGlobalTexture(HDShaderIDs._PyramidDepthTexture, m_BufferPyramid.depthPyramid);
}
void RenderPostProcess(HDCamera hdcamera, CommandBuffer cmd, PostProcessLayer layer)

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipelineAsset.asset


specularGlobalDimmer: 1
enableForwardRenderingOnly: 0
enableDepthPrepassWithDeferredRendering: 0
enableAlphaTestOnlyInDeferredPrepass: 0
enableTransparentPrepass: 1
enableMotionVectors: 1
enableObjectMotionVectors: 1

supportSSAO: 1
supportSubsurfaceScattering: 1
supportForwardOnly: 0
enableUltraQualitySSS: 0
supportDBuffer: 1
supportMSAA: 0
msaaSampleCount: 1

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


{
// At first init we need to initialize correctly the default value
lightData.ConvertPhysicalLightIntensityToLightIntensity();
// Special treatment for Unity builtin area light. Change it to our rectangle light
var light = lightData.gameObject.GetComponent<Light>();
// Sanity check: lightData.lightTypeExtent is init to LightTypeExtent.Punctual (in case for unknow reasons we recreate additional data on an existing line)
if (light.type == LightType.Area && lightData.lightTypeExtent == LightTypeExtent.Punctual)
{
lightData.lightTypeExtent = LightTypeExtent.Rectangle;
light.type = LightType.Point; // Same as in HDLightEditor
}
}
}

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


public struct EnvLightData
{
// Packing order depends on chronological access to avoid cache misses
// Caution: The struct need to be align on byte16 (not strictly needed for structured buffer but if we do array later better).
public float capturePositionWSX;
public float capturePositionWSY;
public float capturePositionWSZ;
public Vector3 capturePositionWS;
public float proxyExtentsX;
public float proxyExtentsY;
public float proxyExtentsZ;
public Vector3 proxyExtents;
public float proxyPositionWSX;
public float proxyPositionWSY;
public float proxyPositionWSZ;
public float proxyForwardX;
public float proxyForwardY;
public float proxyForwardZ;
public float proxyUpX;
public float proxyUpY;
public float proxyUpZ;
public float proxyRightX;
public float proxyRightY;
public float proxyRightZ;
public Vector3 proxyPositionWS;
public Vector3 proxyForward;
public Vector3 proxyUp;
public Vector3 proxyRight;
public float influencePositionWSX;
public float influencePositionWSY;
public float influencePositionWSZ;
public float influenceForwardX;
public float influenceForwardY;
public float influenceForwardZ;
public float influenceUpX;
public float influenceUpY;
public float influenceUpZ;
public float influenceRightX;
public float influenceRightY;
public float influenceRightZ;
public Vector3 influencePositionWS;
public Vector3 influenceForward;
public Vector3 influenceUp;
public Vector3 influenceRight;
public float influenceExtentsX;
public float influenceExtentsY;
public float influenceExtentsZ;
public Vector3 influenceExtents;
public float blendDistancePositiveX;
public float blendDistancePositiveY;
public float blendDistancePositiveZ;
public float blendDistanceNegativeX;
public float blendDistanceNegativeY;
public float blendDistanceNegativeZ;
public float blendNormalDistancePositiveX;
public float blendNormalDistancePositiveY;
public float blendNormalDistancePositiveZ;
public float blendNormalDistanceNegativeX;
public float blendNormalDistanceNegativeY;
public float blendNormalDistanceNegativeZ;
public Vector3 blendDistancePositive;
public Vector3 blendDistanceNegative;
public Vector3 blendNormalDistancePositive;
public Vector3 blendNormalDistanceNegative;
public float boxSideFadePositiveX;
public float boxSideFadePositiveY;
public float boxSideFadePositiveZ;
public float boxSideFadeNegativeX;
public float boxSideFadeNegativeY;
public float boxSideFadeNegativeZ;
public float dimmer;
public float unused01;
public Vector3 boxSideFadePositive;
public Vector3 boxSideFadeNegative;
public float weight;
public float multiplier;
public float sampleDirectionDiscardWSX;
public float sampleDirectionDiscardWSY;
public float sampleDirectionDiscardWSZ;
public Vector3 sampleDirectionDiscardWS;
public Vector3 capturePositionWS
{
get { return new Vector3(capturePositionWSX, capturePositionWSY, capturePositionWSZ); }
set
{
capturePositionWSX = value.x;
capturePositionWSY = value.y;
capturePositionWSZ = value.z;
}
}
public Vector3 proxyExtents
{
get { return new Vector3(proxyExtentsX, proxyExtentsY, proxyExtentsZ); }
set
{
proxyExtentsX = value.x;
proxyExtentsY = value.y;
proxyExtentsZ = value.z;
}
}
public Vector3 proxyPositionWS
{
get { return new Vector3(proxyPositionWSX, proxyPositionWSY, proxyPositionWSZ); }
set
{
proxyPositionWSX = value.x;
proxyPositionWSY = value.y;
proxyPositionWSZ = value.z;
}
}
public Vector3 proxyForward
{
get { return new Vector3(proxyForwardX, proxyForwardY, proxyForwardZ); }
set
{
proxyForwardX = value.x;
proxyForwardY = value.y;
proxyForwardZ = value.z;
}
}
public Vector3 proxyUp
{
get { return new Vector3(proxyUpX, proxyUpY, proxyUpZ); }
set
{
proxyUpX = value.x;
proxyUpY = value.y;
proxyUpZ = value.z;
}
}
public Vector3 proxyRight
{
get { return new Vector3(proxyRightX, proxyRightY, proxyRightZ); }
set
{
proxyRightX = value.x;
proxyRightY = value.y;
proxyRightZ = value.z;
}
}
public Vector3 influenceExtents
{
get { return new Vector3(influenceExtentsX, influenceExtentsY, influenceExtentsZ); }
set
{
influenceExtentsX = value.x;
influenceExtentsY = value.y;
influenceExtentsZ = value.z;
}
}
public Vector3 influencePositionWS
{
get { return new Vector3(influencePositionWSX, influencePositionWSY, influencePositionWSZ); }
set
{
influencePositionWSX = value.x;
influencePositionWSY = value.y;
influencePositionWSZ = value.z;
}
}
public Vector3 influenceForward
{
get { return new Vector3(influenceForwardX, influenceForwardY, influenceForwardZ); }
set
{
influenceForwardX = value.x;
influenceForwardY = value.y;
influenceForwardZ = value.z;
}
}
public Vector3 influenceUp
{
get { return new Vector3(influenceUpX, influenceUpY, influenceUpZ); }
set
{
influenceUpX = value.x;
influenceUpY = value.y;
influenceUpZ = value.z;
}
}
public Vector3 influenceRight
{
get { return new Vector3(influenceRightX, influenceRightY, influenceRightZ); }
set
{
influenceRightX = value.x;
influenceRightY = value.y;
influenceRightZ = value.z;
}
}
public Vector3 blendDistancePositive
{
get { return new Vector3(blendDistancePositiveX, blendDistancePositiveY, blendDistancePositiveZ); }
set
{
blendDistancePositiveX = value.x;
blendDistancePositiveY = value.y;
blendDistancePositiveZ = value.z;
}
}
public Vector3 blendDistanceNegative
{
get { return new Vector3(blendDistanceNegativeX, blendDistanceNegativeY, blendDistanceNegativeZ); }
set
{
blendDistanceNegativeX = value.x;
blendDistanceNegativeY = value.y;
blendDistanceNegativeZ = value.z;
}
}
public Vector3 blendNormalDistancePositive
{
get { return new Vector3(blendNormalDistancePositiveX, blendNormalDistancePositiveY, blendNormalDistancePositiveZ); }
set
{
blendNormalDistancePositiveX = value.x;
blendNormalDistancePositiveY = value.y;
blendNormalDistancePositiveZ = value.z;
}
}
public Vector3 blendNormalDistanceNegative
{
get { return new Vector3(blendNormalDistanceNegativeX, blendNormalDistanceNegativeY, blendNormalDistanceNegativeZ); }
set
{
blendNormalDistanceNegativeX = value.x;
blendNormalDistanceNegativeY = value.y;
blendNormalDistanceNegativeZ = value.z;
}
}
public Vector3 boxSideFadePositive
{
get { return new Vector3(boxSideFadePositiveX, boxSideFadePositiveY, boxSideFadePositiveZ); }
set
{
boxSideFadePositiveX = value.x;
boxSideFadePositiveY = value.y;
boxSideFadePositiveZ = value.z;
}
}
public Vector3 boxSideFadeNegative
{
get { return new Vector3(boxSideFadeNegativeX, boxSideFadeNegativeY, boxSideFadeNegativeZ); }
set
{
boxSideFadeNegativeX = value.x;
boxSideFadeNegativeY = value.y;
boxSideFadeNegativeZ = value.z;
}
}
public Vector3 sampleDirectionDiscardWS
{
get { return new Vector3(sampleDirectionDiscardWSX, sampleDirectionDiscardWSY, sampleDirectionDiscardWSZ); }
set
{
sampleDirectionDiscardWSX = value.x;
sampleDirectionDiscardWSY = value.y;
sampleDirectionDiscardWSZ = value.z;
}
}
};
[GenerateHLSL]

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


// PackingRules = Exact
struct EnvLightData
{
float capturePositionWSX;
float capturePositionWSY;
float capturePositionWSZ;
float3 capturePositionWS;
float proxyExtentsX;
float proxyExtentsY;
float proxyExtentsZ;
float3 proxyExtents;
float proxyPositionWSX;
float proxyPositionWSY;
float proxyPositionWSZ;
float proxyForwardX;
float proxyForwardY;
float proxyForwardZ;
float proxyUpX;
float proxyUpY;
float proxyUpZ;
float proxyRightX;
float proxyRightY;
float proxyRightZ;
float influencePositionWSX;
float influencePositionWSY;
float influencePositionWSZ;
float influenceForwardX;
float influenceForwardY;
float influenceForwardZ;
float influenceUpX;
float influenceUpY;
float influenceUpZ;
float influenceRightX;
float influenceRightY;
float influenceRightZ;
float influenceExtentsX;
float influenceExtentsY;
float influenceExtentsZ;
float3 proxyPositionWS;
float3 proxyForward;
float3 proxyUp;
float3 proxyRight;
float3 influencePositionWS;
float3 influenceForward;
float3 influenceUp;
float3 influenceRight;
float3 influenceExtents;
float blendDistancePositiveX;
float blendDistancePositiveY;
float blendDistancePositiveZ;
float blendDistanceNegativeX;
float blendDistanceNegativeY;
float blendDistanceNegativeZ;
float blendNormalDistancePositiveX;
float blendNormalDistancePositiveY;
float blendNormalDistancePositiveZ;
float blendNormalDistanceNegativeX;
float blendNormalDistanceNegativeY;
float blendNormalDistanceNegativeZ;
float boxSideFadePositiveX;
float boxSideFadePositiveY;
float boxSideFadePositiveZ;
float boxSideFadeNegativeX;
float boxSideFadeNegativeY;
float boxSideFadeNegativeZ;
float dimmer;
float unused01;
float sampleDirectionDiscardWSX;
float sampleDirectionDiscardWSY;
float sampleDirectionDiscardWSZ;
float3 blendDistancePositive;
float3 blendDistanceNegative;
float3 blendNormalDistancePositive;
float3 blendNormalDistanceNegative;
float3 boxSideFadePositive;
float3 boxSideFadeNegative;
float weight;
float multiplier;
float3 sampleDirectionDiscardWS;
int envIndex;
};

//
// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.EnvLightData
//
float GetCapturePositionWSX(EnvLightData value)
{
return value.capturePositionWSX;
}
float GetCapturePositionWSY(EnvLightData value)
float3 GetCapturePositionWS(EnvLightData value)
return value.capturePositionWSY;
}
float GetCapturePositionWSZ(EnvLightData value)
{
return value.capturePositionWSZ;
return value.capturePositionWS;
float GetProxyExtentsX(EnvLightData value)
{
return value.proxyExtentsX;
}
float GetProxyExtentsY(EnvLightData value)
{
return value.proxyExtentsY;
}
float GetProxyExtentsZ(EnvLightData value)
float3 GetProxyExtents(EnvLightData value)
return value.proxyExtentsZ;
return value.proxyExtents;
float GetProxyPositionWSX(EnvLightData value)
float3 GetProxyPositionWS(EnvLightData value)
return value.proxyPositionWSX;
return value.proxyPositionWS;
float GetProxyPositionWSY(EnvLightData value)
float3 GetProxyForward(EnvLightData value)
return value.proxyPositionWSY;
return value.proxyForward;
float GetProxyPositionWSZ(EnvLightData value)
float3 GetProxyUp(EnvLightData value)
return value.proxyPositionWSZ;
return value.proxyUp;
float GetProxyForwardX(EnvLightData value)
float3 GetProxyRight(EnvLightData value)
return value.proxyForwardX;
return value.proxyRight;
float GetProxyForwardY(EnvLightData value)
float3 GetInfluencePositionWS(EnvLightData value)
return value.proxyForwardY;
return value.influencePositionWS;
float GetProxyForwardZ(EnvLightData value)
float3 GetInfluenceForward(EnvLightData value)
return value.proxyForwardZ;
return value.influenceForward;
float GetProxyUpX(EnvLightData value)
float3 GetInfluenceUp(EnvLightData value)
return value.proxyUpX;
return value.influenceUp;
float GetProxyUpY(EnvLightData value)
float3 GetInfluenceRight(EnvLightData value)
return value.proxyUpY;
return value.influenceRight;
float GetProxyUpZ(EnvLightData value)
{
return value.proxyUpZ;
}
float GetProxyRightX(EnvLightData value)
{
return value.proxyRightX;
}
float GetProxyRightY(EnvLightData value)
float3 GetInfluenceExtents(EnvLightData value)
return value.proxyRightY;
}
float GetProxyRightZ(EnvLightData value)
{
return value.proxyRightZ;
}
float GetInfluencePositionWSX(EnvLightData value)
{
return value.influencePositionWSX;
}
float GetInfluencePositionWSY(EnvLightData value)
{
return value.influencePositionWSY;
}
float GetInfluencePositionWSZ(EnvLightData value)
{
return value.influencePositionWSZ;
}
float GetInfluenceForwardX(EnvLightData value)
{
return value.influenceForwardX;
}
float GetInfluenceForwardY(EnvLightData value)
{
return value.influenceForwardY;
}
float GetInfluenceForwardZ(EnvLightData value)
{
return value.influenceForwardZ;
}
float GetInfluenceUpX(EnvLightData value)
{
return value.influenceUpX;
}
float GetInfluenceUpY(EnvLightData value)
{
return value.influenceUpY;
}
float GetInfluenceUpZ(EnvLightData value)
{
return value.influenceUpZ;
}
float GetInfluenceRightX(EnvLightData value)
{
return value.influenceRightX;
}
float GetInfluenceRightY(EnvLightData value)
{
return value.influenceRightY;
}
float GetInfluenceRightZ(EnvLightData value)
{
return value.influenceRightZ;
}
float GetInfluenceExtentsX(EnvLightData value)
{
return value.influenceExtentsX;
}
float GetInfluenceExtentsY(EnvLightData value)
{
return value.influenceExtentsY;
}
float GetInfluenceExtentsZ(EnvLightData value)
{
return value.influenceExtentsZ;
return value.influenceExtents;
float GetBlendDistancePositiveX(EnvLightData value)
{
return value.blendDistancePositiveX;
}
float GetBlendDistancePositiveY(EnvLightData value)
{
return value.blendDistancePositiveY;
}
float GetBlendDistancePositiveZ(EnvLightData value)
{
return value.blendDistancePositiveZ;
}
float GetBlendDistanceNegativeX(EnvLightData value)
{
return value.blendDistanceNegativeX;
}
float GetBlendDistanceNegativeY(EnvLightData value)
{
return value.blendDistanceNegativeY;
}
float GetBlendDistanceNegativeZ(EnvLightData value)
float3 GetBlendDistancePositive(EnvLightData value)
return value.blendDistanceNegativeZ;
return value.blendDistancePositive;
float GetBlendNormalDistancePositiveX(EnvLightData value)
float3 GetBlendDistanceNegative(EnvLightData value)
return value.blendNormalDistancePositiveX;
return value.blendDistanceNegative;
float GetBlendNormalDistancePositiveY(EnvLightData value)
float3 GetBlendNormalDistancePositive(EnvLightData value)
return value.blendNormalDistancePositiveY;
return value.blendNormalDistancePositive;
float GetBlendNormalDistancePositiveZ(EnvLightData value)
float3 GetBlendNormalDistanceNegative(EnvLightData value)
return value.blendNormalDistancePositiveZ;
return value.blendNormalDistanceNegative;
float GetBlendNormalDistanceNegativeX(EnvLightData value)
float3 GetBoxSideFadePositive(EnvLightData value)
return value.blendNormalDistanceNegativeX;
return value.boxSideFadePositive;
float GetBlendNormalDistanceNegativeY(EnvLightData value)
float3 GetBoxSideFadeNegative(EnvLightData value)
return value.blendNormalDistanceNegativeY;
return value.boxSideFadeNegative;
float GetBlendNormalDistanceNegativeZ(EnvLightData value)
float GetWeight(EnvLightData value)
return value.blendNormalDistanceNegativeZ;
return value.weight;
float GetBoxSideFadePositiveX(EnvLightData value)
float GetMultiplier(EnvLightData value)
return value.boxSideFadePositiveX;
return value.multiplier;
float GetBoxSideFadePositiveY(EnvLightData value)
float3 GetSampleDirectionDiscardWS(EnvLightData value)
return value.boxSideFadePositiveY;
}
float GetBoxSideFadePositiveZ(EnvLightData value)
{
return value.boxSideFadePositiveZ;
}
float GetBoxSideFadeNegativeX(EnvLightData value)
{
return value.boxSideFadeNegativeX;
}
float GetBoxSideFadeNegativeY(EnvLightData value)
{
return value.boxSideFadeNegativeY;
}
float GetBoxSideFadeNegativeZ(EnvLightData value)
{
return value.boxSideFadeNegativeZ;
}
float GetDimmer(EnvLightData value)
{
return value.dimmer;
}
float GetUnused01(EnvLightData value)
{
return value.unused01;
}
float GetSampleDirectionDiscardWSX(EnvLightData value)
{
return value.sampleDirectionDiscardWSX;
}
float GetSampleDirectionDiscardWSY(EnvLightData value)
{
return value.sampleDirectionDiscardWSY;
}
float GetSampleDirectionDiscardWSZ(EnvLightData value)
{
return value.sampleDirectionDiscardWSZ;
return value.sampleDirectionDiscardWS;
}
int GetEnvIndex(EnvLightData value)
{

#endif
#include "LightDefinition.cs.custom.hlsl"

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


atlasInit.shadowClearShader = resources.shadowClearShader;
atlasInit.shadowBlurMoments = resources.shadowBlurMoments;
/*
// Code kept here for reference if we want to add VSM/MSM later on
varianceInit.baseInit.shadowmapFormat = ShadowVariance.GetFormat( false, false, true );
varianceInit.baseInit.shadowmapFormat = ShadowVariance.GetFormat(false, false, true);
varianceInit2.baseInit.shadowmapFormat = ShadowVariance.GetFormat( true, true, false );
varianceInit2.baseInit.shadowmapFormat = ShadowVariance.GetFormat(true, true, false);
varianceInit3.baseInit.shadowmapFormat = ShadowVariance.GetFormat( true, false, true );
varianceInit3.baseInit.shadowmapFormat = ShadowVariance.GetFormat(true, false, true);
m_Shadowmaps = new ShadowmapBase[] { new ShadowAtlas(ref atlasInit), new ShadowVariance(ref varianceInit), new ShadowVariance(ref varianceInit2), new ShadowVariance(ref varianceInit3) };
*/
m_Shadowmaps = new ShadowmapBase[] { new ShadowVariance(ref varianceInit), new ShadowVariance(ref varianceInit2), new ShadowVariance(ref varianceInit3), new ShadowAtlas(ref atlasInit) };
m_Shadowmaps = new ShadowmapBase[] { new ShadowAtlas(ref atlasInit) };
ShadowContext.SyncDel syncer = (ShadowContext sc) =>
{

cb.SetGlobalBuffer(HDShaderIDs._ShadowDatasExp, s_ShadowDataBuffer);
cb.SetGlobalBuffer(HDShaderIDs._ShadowPayloads, s_ShadowPayloadBuffer);
// bind textures
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_VSM_0, tex[0]);
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_VSM_1, tex[1]);
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_VSM_2, tex[2]);
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_PCF, tex[3]);
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_PCF, tex[0]);
// Code kept here for reference if we want to add VSM/MSM later on
//cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_VSM_0, tex[1]);
//cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_VSM_1, tex[2]);
//cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_VSM_2, tex[3])
// TODO: Currently samplers are hard coded in ShadowContext.hlsl, so we can't really set them here
};

{
if (m_Shadowmaps != null)
{
(m_Shadowmaps[0] as ShadowAtlas).Dispose();
(m_Shadowmaps[1] as ShadowAtlas).Dispose();
(m_Shadowmaps[2] as ShadowAtlas).Dispose();
(m_Shadowmaps[3] as ShadowAtlas).Dispose();
foreach(var shadowMap in m_Shadowmaps)
{
(shadowMap as ShadowAtlas).Dispose();
}
m_Shadowmaps = null;
}
m_ShadowMgr = null;

public static readonly Vector3 k_BoxCullingExtentThreshold = Vector3.one * 0.01f;
// Static keyword is required here else we get a "DestroyBuffer can only be called from the main thread"
static ComputeBuffer s_DirectionalLightDatas = null;
static ComputeBuffer s_LightDatas = null;
static ComputeBuffer s_EnvLightDatas = null;
static ComputeBuffer s_shadowDatas = null;
static ComputeBuffer s_DecalDatas = null;
ComputeBuffer m_DirectionalLightDatas = null;
ComputeBuffer m_LightDatas = null;
ComputeBuffer m_EnvLightDatas = null;
ComputeBuffer m_shadowDatas = null;
ComputeBuffer m_DecalDatas = null;
static Texture2DArray s_DefaultTexture2DArray;
static Cubemap s_DefaultTextureCube;
Texture2DArray m_DefaultTexture2DArray;
Cubemap m_DefaultTextureCube;
PlanarReflectionProbeCache m_ReflectionPlanarProbeCache;
ReflectionProbeCache m_ReflectionProbeCache;

for (int i = 0, c = Mathf.Max(1, hdAsset.renderPipelineSettings.lightLoopSettings.maxPlanarReflectionProbes); i < c; ++i)
m_Env2DCaptureVP.Add(Matrix4x4.identity);
s_DirectionalLightDatas = new ComputeBuffer(k_MaxDirectionalLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DirectionalLightData)));
s_LightDatas = new ComputeBuffer(k_MaxPunctualLightsOnScreen + k_MaxAreaLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(LightData)));
s_EnvLightDatas = new ComputeBuffer(k_MaxEnvLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(EnvLightData)));
s_shadowDatas = new ComputeBuffer(k_MaxCascadeCount + k_MaxShadowOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(ShadowData)));
s_DecalDatas = new ComputeBuffer(k_MaxDecalsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DecalData)));
m_DirectionalLightDatas = new ComputeBuffer(k_MaxDirectionalLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DirectionalLightData)));
m_LightDatas = new ComputeBuffer(k_MaxPunctualLightsOnScreen + k_MaxAreaLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(LightData)));
m_EnvLightDatas = new ComputeBuffer(k_MaxEnvLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(EnvLightData)));
m_shadowDatas = new ComputeBuffer(k_MaxCascadeCount + k_MaxShadowOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(ShadowData)));
m_DecalDatas = new ComputeBuffer(k_MaxDecalsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DecalData)));
m_CookieTexArray = new TextureCache2D();
m_CookieTexArray = new TextureCache2D("Cookie");
m_CubeCookieTexArray = new TextureCacheCubemap();
m_CubeCookieTexArray = new TextureCacheCubemap("Cookie");
m_CubeCookieTexArray.AllocTextureArray(gLightLoopSettings.cubeCookieTexArraySize, gLightLoopSettings.pointCookieSize, TextureFormat.RGBA32, true, m_CubeToPanoMaterial);
TextureFormat probeCacheFormat = gLightLoopSettings.reflectionCacheCompressed ? TextureFormat.BC6H : TextureFormat.RGBAHalf;

int index = GetDeferredLightingMaterialIndex(outputSplitLighting, lightLoopTilePass, shadowMask, debugDisplay);
m_deferredLightingMaterial[index] = CoreUtils.CreateEngineMaterial(m_Resources.deferredShader);
m_deferredLightingMaterial[index].name = string.Format("{0}_{1}", m_Resources.deferredShader.name, index);
CoreUtils.SetKeyword(m_deferredLightingMaterial[index], "OUTPUT_SPLIT_LIGHTING", outputSplitLighting == 1);
CoreUtils.SelectKeyword(m_deferredLightingMaterial[index], "LIGHTLOOP_TILE_PASS", "LIGHTLOOP_SINGLE_PASS", lightLoopTilePass == 1);
CoreUtils.SetKeyword(m_deferredLightingMaterial[index], "SHADOWS_SHADOWMASK", shadowMask == 1);

}
}
s_DefaultTexture2DArray = new Texture2DArray(1, 1, 1, TextureFormat.ARGB32, false);
s_DefaultTexture2DArray.SetPixels32(new Color32[1] { new Color32(128, 128, 128, 128) }, 0);
s_DefaultTexture2DArray.Apply();
m_DefaultTexture2DArray = new Texture2DArray(1, 1, 1, TextureFormat.ARGB32, false);
m_DefaultTexture2DArray.hideFlags = HideFlags.HideAndDontSave;
m_DefaultTexture2DArray.name = CoreUtils.GetTextureAutoName(1, 1, TextureFormat.ARGB32, depth: 1, dim: TextureDimension.Tex2DArray, name: "LightLoopDefault");
m_DefaultTexture2DArray.SetPixels32(new Color32[1] { new Color32(128, 128, 128, 128) }, 0);
m_DefaultTexture2DArray.Apply();
s_DefaultTextureCube = new Cubemap(16, TextureFormat.ARGB32, false);
s_DefaultTextureCube.Apply();
m_DefaultTextureCube = new Cubemap(16, TextureFormat.ARGB32, false);
m_DefaultTextureCube.Apply();
InitShadowSystem(hdAsset, shadowSettings);
}

DeinitShadowSystem();
CoreUtils.SafeRelease(s_DirectionalLightDatas);
CoreUtils.SafeRelease(s_LightDatas);
CoreUtils.SafeRelease(s_EnvLightDatas);
CoreUtils.SafeRelease(s_shadowDatas);
CoreUtils.SafeRelease(s_DecalDatas);
CoreUtils.Destroy(m_DefaultTexture2DArray);
CoreUtils.Destroy(m_DefaultTextureCube);
CoreUtils.SafeRelease(m_DirectionalLightDatas);
CoreUtils.SafeRelease(m_LightDatas);
CoreUtils.SafeRelease(m_EnvLightDatas);
CoreUtils.SafeRelease(m_shadowDatas);
CoreUtils.SafeRelease(m_DecalDatas);
if (m_ReflectionProbeCache != null)
{

m_CurrentSunLightShadowIndex = shadowIdx;
}
// TODO: Currently m_maxShadowDistance is based on shadow settings, but this value is define for a whole level. We should be able to change this value during gameplay
float scale;
float bias;
GetScaleAndBiasForLinearDistanceFade(m_maxShadowDistance, out scale, out bias);

if (additionalshadowData)
{
float shadowDistanceFade = ComputeLinearDistanceFade(distanceToCamera, additionalshadowData.shadowFadeDistance);
float shadowDistanceFade = ComputeLinearDistanceFade(distanceToCamera, Mathf.Min(shadowSettings.maxShadowDistance, additionalshadowData.shadowFadeDistance));
lightData.shadowDimmer = additionalshadowData.shadowDimmer * shadowDistanceFade;
}
else

envLightData.influenceShapeType = probe.influenceShapeType;
envLightData.dimmer = probe.dimmer;
envLightData.weight = probe.weight;
envLightData.multiplier = probe.multiplier;
envLightData.influenceExtents = probe.influenceExtents;
envLightData.blendNormalDistancePositive = probe.blendNormalDistancePositive;
envLightData.blendNormalDistanceNegative = probe.blendNormalDistanceNegative;

{
// If any light require it, we need to enabled bake shadow mask feature
m_enableBakeShadowMask = false;
m_maxShadowDistance = shadowSettings.maxShadowDistance;
m_lightList.Clear();

UpdateDataBuffers();
m_maxShadowDistance = shadowSettings.maxShadowDistance;
return m_enableBakeShadowMask;
}
}

void UpdateDataBuffers()
{
s_DirectionalLightDatas.SetData(m_lightList.directionalLights);
s_LightDatas.SetData(m_lightList.lights);
s_EnvLightDatas.SetData(m_lightList.envLights);
s_shadowDatas.SetData(m_lightList.shadows);
s_DecalDatas.SetData(DecalSystem.m_DecalDatas, 0, 0, Math.Min(DecalSystem.m_DecalDatasCount, k_MaxDecalsOnScreen)); // don't add more than the size of the buffer
m_DirectionalLightDatas.SetData(m_lightList.directionalLights);
m_LightDatas.SetData(m_lightList.lights);
m_EnvLightDatas.SetData(m_lightList.envLights);
m_shadowDatas.SetData(m_lightList.shadows);
m_DecalDatas.SetData(DecalSystem.m_DecalDatas, 0, 0, Math.Min(DecalSystem.m_DecalDatasCount, k_MaxDecalsOnScreen)); // don't add more than the size of the buffer
// These two buffers have been set in Rebuild()
s_ConvexBoundsBuffer.SetData(m_lightList.bounds);

cmd.SetGlobalTexture(HDShaderIDs._Env2DTextures, m_ReflectionPlanarProbeCache.GetTexCache());
cmd.SetGlobalMatrixArray(HDShaderIDs._Env2DCaptureVP, m_Env2DCaptureVP);
cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, s_DirectionalLightDatas);
cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, m_DirectionalLightDatas);
cmd.SetGlobalBuffer(HDShaderIDs._LightDatas, s_LightDatas);
cmd.SetGlobalBuffer(HDShaderIDs._LightDatas, m_LightDatas);
cmd.SetGlobalBuffer(HDShaderIDs._EnvLightDatas, s_EnvLightDatas);
cmd.SetGlobalBuffer(HDShaderIDs._EnvLightDatas, m_EnvLightDatas);
cmd.SetGlobalBuffer(HDShaderIDs._DecalDatas, s_DecalDatas);
cmd.SetGlobalBuffer(HDShaderIDs._DecalDatas, m_DecalDatas);
cmd.SetGlobalBuffer(HDShaderIDs._ShadowDatas, s_shadowDatas);
cmd.SetGlobalBuffer(HDShaderIDs._ShadowDatas, m_shadowDatas);
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplX, GetNumTileFtplX(hdCamera));
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplY, GetNumTileFtplY(hdCamera));

40
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopSettings.cs


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

// Setup by system
public bool isFptlEnabled = true;
static DebugUI.Widget[] s_DebugEntries;
public void CopyTo(LightLoopSettings lightLoopSettings)
{

aggregate.isFptlEnabled = !aggregateFrameSettings.enableForwardRenderingOnly || aggregate.enableFptlForForwardOpaque;
}
public static void RegisterDebug(string menuName, LightLoopSettings lightLoopSettings)
public static void RegisterDebug(LightLoopSettings lightLoopSettings, List<DebugUI.Widget> widgets)
s_DebugEntries = new DebugUI.Widget[]
widgets.AddRange(new []
new DebugUI.BoolField { displayName = "Enable Fptl for Forward Opaque", getter = () => lightLoopSettings.enableFptlForForwardOpaque, setter = value => lightLoopSettings.enableFptlForForwardOpaque = value },
new DebugUI.BoolField { displayName = "Enable Tile/Cluster", getter = () => lightLoopSettings.enableTileAndCluster, setter = value => lightLoopSettings.enableTileAndCluster = value },
new DebugUI.BoolField { displayName = "Enable Big Tile", getter = () => lightLoopSettings.enableBigTilePrepass, setter = value => lightLoopSettings.enableBigTilePrepass = value },
new DebugUI.BoolField { displayName = "Enable Compute Lighting", getter = () => lightLoopSettings.enableComputeLightEvaluation, setter = value => lightLoopSettings.enableComputeLightEvaluation = value },
new DebugUI.BoolField { displayName = "Enable Light Classification", getter = () => lightLoopSettings.enableComputeLightVariants, setter = value => lightLoopSettings.enableComputeLightVariants = value },
new DebugUI.BoolField { displayName = "Enable Material Classification", getter = () => lightLoopSettings.enableComputeMaterialVariants, setter = value => lightLoopSettings.enableComputeMaterialVariants = value }
};
var panel = DebugManager.instance.GetPanel(menuName, true);
panel.children.Add(s_DebugEntries);
}
public static void UnRegisterDebug(string menuName)
{
var panel = DebugManager.instance.GetPanel(menuName);
if (panel != null)
panel.children.Remove(s_DebugEntries);
new DebugUI.Container
{
displayName = "Lighting Settings",
children =
{
// Uncomment if you re-enable LIGHTLOOP_SINGLE_PASS multi_compile in lit*.shader
//new DebugUI.BoolField { displayName = "Enable Tile/Cluster", getter = () => lightLoopSettings.enableTileAndCluster, setter = value => lightLoopSettings.enableTileAndCluster = value },
new DebugUI.BoolField { displayName = "Enable Fptl for Forward Opaque", getter = () => lightLoopSettings.enableFptlForForwardOpaque, setter = value => lightLoopSettings.enableFptlForForwardOpaque = value },
new DebugUI.BoolField { displayName = "Enable Big Tile", getter = () => lightLoopSettings.enableBigTilePrepass, setter = value => lightLoopSettings.enableBigTilePrepass = value },
new DebugUI.BoolField { displayName = "Enable Compute Lighting", getter = () => lightLoopSettings.enableComputeLightEvaluation, setter = value => lightLoopSettings.enableComputeLightEvaluation = value },
new DebugUI.BoolField { displayName = "Enable Light Classification", getter = () => lightLoopSettings.enableComputeLightVariants, setter = value => lightLoopSettings.enableComputeLightVariants = value },
new DebugUI.BoolField { displayName = "Enable Material Classification", getter = () => lightLoopSettings.enableComputeMaterialVariants, setter = value => lightLoopSettings.enableComputeMaterialVariants = value }
}
}
});
}
}
}

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


//#define SHADOW_DISPATCH_USE_SEPARATE_PUNC_ALGOS // enables separate resources and algorithms for spot and point lights
// directional
#define SHADOW_DISPATCH_DIR_TEX 3
#define SHADOW_DISPATCH_DIR_TEX 0
#define SHADOW_DISPATCH_DIR_SMP 0
#define SHADOW_DISPATCH_DIR_ALG GPUSHADOWALGORITHM_PCF_TENT_5X5 // all cascades
#define SHADOW_DISPATCH_DIR_ALG_0 GPUSHADOWALGORITHM_PCF_TENT_7X7 // 1st cascade

// point
#define SHADOW_DISPATCH_POINT_TEX 3
#define SHADOW_DISPATCH_POINT_TEX 0
#define SHADOW_DISPATCH_SPOT_TEX 3
#define SHADOW_DISPATCH_SPOT_TEX 0
#define SHADOW_DISPATCH_PUNC_TEX 3
#define SHADOW_DISPATCH_PUNC_TEX 0
#define SHADOW_DISPATCH_PUNC_SMP 0
#define SHADOW_DISPATCH_PUNC_ALG GPUSHADOWALGORITHM_PCF_TENT_3X3

{
return GetDirectionalShadowAttenuation( shadowContext, positionWS, normalWS, shadowDataIndex, L );
}
float3 GetDirectionalShadowClosestSample( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int index, real4 L )
{
return EvalShadow_GetClosestSample_Cascade( shadowContext, shadowContext.tex2DArray[SHADOW_DISPATCH_DIR_TEX], positionWS, normalWS, index, L );
}
#endif

float GetPunctualShadowAttenuation( ShadowContext shadowContext, float3 positionWS, float3 normalWS, int shadowDataIndex, float3 L, float L_dist, float2 positionSS )
{
return GetPunctualShadowAttenuation( shadowContext, positionWS, normalWS, shadowDataIndex, L, L_dist );
}
float3 GetPunctualShadowClosestSample( ShadowContext shadowContext, real3 positionWS, int index, real3 L )
{
return EvalShadow_GetClosestSample_Punctual( shadowContext, shadowContext.tex2DArray[SHADOW_DISPATCH_PUNC_TEX], positionWS, index, L );
}
#endif

22
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/ShadowContext.hlsl


#ifndef LIGHTLOOP_SHADOW_CONTEXT_HLSL
#define LIGHTLOOP_SHADOW_CONTEXT_HLSL
#define SHADOWCONTEXT_MAX_TEX2DARRAY 4
#define SHADOWCONTEXT_MAX_TEX2DARRAY 1
#define SHADOWCONTEXT_MAX_SAMPLER 3
#define SHADOWCONTEXT_MAX_SAMPLER 0
#if SHADOWCONTEXT_MAX_TEX2DARRAY == 4
TEXTURE2D_ARRAY(_ShadowmapExp_VSM_0);
SAMPLER(sampler_ShadowmapExp_VSM_0);

TEXTURE2D_ARRAY(_ShadowmapExp_VSM_2);
SAMPLER(sampler_ShadowmapExp_VSM_2);
#endif
TEXTURE2D_ARRAY(_ShadowmapExp_PCF);
SAMPLER_CMP(sampler_ShadowmapExp_PCF);

// Currently we only use the PCF atlas.
// Keeping all other bindings for reference and for future PC dynamic shadow configuration as it's harmless anyway.
sc.tex2DArray[0] = _ShadowmapExp_VSM_0;
sc.tex2DArray[1] = _ShadowmapExp_VSM_1;
sc.tex2DArray[2] = _ShadowmapExp_VSM_2;
sc.tex2DArray[3] = _ShadowmapExp_PCF;
sc.tex2DArray[0] = _ShadowmapExp_PCF;
sc.compSamplers[0] = sampler_ShadowmapExp_PCF;
#if SHADOWCONTEXT_MAX_TEX2DARRAY == 4
sc.tex2DArray[1] = _ShadowmapExp_VSM_0;
sc.tex2DArray[2] = _ShadowmapExp_VSM_1;
sc.tex2DArray[3] = _ShadowmapExp_VSM_2;
#endif
#if SHADOWCONTEXT_MAX_SAMPLER == 3
sc.compSamplers[0] = sampler_ShadowmapExp_PCF;
#endif
return sc;
}

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


#include "LightDefinition.cs.hlsl"
#define SETTER_FLOAT3(data, field, value)\
data.##field##X = value.x;\
data.##field##Y = value.y;\
data.##field##Z = value.z
// The EnvLightData of the sky light contains a bunch of compile-time constants.
// This function sets them directly to allow the compiler to propagate them and optimize the code.
EnvLightData InitSkyEnvLightData(int envIndex)

output.influenceShapeType = ENVSHAPETYPE_SKY;
output.envIndex = envIndex;
SETTER_FLOAT3(output, influenceForward, float3(0.0, 0.0, 1.0));
SETTER_FLOAT3(output, influenceUp, float3(0.0, 1.0, 0.0));
SETTER_FLOAT3(output, influenceRight, float3(1.0, 0.0, 0.0));
SETTER_FLOAT3(output, influencePositionWS, float3(0.0, 0.0, 0.0));
output.influenceForward = float3(0.0, 0.0, 1.0);
output.influenceUp = float3(0.0, 1.0, 0.0);
output.influenceRight = float3(1.0, 0.0, 0.0);
output.influencePositionWS = float3(0.0, 0.0, 0.0);
output.dimmer = 1.0;
output.weight = 1.0;
output.multiplier = 1.0;
SETTER_FLOAT3(output, proxyForward, float3(0.0, 0.0, 1.0));
SETTER_FLOAT3(output, proxyUp, float3(0.0, 1.0, 0.0));
SETTER_FLOAT3(output, proxyRight, float3(1.0, 0.0, 0.0));
output.proxyForward = float3(0.0, 0.0, 1.0);
output.proxyUp = float3(0.0, 1.0, 0.0);
output.proxyRight = float3(1.0, 0.0, 0.0);
#undef SETTER_FLOAT3
#endif // UNITY_LIGHT_UTILITIES_INCLUDED

33
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtils.cs


// Physical light unit helper
// All light unit are in lumen (Luminous power)
// Punctual light (point, spot) are convert to candela (cd = lumens / steradian)
// Area light are convert to luminance (cd/(m^2*steradian)) with the following formulation: Luminous Power / (Area * PI * steradian)
// For our isotropic area lights which expect radiance(W / (sr* m^2)) in the shader:
// power = Integral{area, Integral{hemisphere, radiance * <N, L>}},
// power = area * Pi * radiance,
// radiance = power / (area * Pi).
// We use photometric unit, so radiance is luminance and power is luminous power
// Ref: Moving Frostbite to PBR
// Also good ref: https://www.radiance-online.org/community/workshops/2004-fribourg/presentations/Wandachowicz_paper.pdf

// convert intensity (lumen) to nits
public static float CalculateLineLightIntensity(float intensity, float lineWidth)
{
// Line lights in the shader expect intensity (W / sr).
// In the UI, we specify luminous flux(power) in lumens.
// First, it needs to be converted to radiometric units(radiant flux, W).
// Then we must recall how to compute power from intensity for a line light:
// power = Integral{length, Integral{sphere, intensity}}.
// For an isotropic line light, intensity is constant, so
// power = length * (4 * Pi) * intensity,
// intensity = power / (length * (4 * Pi)).
//Line lights expect radiance (W / (sr * m^2)) in the shader.
//In the UI, we specify luminous flux (power) in lumens.
//First, it needs to be converted to radiometric units (radiant flux, W).
//Then we must recall how to compute power from radiance:
//radiance = differential_power / (differrential_projected_area * differential_solid_angle),
//radiance = differential_power / (differrential_area * differential_solid_angle * <N, L>),
//power = Integral{area, Integral{hemisphere, radiance * <N, L>}}.
//Unlike tube lights, our line lights have no surface area, so the integral becomes:
//power = Integral{length, Integral{sphere, radiance}}.
//For an isotropic line light, radiance is constant, therefore:
//power = length * (4 * Pi) * radiance,
//radiance = power / (length * (4 * Pi)).
return intensity / (4.0f * Mathf.PI * lineWidth);
}
}

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/HDAdditionalReflectionData.cs


using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine.Serialization;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEngine.Experimental.Rendering
{

#pragma warning restore 414
public ShapeType influenceShape;
[Range(0.0f,1.0f)]
public float dimmer = 1.0f;
[FormerlySerializedAsAttribute("dimmer")]
public float multiplier = 1.0f;
[Range(0.0f, 1.0f)]
public float weight = 1.0f;
public float influenceSphereRadius = 3.0f;
public float sphereReprojectionVolumeRadius = 1.0f;
public bool useSeparateProjectionVolume = false;

13
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/PlanarReflectionProbe.cs


using UnityEngine.Rendering;
using UnityEngine.Serialization;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{

[SerializeField]
Vector3 m_CaptureLocalPosition;
[SerializeField]
[Range(0, 1)]
float m_Dimmer = 1;
[FormerlySerializedAsAttribute("m_Dimmer")]
float m_Multiplier = 1.0f;
[SerializeField]
[Range(0.0f, 1.0f)]
float m_Weight = 1.0f;
[SerializeField]
ReflectionProbeMode m_Mode = ReflectionProbeMode.Baked;
[SerializeField]

}
public Bounds bounds { get { return m_InfluenceVolume.GetBoundsAt(transform); } }
public Vector3 captureLocalPosition { get { return m_CaptureLocalPosition; } set { m_CaptureLocalPosition = value; } }
public float dimmer { get { return m_Dimmer; } }
public float weight { get { return m_Weight; } }
public float multiplier { get { return m_Multiplier; } }
public ReflectionProbeMode mode { get { return m_Mode; } }
public Matrix4x4 influenceToWorld
{

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


m_ProbeSize = probeSize;
m_CacheSize = cacheSize;
m_TextureCache = new TextureCache2D();
m_TextureCache = new TextureCache2D("PlanarReflectionProbe");
m_TextureCache.AllocTextureArray(cacheSize, probeSize, probeSize, probeFormat, isMipmaped);
m_IBLFilterGGX = iblFilter;

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

public void Release()
{
if (m_TextureCache != null)
{
m_TextureCache.Release();
m_TextureCache = null;
}
if (m_TempRenderTexture != null)
{
m_TempRenderTexture.Release();
m_TempRenderTexture = null;
}
if (m_ConvolutionTargetTexture != null)
{
m_ConvolutionTargetTexture.Release();
m_ConvolutionTargetTexture = null;
}
m_TextureCache.Release();
CoreUtils.Destroy(m_TempRenderTexture);
CoreUtils.Destroy(m_ConvolutionTargetTexture);
m_ProbeBakingState = null;
CoreUtils.Destroy(m_ConvertTextureMaterial);

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ProbeWrapper.cs


public abstract ReflectionProbeMode mode { get; }
public abstract Texture texture { get; }
// Position of the center of the probe in capture space
public abstract float dimmer { get; }
public abstract float weight { get; }
public abstract float multiplier { get; }
public abstract Matrix4x4 influenceToWorld { get; }
public abstract EnvShapeType influenceShapeType { get; }
public abstract Vector3 influenceExtents { get; }

public override Texture texture { get { return probe.texture; } }
public override ReflectionProbeMode mode { get { return probe.probe.mode; } }
public override EnvShapeType influenceShapeType { get { return ConvertShape(additional.influenceShape); } }
public override float dimmer { get { return additional.dimmer; } }
public override float weight { get { return additional.weight; } }
public override float multiplier { get { return additional.multiplier; } }
public override Vector3 influenceExtents
{
get

public override Matrix4x4 influenceToWorld { get { return planarReflectionProbe.influenceToWorld; } }
public override Texture texture { get { return planarReflectionProbe.texture; } }
public override EnvShapeType influenceShapeType { get { return ConvertShape(planarReflectionProbe.influenceVolume.shapeType); } }
public override float dimmer { get { return planarReflectionProbe.dimmer; } }
public override float weight { get { return planarReflectionProbe.weight; } }
public override float multiplier { get { return planarReflectionProbe.multiplier; } }
public override Vector3 influenceExtents
{
get

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


m_ProbeSize = probeSize;
m_CacheSize = cacheSize;
m_TextureCache = new TextureCacheCubemap();
m_TextureCache = new TextureCacheCubemap("ReflectionProbe");
m_TextureCache.AllocTextureArray(cacheSize, probeSize, probeFormat, isMipmaped, m_CubeToPano);
m_IBLFilterGGX = iblFilter;

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

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

public void Release()
{
if (m_TextureCache != null)
{
m_TextureCache.Release();
m_TextureCache = null;
}
if (m_TempRenderTexture != null)
{
m_TempRenderTexture.Release();
m_TempRenderTexture = null;
}
if (m_ConvolutionTargetTexture != null)
{
m_ConvolutionTargetTexture.Release();
m_ConvolutionTargetTexture = null;
}
m_TextureCache.Release();
CoreUtils.Destroy(m_TempRenderTexture);
CoreUtils.Destroy(m_ConvolutionTargetTexture);
m_ProbeBakingState = null;
CoreUtils.Destroy(m_ConvertTextureMaterial);

48
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/VolumeProjection.hlsl


{
return transpose(
float3x3(
GetProxyRight(lightData),
GetProxyUp(lightData),
GetProxyForward(lightData)
lightData.proxyRight,
lightData.proxyUp,
lightData.proxyForward
)
); // worldToLocal assume no scaling
}

float3 positionPS = positionWS - GetProxyPositionWS(lightData);
float3 positionPS = positionWS - lightData.proxyPositionWS;
positionPS = mul(positionPS, worldToPS).xyz;
return positionPS;
}

float sphereOuterDistance = lightData.proxyExtentsX;
float sphereOuterDistance = lightData.proxyExtents.x;
float projectionDistance = IntersectRaySphereSimple(positionPS, dirPS, sphereOuterDistance);
projectionDistance = max(projectionDistance, lightData.minProjectionDistance); // Setup projection to infinite if requested (mean no projection shape)

float IntersectBoxProxy(EnvLightData lightData, float3 dirPS, float3 positionPS)
{
float3 boxOuterDistance = GetProxyExtents(lightData);
float3 boxOuterDistance = lightData.proxyExtents;
float projectionDistance = IntersectRayAABBSimple(positionPS, dirPS, -boxOuterDistance, boxOuterDistance);
projectionDistance = max(projectionDistance, lightData.minProjectionDistance); // Setup projection to infinite if requested (mean no projection shape)

float InfluenceSphereWeight(EnvLightData lightData, BSDFData bsdfData, float3 positionWS, float3 positionLS, float3 dirLS)
{
float lengthPositionLS = length(positionLS);
float sphereInfluenceDistance = lightData.influenceExtentsX - lightData.blendDistancePositiveX;
float sphereInfluenceDistance = lightData.influenceExtents.x - lightData.blendDistancePositive.x;
float alpha = saturate(1.0 - distFade / max(lightData.blendDistancePositiveX, 0.0001)); // avoid divide by zero
float alpha = saturate(1.0 - distFade / max(lightData.blendDistancePositive.x, 0.0001)); // avoid divide by zero
float insideInfluenceNormalVolume = lengthPositionLS <= (lightData.influenceExtentsX - lightData.blendNormalDistancePositiveX) ? 1.0 : 0.0;
float insideWeight = InfluenceFadeNormalWeight(bsdfData.normalWS, normalize(positionWS - GetCapturePositionWS(lightData)));
float insideInfluenceNormalVolume = lengthPositionLS <= (lightData.influenceExtents.x - lightData.blendNormalDistancePositive.x) ? 1.0 : 0.0;
float insideWeight = InfluenceFadeNormalWeight(bsdfData.normalWS, normalize(positionWS - lightData.capturePositionWS));
alpha *= insideInfluenceNormalVolume ? 1.0 : insideWeight;
#endif

float InfluenceBoxWeight(EnvLightData lightData, BSDFData bsdfData, float3 positionWS, float3 positionIS, float3 dirIS)
{
float3 influenceExtents = GetInfluenceExtents(lightData);
float3 influenceExtents = lightData.influenceExtents;
// 2. Process the position influence
// Calculate falloff value, so reflections on the edges of the volume would gradually blend to previous reflection.
#if defined(ENVMAP_FEATURE_PERFACEINFLUENCE) || defined(ENVMAP_FEATURE_INFLUENCENORMAL) || defined(ENVMAP_FEATURE_PERFACEFADE)

#if defined(ENVMAP_FEATURE_PERFACEINFLUENCE)
// Influence falloff for each face
float3 negativeFalloff = negativeDistance / max(0.0001, GetBlendDistanceNegative(lightData));
float3 positiveFalloff = positiveDistance / max(0.0001, GetBlendDistancePositive(lightData));
float3 negativeFalloff = negativeDistance / max(0.0001, lightData.blendDistanceNegative);
float3 positiveFalloff = positiveDistance / max(0.0001, lightData.blendDistancePositive);
// Fallof is the min for all faces
float influenceFalloff = min(

float alpha = saturate(influenceFalloff);
#else
float distFace = DistancePointBox(positionIS, -influenceExtents + lightData.blendDistancePositiveX, influenceExtents - lightData.blendDistancePositiveX);
float alpha = saturate(1.0 - distFace / max(lightData.blendDistancePositiveX, 0.0001));
float distFace = DistancePointBox(positionIS, -influenceExtents + lightData.blendDistancePositive.x, influenceExtents - lightData.blendDistancePositive.x);
float alpha = saturate(1.0 - distFace / max(lightData.blendDistancePositive.x, 0.0001));
float3 belowPositiveInfluenceNormalVolume = positiveDistance / max(0.0001, GetBlendNormalDistancePositive(lightData));
float3 aboveNegativeInfluenceNormalVolume = negativeDistance / max(0.0001, GetBlendNormalDistanceNegative(lightData));
float3 belowPositiveInfluenceNormalVolume = positiveDistance / max(0.0001, lightData.blendNormalDistancePositive);
float3 aboveNegativeInfluenceNormalVolume = negativeDistance / max(0.0001, lightData.blendNormalDistanceNegative);
float insideWeight = InfluenceFadeNormalWeight(bsdfData.normalWS, normalize(positionWS - GetCapturePositionWS(lightData)));
float insideWeight = InfluenceFadeNormalWeight(bsdfData.normalWS, normalize(positionWS - lightData.capturePositionWS));
alpha *= insideInfluenceNormalVolume ? 1.0 : insideWeight;
#endif

// We consider R.x as cos(X) and then fade as angle from 60°(=acos(1/2)) to 75°(=acos(1/4))
// For positive axes: axisFade = (R - 1/4) / (1/2 - 1/4)
// <=> axisFace = 4 * R - 1;
float3 faceFade = saturate((4 * dirIS - 1) * GetBoxSideFadePositive(lightData))
+ saturate((-4 * dirIS - 1) * GetBoxSideFadeNegative(lightData));
float3 faceFade = saturate((4 * dirIS - 1) * lightData.boxSideFadePositive)
+ saturate((-4 * dirIS - 1) * lightData.boxSideFadeNegative);
alpha *= saturate(faceFade.x + faceFade.y + faceFade.z);
#endif

{
return transpose(
float3x3(
GetInfluenceRight(lightData),
GetInfluenceUp(lightData),
GetInfluenceForward(lightData)
lightData.influenceRight,
lightData.influenceUp,
lightData.influenceForward
)
); // worldToLocal assume no scaling
}

float3 positionIS = positionWS - GetInfluencePositionWS(lightData);
float3 positionIS = positionWS - lightData.influencePositionWS;
positionIS = mul(positionIS, worldToIS).xyz;
return positionIS;
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/MRTBufferManager.cs


public abstract void CreateBuffers();
public void BindBufferAsTextures(CommandBuffer cmd)
public virtual void BindBufferAsTextures(CommandBuffer cmd)
{
for (int i = 0; i < m_BufferCount; ++i)
{

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs.hlsl


// PackingRules = Exact
struct DecalData
{
float4x4 worldToDecal;
float4x4 worldToDecal;
float4x4 normalToWorld;
};

float4x4 GetWorldToDecal(DecalData value)
{
return value.worldToDecal;
}
float4x4 GetNormalToWorld(DecalData value)
{
return value.normalToWorld;

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalUtilities.hlsl


return _DecalDatas[j];
}
// Caution: We can't compute LOD inside a dynamic loop. The gradient are not accessible.
// we need to find a way to calculate mips. For now just fetch first mip of the decals
src.xyz = mul(decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, ComputeTextureLOD(texCoords)))) * 0.5f + 0.5f;
src.xyz = mul(decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, 0 /* ComputeTextureLOD(texCoords) */))) * 0.5f + 0.5f;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);

void ApplyBlendDiffuse(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float blend)
{
float4 src = SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, ComputeTextureLOD(texCoords));
float4 src = SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, 0 /* ComputeTextureLOD(texCoords) */);
src.w *= blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);

void ApplyBlendMask(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float blend)
{
float4 src = SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, ComputeTextureLOD(texCoords));
float4 src = SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, 0 /* ComputeTextureLOD(texCoords) */);
src.z = src.w;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);

21
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GBufferManager.cs


using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{

bool m_EnableShadowMask = false;
bool m_SupportShadowMask = false;
RenderPipelineMaterial m_DeferredMaterial;
protected RenderTargetIdentifier[] m_RTIDsNoShadowMask;

m_DeferredMaterial = deferredMaterial;
m_GBufferCount = deferredMaterial.GetMaterialGBufferCount();
m_EnableShadowMask = enableBakeShadowMask;
m_SupportShadowMask = enableBakeShadowMask;
m_RTIDsNoShadowMask = new RenderTargetIdentifier[m_GBufferCount];
}

m_RTIDsNoShadowMask[gbufferIndex] = HDShaderIDs._GBufferTexture[gbufferIndex];
}
if (m_EnableShadowMask)
if (m_SupportShadowMask)
}
}
public override void BindBufferAsTextures(CommandBuffer cmd)
{
for (int i = 0; i < m_BufferCount; ++i)
{
cmd.SetGlobalTexture(m_TextureShaderIDs[i], m_RTs[i]);
}
// When shadow mask are disabled (i.e we haven't created shadow mask texture, bind a white texture).
if (!m_SupportShadowMask)
{
cmd.SetGlobalTexture(HDShaderIDs._ShadowMaskTexture, RuntimeUtilities.whiteTexture);
}
}

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


m_GgxIblSampleData.enableRandomWrite = true;
m_GgxIblSampleData.filterMode = FilterMode.Point;
m_GgxIblSampleData.name = CoreUtils.GetRenderTargetAutoName(m_GgxIblMaxSampleCount, k_GgxIblMipCountMinusOne, RenderTextureFormat.ARGBHalf, "GGXIblSampleData");
m_GgxIblSampleData.hideFlags = HideFlags.HideAndDontSave;
m_GgxIblSampleData.Create();
m_ComputeGgxIblSampleDataCS.SetTexture(m_ComputeGgxIblSampleDataKernel, "output", m_GgxIblSampleData);

var lookAt = Matrix4x4.LookAt(Vector3.zero, CoreUtils.lookAtList[i], CoreUtils.upVectorList[i]);
m_faceWorldToViewMatrixMatrices[i] = lookAt * Matrix4x4.Scale(new Vector3(1.0f, 1.0f, -1.0f)); // Need to scale -1.0 on Z to match what is being done in the camera.wolrdToCameraMatrix API. ...
}
}
public void Cleanup()
{
CoreUtils.Destroy(m_GgxConvolveMaterial);
CoreUtils.Destroy(m_GgxIblSampleData);
}
void FilterCubemapCommon( CommandBuffer cmd,

47
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLit.shader


[HideInInspector] _ZWrite ("__zw", Float) = 1.0
[HideInInspector] _CullMode("__cullmode", Float) = 2.0
[HideInInspector] _ZTestDepthEqualForOpaque("_ZTestDepthEqualForOpaque", Int) = 4 // Less equal
[HideInInspector] _ZTestGBuffer("_ZTestGBuffer", Int) = 4
[ToggleUI] _EnableFogOnTransparent("Enable Fog", Float) = 1.0
[ToggleUI] _EnableBlendModePreserveSpecularLighting("Enable Blend Mode Preserve Specular Lighting", Float) = 1.0

Tags { "LightMode" = "GBuffer" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
ZTest[_ZTestGBuffer]
Stencil
{

#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#include "../../Debug/DebugDisplay.hlsl"
#endif
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL
}
// This pass is the same as GBuffer only it does not do alpha test (the clip instruction is removed)
// This is due to the fact that on GCN, any shader with a clip instruction cannot benefit from HiZ so when we do a prepass, in order to get the most performance, we need to make a special case in the subsequent GBuffer pass.
Pass
{
Name "GBufferWithPrepass" // Name is not used
Tags { "LightMode" = "GBufferWithPrepass" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
Stencil
{
WriteMask [_StencilWriteMask]
Ref [_StencilRef]
Comp Always
Pass Replace
}
HLSLPROGRAM
#pragma multi_compile _ DEBUG_DISPLAY
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#ifdef _ALPHATEST_ON
// When we have alpha test, we will force a depth prepass so we always bypass the clip instruction in the GBuffer
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#endif
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#include "../../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#include "../../Debug/DebugDisplay.hlsl"

#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
// #include "../../Lighting/Forward.hlsl"
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
//#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#define LIGHTLOOP_TILE_PASS
#pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST
#define SHADERPASS SHADERPASS_FORWARD

50
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitTessellation.shader


[HideInInspector] _ZWrite ("__zw", Float) = 1.0
[HideInInspector] _CullMode("__cullmode", Float) = 2.0
[HideInInspector] _ZTestDepthEqualForOpaque("_ZTestDepthEqualForOpaque", Int) = 4 // Less equal
[HideInInspector] _ZTestGBuffer("_ZTestGBuffer", Int) = 4
[ToggleUI] _EnableFogOnTransparent("Enable Fog", Float) = 1.0
[ToggleUI] _EnableBlendModePreserveSpecularLighting("Enable Blend Mode Preserve Specular Lighting", Float) = 1.0

Tags { "LightMode" = "GBuffer" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
ZTest[_ZTestGBuffer]
Stencil
{

#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#include "../../Debug/DebugDisplay.hlsl"
#endif
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL
}
// This pass is the same as GBuffer only it does not do alpha test (the clip instruction is removed)
// This is due to the fact that on GCN, any shader with a clip instruction cannot benefit from HiZ so when we do a prepass, in order to get the most performance, we need to make a special case in the subsequent GBuffer pass.
Pass
{
Name "GBufferWithPrepass" // Name is not used
Tags { "LightMode" = "GBufferWithPrepass" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
Stencil
{
WriteMask [_StencilWriteMask]
Ref [_StencilRef]
Comp Always
Pass Replace
}
HLSLPROGRAM
#pragma hull Hull
#pragma domain Domain
#pragma multi_compile _ DEBUG_DISPLAY
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#ifdef _ALPHATEST_ON
// When we have alpha test, we will force a depth prepass so we always bypass the clip instruction in the GBuffer
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#endif
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#include "../../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#include "../../Debug/DebugDisplay.hlsl"

#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
// #include "../../Lighting/Forward.hlsl"
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
//#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#define LIGHTLOOP_TILE_PASS
#pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST
#define SHADERPASS SHADERPASS_FORWARD

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.cs


{
hideFlags = HideFlags.HideAndDontSave,
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Bilinear
filterMode = FilterMode.Bilinear,
name = CoreUtils.GetTextureAutoName(k_LtcLUTResolution, k_LtcLUTResolution, TextureFormat.RGBAHalf, depth: 3, dim: TextureDimension.Tex2DArray, name: "LTC_LUT")
};
LoadLUT(m_LtcData, 0, TextureFormat.RGBAHalf, s_LtcGGXMatrixData);

public override void Cleanup()
{
CoreUtils.Destroy(m_InitPreFGD);
CoreUtils.Destroy(m_PreIntegratedFGD);
CoreUtils.Destroy(m_LtcData);
// TODO: how to delete RenderTexture ? or do we need to do it ?
m_isInit = false;

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


// bake lighting function
//-----------------------------------------------------------------------------
// GetBakedDiffuseLigthing function compute the bake lighting + emissive color to be store in emissive buffer (Deferred case)
// GetBakedDiffuseLighting function compute the bake lighting + emissive color to be store in emissive buffer (Deferred case)
float3 GetBakedDiffuseLigthing(SurfaceData surfaceData, BuiltinData builtinData, BSDFData bsdfData, PreLightData preLightData)
float3 GetBakedDiffuseLighting(SurfaceData surfaceData, BuiltinData builtinData, BSDFData bsdfData, PreLightData preLightData)
{
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING))
{

{
// TODO: perform bilinear filtering of the shadow map.
// Recompute transmittance using the thickness value computed from the shadow map.
#if 0
// Does not work, I get a compiler crash...
float3 occluderPosWS = EvalShadow_GetClosestSample_Cascade(lightLoopContext.shadowContext, posInput.positionWS, bsdfData.normalWS, lightData.shadowIndex, float4(L, 0));
#else
#define SHADOW_DISPATCH_DIR_TEX 3 // Manually keep it in sync with Shadow.hlsl...
float3 occluderPosWS = EvalShadow_GetClosestSample_Cascade(lightLoopContext.shadowContext, lightLoopContext.shadowContext.tex2DArray[SHADOW_DISPATCH_DIR_TEX], posInput.positionWS, bsdfData.normalWS, lightData.shadowIndex, float4(L, 0));
#endif
float3 occluderPosWS = GetDirectionalShadowClosestSample(lightLoopContext.shadowContext, posInput.positionWS, bsdfData.normalWS, lightData.shadowIndex, float4(L, 0));
float thicknessInUnits = distance(posInput.positionWS, occluderPosWS);
float thicknessInMeters = thicknessInUnits * _WorldScales[bsdfData.diffusionProfile].x;

{
// TODO: perform bilinear filtering of the shadow map.
// Recompute transmittance using the thickness value computed from the shadow map.
#if 0
// Does not work, I get a compiler crash...
float3 occluderPosWS = EvalShadow_GetClosestSample_Punctual(lightLoopContext.shadowContext, posInput.positionWS, lightData.shadowIndex, L);
#else
#define SHADOW_DISPATCH_PUNC_TEX 3 // Manually keep it in sync with Shadow.hlsl...
float3 occluderPosWS = EvalShadow_GetClosestSample_Punctual(lightLoopContext.shadowContext, lightLoopContext.shadowContext.tex2DArray[SHADOW_DISPATCH_PUNC_TEX], posInput.positionWS, lightData.shadowIndex, L);
#endif
float3 occluderPosWS = GetPunctualShadowClosestSample(lightLoopContext.shadowContext, posInput.positionWS, lightData.shadowIndex, L);
float thicknessInUnits = distance(posInput.positionWS, occluderPosWS);
float thicknessInMeters = thicknessInUnits * _WorldScales[bsdfData.diffusionProfile].x;

{
projectionDistance = IntersectSphereProxy(lightData, dirPS, positionPS);
// We can reuse dist calculate in LS directly in WS as there is no scaling. Also the offset is already include in lightData.capturePositionWS
float3 capturePositionWS = GetCapturePositionWS(lightData);
float3 capturePositionWS = lightData.capturePositionWS;
R = (positionWS + projectionDistance * R) - capturePositionWS;
// Test again for clear coat

projectionDistance = IntersectBoxProxy(lightData, dirPS, positionPS);
// No need to normalize for fetching cubemap
// We can reuse dist calculate in LS directly in WS as there is no scaling. Also the offset is already include in lightData.capturePositionWS
float3 capturePositionWS = GetCapturePositionWS(lightData);
float3 capturePositionWS = lightData.capturePositionWS;
R = (positionWS + projectionDistance * R) - capturePositionWS;
// TODO: add distance based roughness

float roughness = PerceptualRoughnessToRoughness(preLightData.iblPerceptualRoughness);
R = lerp(R, preLightData.iblR, saturate(smoothstep(0, 1, roughness * roughness)));
float3 sampleDirectionDiscardWS = GetSampleDirectionDiscardWS(lightData);
float3 sampleDirectionDiscardWS = lightData.sampleDirectionDiscardWS;
if (dot(sampleDirectionDiscardWS, R) < 0)
return lighting;

#endif // LIT_DISPLAY_REFERENCE_IBL
weight *= lightData.weight;
envLighting *= weight * lightData.dimmer;
envLighting *= weight * lightData.multiplier;
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
lighting.specularReflected = envLighting;

float3 modifiedDiffuseColor = ApplySubsurfaceScatteringTexturingMode(texturingMode, bsdfData.diffuseColor);
// Apply the albedo to the direct diffuse lighting (only once). The indirect (baked)
// diffuse lighting has already had the albedo applied in GetBakedDiffuseLigthing().
// diffuse lighting has already had the albedo applied in GetBakedDiffuseLighting().
diffuseLighting = modifiedDiffuseColor * lighting.direct.diffuse + bakeDiffuseLighting;
// If refraction is enable we use the transmittanceMask to lerp between current diffuse lighting and refraction value

50
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.shader


[HideInInspector] _CullModeForward("__cullmodeForward", Float) = 2.0 // This mode is dedicated to Forward to correctly handle backface then front face rendering thin transparent
[HideInInspector] _ZTestDepthEqualForOpaque("_ZTestDepthEqualForOpaque", Int) = 4 // Less equal
[HideInInspector] _ZTestModeDistortion("_ZTestModeDistortion", Int) = 8
[HideInInspector] _ZTestGBuffer("_ZTestGBuffer", Int) = 4
[ToggleUI] _EnableFogOnTransparent("Enable Fog", Float) = 1.0
[ToggleUI] _EnableBlendModePreserveSpecularLighting("Enable Blend Mode Preserve Specular Lighting", Float) = 1.0

Tags { "LightMode" = "GBuffer" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
ZTest [_ZTestGBuffer]
Stencil
{

#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#include "../../Debug/DebugDisplay.hlsl"
#endif
#include "../../Material/Material.hlsl"
#include "ShaderPass/LitSharePass.hlsl"
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL
}
// This pass is the same as GBuffer only it does not do alpha test (the clip instruction is removed)
// This is due to the fact that on GCN, any shader with a clip instruction cannot benefit from HiZ so when we do a prepass, in order to get the most performance, we need to make a special case in the subsequent GBuffer pass.
Pass
{
Name "GBufferWithPrepass" // Name is not used
Tags { "LightMode" = "GBufferWithPrepass" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
Stencil
{
WriteMask [_StencilWriteMask]
Ref [_StencilRef]
Comp Always
Pass Replace
}
HLSLPROGRAM
#pragma multi_compile _ DEBUG_DISPLAY
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#ifdef _ALPHATEST_ON
// When we have alpha test, we will force a depth prepass so we always bypass the clip instruction in the GBuffer
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#endif
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST // This define allow to not perform the alpha test (alpha test is done during depth prepass)
#include "../../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#include "../../Debug/DebugDisplay.hlsl"

#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
// #include "../../Lighting/Forward.hlsl"
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
//#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#define LIGHTLOOP_TILE_PASS
#pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST
#define SHADERPASS SHADERPASS_FORWARD

#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
// #include "../../Lighting/Forward.hlsl"
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
//#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#define LIGHTLOOP_TILE_PASS
#pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST
#define SHADERPASS SHADERPASS_FORWARD

53
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitTessellation.shader


[HideInInspector] _CullModeForward("__cullmodeForward", Float) = 2.0 // This mode is dedicated to Forward to correctly handle backface then front face rendering thin transparent
[HideInInspector] _ZTestDepthEqualForOpaque("_ZTestDepthEqualForOpaque", Int) = 4 // Less equal
[HideInInspector] _ZTestModeDistortion("_ZTestModeDistortion", Int) = 8
[HideInInspector] _ZTestGBuffer("_ZTestGBuffer", Int) = 4
[ToggleUI] _EnableFogOnTransparent("Enable Fog", Float) = 1.0
[ToggleUI] _EnableBlendModePreserveSpecularLighting("Enable Blend Mode Preserve Specular Lighting", Float) = 1.0

Tags { "LightMode" = "GBuffer" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
ZTest[_ZTestGBuffer]
Stencil
{

#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#include "../../Debug/DebugDisplay.hlsl"
#endif
#include "../../Material/Material.hlsl"
#include "ShaderPass/LitSharePass.hlsl"
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL
}
// This pass is the same as GBuffer only it does not do alpha test (the clip instruction is removed)
// This is due to the fact that on GCN, any shader with a clip instruction cannot benefit from HiZ so when we do a prepass, in order to get the most performance, we need to make a special case in the subsequent GBuffer pass.
Pass
{
Name "GBufferWithPrepass" // Name is not used
Tags { "LightMode" = "GBufferWithPrepass" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
Stencil
{
WriteMask [_StencilWriteMask]
Ref [_StencilRef]
Comp Always
Pass Replace
}
HLSLPROGRAM
#pragma hull Hull
#pragma domain Domain
#pragma multi_compile _ DEBUG_DISPLAY
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#ifdef _ALPHATEST_ON
// When we have alpha test, we will force a depth prepass so we always bypass the clip instruction in the GBuffer
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#endif
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST // This define allow to not perform the alpha test (alpha test is done during depth prepass)
#include "../../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#include "../../Debug/DebugDisplay.hlsl"

#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
// #include "../../Lighting/Forward.hlsl"
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
//#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#define LIGHTLOOP_TILE_PASS
#pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST
#define SHADERPASS SHADERPASS_FORWARD

#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
// #include "../../Lighting/Forward.hlsl"
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
//#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#define LIGHTLOOP_TILE_PASS
#pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST
#define SHADERPASS SHADERPASS_FORWARD

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/MaterialUtilities.hlsl


#ifdef UNITY_LIGHTMAP_FULL_HDR
bool useRGBMLightmap = false;
float4 decodeInstructions = float4(0.0, 0.0, 0.0, 0.0); // Never used but needed for the interface since it supports gamma lightmaps
#if defined(UNITY_LIGHTMAP_RGBM_ENCODING)
float4 decodeInstructions = float4(34.493242, 2.2, 0.0, 0.0); // range^2.2 = 5^2.2, gamma = 2.2
#else
float4 decodeInstructions = float4(2.0, 2.2, 0.0, 0.0); // range = 2.0^2.2 = 4.59
#endif
#endif
#ifdef LIGHTMAP_ON

uvStaticLightmap, unity_LightmapST, normalWS, useRGBMLightmap);
uvStaticLightmap, unity_LightmapST, normalWS, useRGBMLightmap, decodeInstructions);
bakeDiffuseLighting += SampleSingleLightmap(TEXTURE2D_PARAM(unity_Lightmap, samplerunity_Lightmap), uvStaticLightmap, unity_LightmapST, useRGBMLightmap);
bakeDiffuseLighting += SampleSingleLightmap(TEXTURE2D_PARAM(unity_Lightmap, samplerunity_Lightmap), uvStaticLightmap, unity_LightmapST, useRGBMLightmap, decodeInstructions);
#endif
#endif

TEXTURE2D_PARAM(unity_DynamicDirectionality, samplerunity_DynamicLightmap),
uvDynamicLightmap, unity_DynamicLightmapST, normalWS, false);
uvDynamicLightmap, unity_DynamicLightmapST, normalWS, false, decodeInstructions);
bakeDiffuseLighting += SampleSingleLightmap(TEXTURE2D_PARAM(unity_DynamicLightmap, samplerunity_DynamicLightmap), uvDynamicLightmap, unity_DynamicLightmapST, false);
bakeDiffuseLighting += SampleSingleLightmap(TEXTURE2D_PARAM(unity_DynamicLightmap, samplerunity_DynamicLightmap), uvDynamicLightmap, unity_DynamicLightmapST, false, decodeInstructions);
#endif
#endif

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


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

// View
public bool enableForwardRenderingOnly = false; // TODO: Currently there is no way to strip the extra forward shaders generated by the shaders compiler, so we can switch dynamically.
public bool enableDepthPrepassWithDeferredRendering = false;
public bool enableAlphaTestOnlyInDeferredPrepass = false;
public bool enableTransparentPrepass = true;
public bool enableMotionVectors = true; // Enable/disable whole motion vectors pass (Camera + Object).

public bool enableShadowMask = false;
public LightLoopSettings lightLoopSettings = new LightLoopSettings();
static DebugUI.Widget[] s_DebugEntries;
public void CopyTo(FrameSettings frameSettings)
{

frameSettings.enableForwardRenderingOnly = this.enableForwardRenderingOnly;
frameSettings.enableDepthPrepassWithDeferredRendering = this.enableDepthPrepassWithDeferredRendering;
frameSettings.enableAlphaTestOnlyInDeferredPrepass = this.enableAlphaTestOnlyInDeferredPrepass;
frameSettings.enableTransparentPrepass = this.enableTransparentPrepass;
frameSettings.enableMotionVectors = this.enableMotionVectors;

// as rendering everything in wireframe + deferred do not play well together
aggregate.enableForwardRenderingOnly = srcFrameSettings.enableForwardRenderingOnly || GL.wireframe || renderPipelineSettings.supportForwardOnly;
aggregate.enableDepthPrepassWithDeferredRendering = srcFrameSettings.enableDepthPrepassWithDeferredRendering;
aggregate.enableAlphaTestOnlyInDeferredPrepass = srcFrameSettings.enableAlphaTestOnlyInDeferredPrepass;
aggregate.enableTransparentPrepass = srcFrameSettings.enableTransparentPrepass;
aggregate.enableMotionVectors = camera.cameraType != CameraType.Reflection && srcFrameSettings.enableMotionVectors && renderPipelineSettings.supportMotionVectors;

public static void RegisterDebug(string menuName, FrameSettings frameSettings)
{
s_DebugEntries = new DebugUI.Widget[]
List<DebugUI.Widget> widgets = new List<DebugUI.Widget>();
widgets.AddRange(
new DebugUI.Widget[]
new DebugUI.BoolField { displayName = "Enable Shadows", getter = () => frameSettings.enableShadow, setter = value => frameSettings.enableShadow = value },
new DebugUI.BoolField { displayName = "Enable Contact Shadows", getter = () => frameSettings.enableContactShadows, setter = value => frameSettings.enableContactShadows = value },
new DebugUI.BoolField { displayName = "Enable SSR", getter = () => frameSettings.enableSSR, setter = value => frameSettings.enableSSR = value },
new DebugUI.BoolField { displayName = "Enable SSAO", getter = () => frameSettings.enableSSAO, setter = value => frameSettings.enableSSAO = value },
new DebugUI.BoolField { displayName = "Enable SubsurfaceScattering", getter = () => frameSettings.enableSubsurfaceScattering, setter = value => frameSettings.enableSubsurfaceScattering = value },
new DebugUI.BoolField { displayName = "Enable Transmission", getter = () => frameSettings.enableTransmission, setter = value => frameSettings.enableTransmission = value },
new DebugUI.BoolField { displayName = "Forward Only", getter = () => frameSettings.enableForwardRenderingOnly, setter = value => frameSettings.enableForwardRenderingOnly = value },
new DebugUI.BoolField { displayName = "Deferred Depth Prepass", getter = () => frameSettings.enableDepthPrepassWithDeferredRendering, setter = value => frameSettings.enableDepthPrepassWithDeferredRendering = value },
new DebugUI.BoolField { displayName = "Deferred Depth Prepass ATest Only", getter = () => frameSettings.enableAlphaTestOnlyInDeferredPrepass, setter = value => frameSettings.enableAlphaTestOnlyInDeferredPrepass = value },
new DebugUI.BoolField { displayName = "Enable Transparent Prepass", getter = () => frameSettings.enableTransparentPrepass, setter = value => frameSettings.enableTransparentPrepass = value },
new DebugUI.BoolField { displayName = "Enable Motion Vectors", getter = () => frameSettings.enableMotionVectors, setter = value => frameSettings.enableMotionVectors = value },
new DebugUI.BoolField { displayName = "Enable Object Motion Vectors", getter = () => frameSettings.enableObjectMotionVectors, setter = value => frameSettings.enableObjectMotionVectors = value },
new DebugUI.BoolField { displayName = "Enable DBuffer", getter = () => frameSettings.enableDBuffer, setter = value => frameSettings.enableDBuffer = value },
new DebugUI.BoolField { displayName = "Enable Atmospheric Scattering", getter = () => frameSettings.enableAtmosphericScattering, setter = value => frameSettings.enableAtmosphericScattering = value },
new DebugUI.BoolField { displayName = "Enable Rough Refraction", getter = () => frameSettings.enableRoughRefraction, setter = value => frameSettings.enableRoughRefraction = value },
new DebugUI.BoolField { displayName = "Enable Transparent Postpass", getter = () => frameSettings.enableTransparentPostpass, setter = value => frameSettings.enableTransparentPostpass = value },
new DebugUI.BoolField { displayName = "Enable Distortion", getter = () => frameSettings.enableDistortion, setter = value => frameSettings.enableDistortion = value },
new DebugUI.BoolField { displayName = "Enable Postprocess", getter = () => frameSettings.enablePostprocess, setter = value => frameSettings.enablePostprocess = value },
new DebugUI.BoolField { displayName = "Enable Stereo Rendering", getter = () => frameSettings.enableStereo, setter = value => frameSettings.enableStereo = value },
new DebugUI.BoolField { displayName = "Enable Async Compute", getter = () => frameSettings.enableAsyncCompute, setter = value => frameSettings.enableAsyncCompute = value },
new DebugUI.BoolField { displayName = "Enable Opaque Objects", getter = () => frameSettings.enableOpaqueObjects, setter = value => frameSettings.enableOpaqueObjects = value },
new DebugUI.BoolField { displayName = "Enable Transparent Objects", getter = () => frameSettings.enableTransparentObjects, setter = value => frameSettings.enableTransparentObjects = value },
new DebugUI.Container
{
displayName = "Rendering Passes",
children =
{
new DebugUI.BoolField { displayName = "Enable Transparent Prepass", getter = () => frameSettings.enableTransparentPrepass, setter = value => frameSettings.enableTransparentPrepass = value },
new DebugUI.BoolField { displayName = "Enable Transparent Postpass", getter = () => frameSettings.enableTransparentPostpass, setter = value => frameSettings.enableTransparentPostpass = value },
new DebugUI.BoolField { displayName = "Enable Motion Vectors", getter = () => frameSettings.enableMotionVectors, setter = value => frameSettings.enableMotionVectors = value },
new DebugUI.BoolField { displayName = "Enable Object Motion Vectors", getter = () => frameSettings.enableObjectMotionVectors, setter = value => frameSettings.enableObjectMotionVectors = value },
new DebugUI.BoolField { displayName = "Enable DBuffer", getter = () => frameSettings.enableDBuffer, setter = value => frameSettings.enableDBuffer = value },
new DebugUI.BoolField { displayName = "Enable Atmospheric Scattering", getter = () => frameSettings.enableAtmosphericScattering, setter = value => frameSettings.enableAtmosphericScattering = value },
new DebugUI.BoolField { displayName = "Enable Rough Refraction", getter = () => frameSettings.enableRoughRefraction, setter = value => frameSettings.enableRoughRefraction = value },
new DebugUI.BoolField { displayName = "Enable Distortion", getter = () => frameSettings.enableDistortion, setter = value => frameSettings.enableDistortion = value },
new DebugUI.BoolField { displayName = "Enable Postprocess", getter = () => frameSettings.enablePostprocess, setter = value => frameSettings.enablePostprocess = value },
}
},
new DebugUI.Container
{
displayName = "Rendering Settings",
children =
{
new DebugUI.BoolField { displayName = "Forward Only", getter = () => frameSettings.enableForwardRenderingOnly, setter = value => frameSettings.enableForwardRenderingOnly = value },
new DebugUI.BoolField { displayName = "Deferred Depth Prepass", getter = () => frameSettings.enableDepthPrepassWithDeferredRendering, setter = value => frameSettings.enableDepthPrepassWithDeferredRendering = value },
new DebugUI.BoolField { displayName = "Enable Async Compute", getter = () => frameSettings.enableAsyncCompute, setter = value => frameSettings.enableAsyncCompute = value },
new DebugUI.BoolField { displayName = "Enable Opaque Objects", getter = () => frameSettings.enableOpaqueObjects, setter = value => frameSettings.enableOpaqueObjects = value },
new DebugUI.BoolField { displayName = "Enable Transparent Objects", getter = () => frameSettings.enableTransparentObjects, setter = value => frameSettings.enableTransparentObjects = value },
new DebugUI.BoolField { displayName = "Enable MSAA", getter = () => frameSettings.enableMSAA, setter = value => frameSettings.enableMSAA = value },
}
},
new DebugUI.Container
{
displayName = "XR Settings",
children =
{
new DebugUI.BoolField { displayName = "Enable Stereo Rendering", getter = () => frameSettings.enableStereo, setter = value => frameSettings.enableStereo = value }
}
},
new DebugUI.Container
{
displayName = "Lighting Settings",
children =
{
new DebugUI.BoolField { displayName = "Enable SSR", getter = () => frameSettings.enableSSR, setter = value => frameSettings.enableSSR = value },
new DebugUI.BoolField { displayName = "Enable SSAO", getter = () => frameSettings.enableSSAO, setter = value => frameSettings.enableSSAO = value },
new DebugUI.BoolField { displayName = "Enable SubsurfaceScattering", getter = () => frameSettings.enableSubsurfaceScattering, setter = value => frameSettings.enableSubsurfaceScattering = value },
new DebugUI.BoolField { displayName = "Enable Transmission", getter = () => frameSettings.enableTransmission, setter = value => frameSettings.enableTransmission = value },
new DebugUI.BoolField { displayName = "Enable Shadows", getter = () => frameSettings.enableShadow, setter = value => frameSettings.enableShadow = value },
new DebugUI.BoolField { displayName = "Enable Contact Shadows", getter = () => frameSettings.enableContactShadows, setter = value => frameSettings.enableContactShadows = value },
new DebugUI.BoolField { displayName = "Enable ShadowMask", getter = () => frameSettings.enableShadowMask, setter = value => frameSettings.enableShadowMask = value },
}
}
});
new DebugUI.BoolField { displayName = "Enable MSAA", getter = () => frameSettings.enableMSAA, setter = value => frameSettings.enableMSAA = value },
new DebugUI.BoolField { displayName = "Enable ShadowMask", getter = () => frameSettings.enableShadowMask, setter = value => frameSettings.enableShadowMask = value },
};
LightLoopSettings.RegisterDebug(frameSettings.lightLoopSettings, widgets);
panel.children.Add(s_DebugEntries);
LightLoopSettings.RegisterDebug(menuName, frameSettings.lightLoopSettings);
}
panel.children.Add(widgets.ToArray());
}
var panel = DebugManager.instance.GetPanel(menuName);
if (panel != null)
panel.children.Remove(s_DebugEntries);
LightLoopSettings.UnRegisterDebug(menuName);
DebugManager.instance.RemovePanel(menuName);
}
}
}

13
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/DefaultHDMaterial.mat


m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _IridescenceMaskMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _IridescenceThicknessMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}

- _IOR: 1.097
- _InitialBend: 1
- _InvTilingScale: 1
- _Ior: 1
- _IridescenceMask: 1
- _IridescenceThickness: 1
- _LinkDetailsWithBase: 1
- _MaterialID: 1
- _Metallic: 0

- _UVEmissive: 0
- _UVSec: 0
- _ZTestDepthEqualForOpaque: 3
- _ZTestGBuffer: 4
- _ZTestMode: 8
- _ZTestModeDistortion: 8
- _ZWrite: 1

- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _InvPrimScale: {r: 1, g: 1, b: 0, a: 0}
- _IridescenceThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
- _SpecularColor: {r: 1, g: 1, b: 1, a: 1}
- _ThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
- _TransmittanceColor: {r: 1, g: 1, b: 1, a: 1}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset


GGXConvolve: {fileID: 4800000, guid: 123ed592ad5c2494b8aed301fd609e7b, type: 3}
opaqueAtmosphericScattering: {fileID: 4800000, guid: 326059e48e5735e46a98047eff4f0295,
type: 3}
hdriSky: {fileID: 4800000, guid: 9bd32a6ece529fd4f9408b8d7e00c10d, type: 3}
proceduralSky: {fileID: 4800000, guid: ec63f47fd265df243a7b1d40f9ef7fe7, type: 3}
skyboxCubemap: {fileID: 103, guid: 0000000000000000f000000000000000, type: 0}
encodeBC6HCS: {fileID: 7200000, guid: aa922d239de60304f964e24488559eeb, type: 3}
cubeToPanoShader: {fileID: 4800000, guid: 595434cc3b6405246b6cd3086d0b6f7d, type: 3}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/RenderPipelineResources.cs


public ComputeShader computeGgxIblSampleData;
public Shader GGXConvolve;
public Shader opaqueAtmosphericScattering;
public Shader hdriSky;
public Shader proceduralSky;
public Shader skyboxCubemap;

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassForward.hlsl


// We need to skip lighting when doing debug pass because the debug pass is done before lighting so some buffers may not be properly initialized potentially causing crashes on PS4.
#ifdef DEBUG_DISPLAY
// Init in debug display mode to quiet warning
#ifdef OUTPUT_SPLIT_LIGHTING
outDiffuseLighting = 0;
ENCODE_INTO_SSSBUFFER(surfaceData, posInput.positionSS, outSSSBuffer);
#endif
if (_DebugLightingMode != DEBUGLIGHTINGMODE_NONE || _DebugMipMapMode != DEBUGMIPMAPMODE_NONE)
#endif
{

float3 diffuseLighting;
float3 specularLighting;
BakeLightingData bakeLightingData;
bakeLightingData.bakeDiffuseLighting = GetBakedDiffuseLigthing(surfaceData, builtinData, bsdfData, preLightData);
bakeLightingData.bakeDiffuseLighting = GetBakedDiffuseLighting(surfaceData, builtinData, bsdfData, preLightData);
#ifdef SHADOWS_SHADOWMASK
bakeLightingData.bakeShadowMask = float4(builtinData.shadowMask0, builtinData.shadowMask1, builtinData.shadowMask2, builtinData.shadowMask3);
#endif

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


PreLightData preLightData = GetPreLightData(V, posInput, bsdfData);
float3 bakeDiffuseLighting = GetBakedDiffuseLigthing(surfaceData, builtinData, bsdfData, preLightData);
float3 bakeDiffuseLighting = GetBakedDiffuseLighting(surfaceData, builtinData, bsdfData, preLightData);
ENCODE_INTO_GBUFFER(surfaceData, bakeDiffuseLighting, posInput.positionSS, outGBuffer);
ENCODE_SHADOWMASK_INTO_GBUFFER(float4(builtinData.shadowMask0, builtinData.shadowMask1, builtinData.shadowMask2, builtinData.shadowMask3), outShadowMaskBuffer);

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISky.cs


public class HDRISky : SkySettings
{
[Tooltip("Cubemap used to render the sky.")]
public CubemapParameter skyHDRI = new CubemapParameter(null);
public CubemapParameter hdriSky = new CubemapParameter(null);
public override SkyRenderer CreateRenderer()
{

unchecked
{
hash = skyHDRI.value != null ? hash * 23 + skyHDRI.GetHashCode() : hash;
hash = hdriSky.value != null ? hash * 23 + hdriSky.GetHashCode() : hash;
}
return hash;

7
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISkyRenderer.cs


using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class HDRISkyRenderer : SkyRenderer

public override void Build()
{
m_SkyHDRIMaterial = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/Sky/SkyHDRI");
var hdrp = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;
m_SkyHDRIMaterial = CoreUtils.CreateEngineMaterial(hdrp.renderPipelineResources.hdriSky);
}
public override void Cleanup()

public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap)
{
m_SkyHDRIMaterial.SetTexture(HDShaderIDs._Cubemap, m_HdriSkyParams.skyHDRI);
m_SkyHDRIMaterial.SetTexture(HDShaderIDs._Cubemap, m_HdriSkyParams.hdriSky);
m_SkyHDRIMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_HdriSkyParams.exposure, m_HdriSkyParams.multiplier, -m_HdriSkyParams.rotation, 0.0f)); // -rotation to match Legacy...
// This matrix needs to be updated at the draw call frequency.

29
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/ProceduralSky/ProceduralSkyRenderer.cs


using UnityEngine.Rendering;
Material m_SkyProceduralMaterial;
Material m_ProceduralSkyMaterial;
MaterialPropertyBlock m_PropertyBlock;
ProceduralSky m_ProceduralSkyParams;

public override void Build()
{
m_SkyProceduralMaterial = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/Sky/SkyProcedural");
var hdrp = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;
m_ProceduralSkyMaterial = CoreUtils.CreateEngineMaterial(hdrp.renderPipelineResources.proceduralSky);
CoreUtils.Destroy(m_SkyProceduralMaterial);
CoreUtils.Destroy(m_ProceduralSkyMaterial);
}
public override void SetRenderTargets(BuiltinSkyParameters builtinParams)

public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap)
{
CoreUtils.SetKeyword(m_SkyProceduralMaterial, "_ENABLE_SUN_DISK", m_ProceduralSkyParams.enableSunDisk);
CoreUtils.SetKeyword(m_ProceduralSkyMaterial, "_ENABLE_SUN_DISK", m_ProceduralSkyParams.enableSunDisk);
Color sunColor = Color.white;
Vector3 sunDirection = Vector3.zero;

sunDirection = -builtinParams.sunLight.transform.forward;
}
m_SkyProceduralMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_ProceduralSkyParams.exposure, m_ProceduralSkyParams.multiplier, 0.0f, 0.0f));
m_SkyProceduralMaterial.SetFloat(_SunSizeParam, m_ProceduralSkyParams.sunSize);
m_SkyProceduralMaterial.SetFloat(_SunSizeConvergenceParam, m_ProceduralSkyParams.sunSizeConvergence);
m_SkyProceduralMaterial.SetFloat(_AtmoshpereThicknessParam, m_ProceduralSkyParams.atmosphereThickness);
m_SkyProceduralMaterial.SetColor(_SkyTintParam, m_ProceduralSkyParams.skyTint);
m_SkyProceduralMaterial.SetColor(_GroundColorParam, m_ProceduralSkyParams.groundColor);
m_SkyProceduralMaterial.SetColor(_SunColorParam, sunColor);
m_SkyProceduralMaterial.SetVector(_SunDirectionParam, sunDirection);
m_ProceduralSkyMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_ProceduralSkyParams.exposure, m_ProceduralSkyParams.multiplier, 0.0f, 0.0f));
m_ProceduralSkyMaterial.SetFloat(_SunSizeParam, m_ProceduralSkyParams.sunSize);
m_ProceduralSkyMaterial.SetFloat(_SunSizeConvergenceParam, m_ProceduralSkyParams.sunSizeConvergence);
m_ProceduralSkyMaterial.SetFloat(_AtmoshpereThicknessParam, m_ProceduralSkyParams.atmosphereThickness);
m_ProceduralSkyMaterial.SetColor(_SkyTintParam, m_ProceduralSkyParams.skyTint);
m_ProceduralSkyMaterial.SetColor(_GroundColorParam, m_ProceduralSkyParams.groundColor);
m_ProceduralSkyMaterial.SetColor(_SunColorParam, sunColor);
m_ProceduralSkyMaterial.SetVector(_SunDirectionParam, sunDirection);
CoreUtils.DrawFullScreen(builtinParams.commandBuffer, m_SkyProceduralMaterial, m_PropertyBlock, renderForCubemap ? 0 : 1);
CoreUtils.DrawFullScreen(builtinParams.commandBuffer, m_ProceduralSkyMaterial, m_PropertyBlock, renderForCubemap ? 0 : 1);
}
public override bool IsValid()

7
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyManager.cs


SkyResolution256 = 256,
SkyResolution512 = 512,
SkyResolution1024 = 1024,
// TODO: Anything above 1024 cause a crash in Unity...
//SkyResolution2048 = 2048,
//SkyResolution4096 = 4096
SkyResolution2048 = 2048,
SkyResolution4096 = 4096
}
public enum EnvironementUpdateMode

public void Cleanup()
{
CoreUtils.Destroy(m_StandardSkyboxMaterial);
CoreUtils.Destroy(m_BlitCubemapMaterial);
CoreUtils.Destroy(m_OpaqueAtmScatteringMaterial);
m_BakingSky.Cleanup();
m_VisualSky.Cleanup();

29
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyRenderingContext.cs


}
}
// We do our own hash here because Unity does not provide correct hash for builtin types
// Moreover, we don't want to test every single parameters of the light so we filter them here in this specific function.
int GetSunLightHashCode(Light light)
{
HDAdditionalLightData ald = light.GetComponent<HDAdditionalLightData>();
unchecked
{
int hash = 13;
hash = hash * 23 + (light.GetHashCode() * 23 + light.transform.position.GetHashCode()) * 23 + light.transform.rotation.GetHashCode();
hash = hash * 23 + light.color.GetHashCode();
hash = hash * 23 + light.colorTemperature.GetHashCode();
hash = hash * 23 + light.intensity.GetHashCode();
hash = hash * 23 + light.range.GetHashCode();
if (light.cookie != null)
{
hash = hash * 23 + (int)light.cookie.updateCount;
hash = hash * 23 + (int)light.cookie.GetInstanceID();
}
if (ald != null)
{
hash = hash * 23 + ald.lightDimmer.GetHashCode();
}
return hash;
}
}
public bool UpdateEnvironment(SkyUpdateContext skyContext, HDCamera camera, Light sunLight, bool updateRequired, CommandBuffer cmd)
{
bool result = false;

int sunHash = 0;
if (sunLight != null)
sunHash = (sunLight.GetHashCode() * 23 + sunLight.transform.position.GetHashCode()) * 23 + sunLight.transform.rotation.GetHashCode();
sunHash = GetSunLightHashCode(sunLight);
int skyHash = sunHash * 23 + skyContext.skySettings.GetHashCode();
bool forceUpdate = (updateRequired || skyContext.updatedFramesRequired > 0 || m_NeedUpdate);

2
ScriptableRenderPipeline/HDRenderPipeline/package.json


"version": "0.1.33",
"unity": "2018.1",
"dependencies": {
"com.unity.postprocessing": "0.2.0",
"com.unity.postprocessing": "2.0.2-preview",
"com.unity.render-pipelines.core": "0.1.33"
}
}

33
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/LightweightAssetEditor.cs


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

EditorGUILayout.PropertyField(prop, content);
}
protected void DoPopup(GUIContent label, SerializedProperty property, string[] options)
{
var mode = property.intValue;
EditorGUI.BeginChangeCheck();
if (mode >= options.Length)
Debug.LogError(string.Format("Invalid option while trying to set {0}", label.text));
mode = EditorGUILayout.Popup(label, mode, options);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(property.objectReferenceValue, property.name);
property.intValue = mode;
}
}
public override void OnInspectorGUI()
{
serializedObject.Update();

EditorGUILayout.LabelField(Styles.shadowLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
DoPopup(Styles.shadowType, m_ShadowTypeProp, Styles.shadowTypeOptions);
CoreEditorUtils.DrawPopup(Styles.shadowType, m_ShadowTypeProp, Styles.shadowTypeOptions);
EditorGUILayout.PropertyField(m_ShadowDistanceProp, Styles.shadowDistante);
DoPopup(Styles.shadowCascades, m_ShadowCascadesProp, Styles.shadowCascadeOptions);
m_ShadowDistanceProp.floatValue = Mathf.Max(0.0f, EditorGUILayout.FloatField(Styles.shadowDistante, m_ShadowDistanceProp.floatValue));
CoreEditorUtils.DrawPopup(Styles.shadowCascades, m_ShadowCascadesProp, Styles.shadowCascadeOptions);
{
EditorGUILayout.PropertyField(m_ShadowCascade4SplitProp, Styles.shadowCascadeSplit);
}
CoreEditorUtils.DrawCascadeSplitGUI<Vector3>(ref m_ShadowCascade4SplitProp);
{
EditorGUILayout.PropertyField(m_ShadowCascade2SplitProp, Styles.shadowCascadeSplit);
}
CoreEditorUtils.DrawCascadeSplitGUI<float>(ref m_ShadowCascade2SplitProp);
EditorGUI.indentLevel--;

23
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGraph/lightweightPBRForwardPass.template


HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 3.0
#pragma target 2.0
// -------------------------------------
// Lightweight Pipeline keywords

struct GraphVertexOutput
{
float4 clipPos : SV_POSITION;
float4 lightmapUVOrVertexSH : TEXCOORD0;
DECLARE_LIGHTMAP_OR_SH(lightmapUV, vertexSH, 0);
half4 fogFactorAndVertexLight : TEXCOORD1; // x: fogFactor, yzw: vertex light
float4 shadowCoord : TEXCOORD2;
${Interpolators}

float3 lwWorldPos = TransformObjectToWorld(v.vertex.xyz);
float4 clipPos = TransformWorldToHClip(lwWorldPos);
// We either sample GI from lightmap or SH. lightmap UV and vertex SH coefficients
// are packed in lightmapUVOrVertexSH to save interpolator.
// The following funcions initialize
OUTPUT_LIGHTMAP_UV(v.texcoord1, unity_LightmapST, o.lightmapUVOrVertexSH);
OUTPUT_SH(lwWNormal, o.lightmapUVOrVertexSH);
// We either sample GI from lightmap or SH.
// Lightmap UV and vertex SH coefficients use the same interpolator ("float2 lightmapUV" for lightmap or "half3 vertexSH" for SH)
// see DECLARE_LIGHTMAP_OR_SH macro.
// The following funcions initialize the correct variable with correct data
OUTPUT_LIGHTMAP_UV(v.texcoord1, unity_LightmapST, o.lightmapUV);
OUTPUT_SH(lwWNormal, o.vertexSH);
half3 vertexLight = VertexLighting(lwWorldPos, lwWNormal);
half fogFactor = ComputeFogFactor(clipPos.z);

#ifdef _NORMALMAP
inputData.normalWS = TangentToWorldNormal(Normal, WorldSpaceTangent, WorldSpaceBiTangent, WorldSpaceNormal);
#else
#if !SHADER_HINT_NICE_QUALITY
inputData.normalWS = WorldSpaceNormal;
#else
#endif
#ifdef SHADER_API_MOBILE
#if !SHADER_HINT_NICE_QUALITY
// viewDirection should be normalized here, but we avoid doing it as it's close enough and we save some ALU.
inputData.viewDirectionWS = WorldSpaceViewDirection;
#else

inputData.fogCoord = IN.fogFactorAndVertexLight.x;
inputData.vertexLighting = IN.fogFactorAndVertexLight.yzw;
inputData.bakedGI = SampleGI(IN.lightmapUVOrVertexSH, inputData.normalWS);
inputData.bakedGI = SAMPLE_GI(IN.lightmapUV, IN.vertexSH, inputData.normalWS);
half4 color = LightweightFragmentPBR(
inputData,

55
ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs


using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
#if UNITY_EDITOR
using UnityEditor.Experimental.Rendering.LightweightPipeline;
#endif
using UnityEngine.Experimental.GlobalIllumination;
using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;

public class ShadowSettings
{
public bool enabled;
public bool screenSpace;
public int shadowAtlasWidth;
public int shadowAtlasHeight;

{
defaultShadowSettings = new ShadowSettings();
defaultShadowSettings.enabled = true;
defaultShadowSettings.screenSpace = true;
defaultShadowSettings.shadowAtlasHeight = defaultShadowSettings.shadowAtlasWidth = 4096;
defaultShadowSettings.directionalLightCascadeCount = 1;
defaultShadowSettings.directionalLightCascades = new Vector3(0.05F, 0.2F, 0.3F);

private MixedLightingSetup m_MixedLightingSetup;
private const int kDepthStencilBufferBits = 32;
private const int kShadowBufferBits = 16;
private Vector4[] m_DirectionalShadowSplitDistances = new Vector4[kMaxCascades];
private Vector4 m_DirectionalShadowSplitRadii;

CoreUtils.Destroy(m_ErrorMaterial);
CoreUtils.Destroy(m_CopyDepthMaterial);
CoreUtils.Destroy(m_BlitMaterial);
#if UNITY_EDITOR
SceneViewDrawMode.ResetDrawMode();
#endif
}
private void SetRenderingFeatures()

rendererSupportsReceiveShadows = true,
rendererSupportsReflectionProbes = true
};
SceneViewDrawMode.SetupDrawMode();
#endif
}

ScriptableCullingParameters cullingParameters;
if (!CullResults.GetCullingParameters(m_CurrCamera, stereoEnabled, out cullingParameters))
{
cmd.EndSample("LightweightPipeline.Render");
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
cullingParameters.shadowDistance = Mathf.Min(m_ShadowSettings.maxShadowDistance,
m_CurrCamera.farClipPlane);

context.SetupCameraProperties(m_CurrCamera, stereoEnabled);
if (LightweightUtils.HasFlag(frameRenderingConfiguration, FrameRenderingConfiguration.DepthPrePass))
{
// Only screen space shadowmap mode is supported.
if (shadows)
ShadowCollectPass(visibleLights, ref context, ref lightData, frameRenderingConfiguration);
}
if (shadows && m_ShadowSettings.screenSpace)
ShadowCollectPass(visibleLights, ref context, ref lightData, frameRenderingConfiguration);
setRT.GetTemporaryRT(m_ScreenSpaceShadowMapRTID, 4, 4, 0, FilterMode.Bilinear, RenderTextureFormat.R8);
int shadowmapID = m_ShadowSettings.screenSpace ? m_ScreenSpaceShadowMapRTID : m_ShadowMapRTID;
setRT.GetTemporaryRT(shadowmapID, 4, 4, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32);
setRT.Blit(Texture2D.whiteTexture, m_ScreenSpaceShadowMapRT);
context.ExecuteCommandBuffer(setRT);
}

bool shadowsRendered = RenderShadows(ref m_CullResults, ref mainLight, shadowOriginalIndex, ref context);
if (shadowsRendered)
{
lightData.shadowMapSampleType = (m_Asset.ShadowSetting != ShadowType.SOFT_SHADOWS)
? LightShadows.Hard
: mainLight.light.shadows;
lightData.shadowMapSampleType = (m_Asset.ShadowSetting != ShadowType.SOFT_SHADOWS) ? LightShadows.Hard : mainLight.light.shadows;
// In order to avoid shader variants explosion we only do hard shadows when sampling shadowmap in the lit pass.
// GLES2 platform is forced to hard single cascade shadows.
if (!m_ShadowSettings.screenSpace)
lightData.shadowMapSampleType = LightShadows.Hard;
}
else
{

{
CommandBuffer cmd = CommandBufferPool.Get("Collect Shadows");
SetupShadowReceiverConstants(cmd, visibleLights[lightData.mainLightIndex]);
// TODO: Support RenderScale for the SSSM target. Should probably move allocation elsewhere, or at
// least propogate RenderTextureDescriptor generation

private void BuildShadowSettings()
{
m_ShadowSettings = ShadowSettings.Default;
m_ShadowSettings.directionalLightCascadeCount = m_Asset.CascadeCount;
m_ShadowSettings.screenSpace = SystemInfo.graphicsDeviceType != GraphicsDeviceType.OpenGLES2;
m_ShadowSettings.directionalLightCascadeCount = (m_ShadowSettings.screenSpace) ? m_Asset.CascadeCount : 1;
m_ShadowSettings.shadowAtlasWidth = m_Asset.ShadowAtlasResolution;
m_ShadowSettings.shadowAtlasHeight = m_Asset.ShadowAtlasResolution;

if (shadows)
{
m_RequireDepthTexture = true;
m_RequireDepthTexture = m_ShadowSettings.screenSpace;
if (!msaaEnabled)
intermediateTexture = true;

msaaSamples = (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Msaa)) ? msaaSamples : 1;
m_CurrCameraColorRT = BuiltinRenderTextureType.CameraTarget;
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture))
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture) || m_RequireDepthTexture)
SetupIntermediateRenderTextures(cmd, renderingConfig, msaaSamples);
context.ExecuteCommandBuffer(cmd);

cmd.SetGlobalVector("_LightDirection", new Vector4(lightDirection.x, lightDirection.y, lightDirection.z, 0.0f));
}
private void SetupShadowReceiverConstants(CommandBuffer cmd, VisibleLight shadowLight)
private void SetupShadowReceiverConstants(CommandBuffer cmd, VisibleLight shadowLight, ref ScriptableRenderContext context)
{
Light light = shadowLight.light;

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

cmd.SetGlobalVector(ShadowConstantBuffer._ShadowOffset2, new Vector4(-invHalfShadowResolution, invHalfShadowResolution, 0.0f, 0.0f));
cmd.SetGlobalVector(ShadowConstantBuffer._ShadowOffset3, new Vector4(invHalfShadowResolution, invHalfShadowResolution, 0.0f, 0.0f));
cmd.SetGlobalVector(ShadowConstantBuffer._ShadowmapSize, new Vector4(invShadowResolution, invShadowResolution, m_Asset.ShadowAtlasResolution, m_Asset.ShadowAtlasResolution));
context.ExecuteCommandBuffer(cmd);
}
private void SetShaderKeywords(CommandBuffer cmd, ref LightData lightData, List<VisibleLight> visibleLights)

CoreUtils.SetKeyword(cmd, "_MIXED_LIGHTING_SUBTRACTIVE", m_MixedLightingSetup == MixedLightingSetup.Subtractive);
CoreUtils.SetKeyword(cmd, "_VERTEX_LIGHTS", vertexLightsCount > 0);
CoreUtils.SetKeyword(cmd, "SOFTPARTICLES_ON", m_RequireDepthTexture && m_Asset.RequireSoftParticles);
bool linearFogModeEnabled = false;
bool exponentialFogModeEnabled = false;
if (RenderSettings.fog)

var cmd = CommandBufferPool.Get("Prepare Shadowmap");
cmd.GetTemporaryRT(m_ShadowMapRTID, m_ShadowSettings.shadowAtlasWidth,
m_ShadowSettings.shadowAtlasHeight, kDepthStencilBufferBits, FilterMode.Bilinear, m_ShadowSettings.renderTextureFormat);
m_ShadowSettings.shadowAtlasHeight, kShadowBufferBits, FilterMode.Bilinear, m_ShadowSettings.renderTextureFormat);
// LightweightPipeline.SetRenderTarget is meant to be used with camera targets, not shadowmaps
CoreUtils.SetRenderTarget(cmd, m_ShadowMapRT, ClearFlag.Depth, CoreUtils.ConvertSRGBToActiveColorSpace(m_CurrCamera.backgroundColor));

{
Debug.LogWarning("Only spot and directional shadow casters are supported in lightweight pipeline");
}
if (success)
SetupShadowReceiverConstants(cmd, shadowLight, ref context);
CommandBufferPool.Release(cmd);
return success;

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


#include "CoreRP/ShaderLibrary/Packing.hlsl"
#include "Input.hlsl"
#if !defined(SHADER_HINT_NICE_QUALITY)
#ifdef SHADER_API_MOBILE
#define SHADER_HINT_NICE_QUALITY 0
#else
#define SHADER_HINT_NICE_QUALITY 1
#endif
#endif
#define OUTPUT_NORMAL(IN, OUT) OutputTangentToWorld(IN.tangent, IN.normal, OUT.tangent, OUT.binormal, OUT.normal)
#define OUTPUT_NORMAL(IN, OUT) OutputTangentToWorld(IN.tangent, IN.normal, OUT.tangent.xyz, OUT.binormal.xyz, OUT.normal.xyz)
#else
#define OUTPUT_NORMAL(IN, OUT) OUT.normal = TransformObjectToWorldNormal(IN.normal)
#endif

#define UNITY_Z_0_FAR_FROM_CLIPSPACE(coord) (coord)
#endif
void AlphaDiscard(half alpha, half cutoff)
void AlphaDiscard(half alpha, half cutoff, half offset = 0.0h)
clip(alpha - cutoff);
clip(alpha - cutoff + offset);
// Compiler will optimize the scale away
return UnpackNormalRGB(packedNormal, 1.0);
return UnpackNormalRGBNoScale(packedNormal);
// Compiler will optimize the scale away
return UnpackNormalmapRGorAG(packedNormal, 1.0);
#endif
}

binormalWS = cross(normalWS, tangentWS) * sign;
}
half3 FragmentNormalWS(half3 normal)
{
#if !SHADER_HINT_NICE_QUALITY
// World normal is already normalized in vertex. Small acceptable error to save ALU.
return normal;
#else
return normalize(normal);
#endif
}
half3 FragmentViewDirWS(half3 viewDir)
{
#if !SHADER_HINT_NICE_QUALITY
// View direction is already normalized in vertex. Small acceptable error to save ALU.
return viewDir;
#else
return SafeNormalize(viewDir);
#endif
}
half3 VertexViewDirWS(half3 viewDir)
{
#if !SHADER_HINT_NICE_QUALITY
// Normalize in vertex and avoid renormalizing it in frag to save ALU.
return SafeNormalize(viewDir);
#else
return viewDir;
#endif
}
return normalize(mul(normalTangent, tangentToWorld));
return FragmentNormalWS(mul(normalTangent, tangentToWorld));
}
// TODO: A similar function should be already available in SRP lib on master. Use that instead

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


// HDR environment map decode instructions
half4 unity_SpecCube0_HDR;
// HDR lightmap decode instructions
half4 unity_Lightmap_HDR;
// These are set internally by the engine upon request by RendererConfiguration.
// Check GetRendererSettings in LightweightPipeline.cs
half4 unity_LightIndicesOffsetAndCount;

40
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputSurface.hlsl


half3 Normal(float2 uv)
{
#if _NORMALMAP
return UnpackNormalScale(SAMPLE_TEXTURE2D(_BumpMap, sampler_BumpMap, uv), _BumpScale);
#if BUMP_SCALE_NOT_SUPPORTED
return UnpackNormal(SAMPLE_TEXTURE2D(_BumpMap, sampler_BumpMap, uv));
#else
return UnpackNormalScale(SAMPLE_TEXTURE2D(_BumpMap, sampler_BumpMap, uv), _BumpScale);
#endif
#else
return half3(0.0h, 0.0h, 1.0h);
#endif

half4 specularGloss = half4(0, 0, 0, 1);
#ifdef _SPECGLOSSMAP
specularGloss = SAMPLE_TEXTURE2D(_SpecGlossMap, sampler_SpecGlossMap, uv);
specularGloss.rgb = specularGloss.rgb;
#elif defined(_SPECULAR_COLOR)
specularGloss = _SpecColor;
#endif

half4 specGloss;
#ifdef _METALLICSPECGLOSSMAP
specGloss = specGloss = SAMPLE_METALLICSPECULAR(uv);
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
specGloss.a = albedoAlpha * _GlossMapScale;
#else
specGloss.a *= _GlossMapScale;
#endif
specGloss = SAMPLE_METALLICSPECULAR(uv);
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
specGloss.a = albedoAlpha * _GlossMapScale;
#else
specGloss.a *= _GlossMapScale;
#endif
#if _SPECULAR_SETUP
specGloss.rgb = _SpecColor.rgb;
#else
specGloss.rgb = _Metallic.rrr;
#endif
#if _SPECULAR_SETUP
specGloss.rgb = _SpecColor.rgb;
#else
specGloss.rgb = _Metallic.rrr;
#endif
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
specGloss.a = albedoAlpha * _GlossMapScale;
#else
specGloss.a = _Glossiness;
#endif
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
specGloss.a = albedoAlpha * _GlossMapScale;
#else
specGloss.a = _Glossiness;
#endif
#endif
return specGloss;

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


// If lightmap is not defined than we evaluate GI (ambient + probes) from SH
// We might do it fully or partially in vertex to save shader ALU
#if !defined(LIGHTMAP_ON)
#ifdef SHADER_API_GLES
#if defined(SHADER_API_GLES) || (SHADER_TARGET < 30) || !defined(_NORMALMAP)
#else
#elif !SHADER_HINT_NICE_QUALITY
// Otherwise evaluate SH fully per-pixel
#define DECLARE_LIGHTMAP_OR_SH(lmName, shName, index) float2 lmName : TEXCOORD##index
#define DECLARE_LIGHTMAP_OR_SH(lmName, shName, index) half3 shName : TEXCOORD##index
#define OUTPUT_LIGHTMAP_UV(lightmapUV, lightmapScaleOffset, OUT)
#define OUTPUT_SH(normalWS, OUT) OUT.xyz = SampleSHVertex(normalWS)
#endif

half4 GetMainLightDirectionAndAttenuation(LightInput lightInput, float3 positionWS)
{
half4 directionAndAttenuation = lerp(half4(lightInput.position.xyz, 1.0), GetLightDirectionAndAttenuation(lightInput, positionWS), lightInput.position.w);
half4 directionAndAttenuation = GetLightDirectionAndAttenuation(lightInput, positionWS);
// Cookies are only computed for main light
directionAndAttenuation.w *= CookieAttenuation(positionWS);

// mixed or fully in pixel. See SampleSHVertex
half3 SampleSHPixel(half3 L2Term, half3 normalWS)
{
#ifdef EVALUATE_SH_MIXED
#if defined(EVALUATE_SH_VERTEX)
return L2Term;
#elif defined(EVALUATE_SH_MIXED)
half3 L0L1Term = SHEvalLinearL0L1(normalWS, unity_SHAr, unity_SHAg, unity_SHAb);
return max(half3(0, 0, 0), L2Term + L0L1Term);
#endif

#ifdef DIRLIGHTMAP_COMBINED
return SampleDirectionalLightmap(TEXTURE2D_PARAM(unity_Lightmap, samplerunity_Lightmap),
TEXTURE2D_PARAM(unity_LightmapInd, samplerunity_Lightmap),
lightmapUV, transformCoords, normalWS, encodedLightmap);
lightmapUV, transformCoords, normalWS, encodedLightmap, unity_Lightmap_HDR);
return SampleSingleLightmap(TEXTURE2D_PARAM(unity_Lightmap, samplerunity_Lightmap), lightmapUV, transformCoords, encodedLightmap);
return SampleSingleLightmap(TEXTURE2D_PARAM(unity_Lightmap, samplerunity_Lightmap), lightmapUV, transformCoords, encodedLightmap, unity_Lightmap_HDR);
#endif
}

half3 SampleGI(float4 sampleData, half3 normalWS)
#ifdef LIGHTMAP_ON
#define SAMPLE_GI(lmName, shName, normalWSName) SampleGI(lmName, normalWSName)
half3 SampleGI(float2 sampleData, half3 normalWS)
{
return SampleLightmap(sampleData, normalWS);
}
#else
#define SAMPLE_GI(lmName, shName, normalWSName) SampleGI(shName, normalWSName)
half3 SampleGI(half3 sampleData, half3 normalWS)
#ifdef LIGHTMAP_ON
return SampleLightmap(sampleData.xy, normalWS);
#endif
return SampleSHPixel(sampleData.xyz, normalWS);
return SampleSHPixel(sampleData, normalWS);
#endif
half3 GlossyEnvironmentReflection(half3 reflectVector, half perceptualRoughness, half occlusion)
{

// 1) Gives good estimate of illumination as if light would've been shadowed during the bake.
// Preserves bounce and other baked lights
// No shadows on the geometry facing away from the light
// We only subtract the main direction light. This is accounted in the contribution term below.
half NdotL = saturate(dot(mainLight.direction, normalWS));
half3 lambert = mainLight.color * NdotL;
half contributionTerm = saturate(dot(mainLight.direction, normalWS)) * (1.0 - _MainLightPosition.w);
half3 lambert = mainLight.color * contributionTerm;
half3 estimatedLightContributionMaskedByInverseOfShadow = lambert * (1.0 - mainLight.attenuation);
half3 subtractedLightmap = bakedGI - estimatedLightContributionMaskedByInverseOfShadow;

void MixRealtimeAndBakedGI(inout Light light, half3 normalWS, inout half3 bakedGI, half4 shadowMask)
{
#if defined(_MIXED_LIGHTING_SUBTRACTIVE) && defined(LIGHTMAP_ON) && defined(_SHADOWS_ENABLED)
bakedGI = lerp(SubtractDirectMainLightFromLightmap(light, normalWS, bakedGI), bakedGI, _MainLightPosition.w);
#if defined(_MIXED_LIGHTING_SUBTRACTIVE) && defined(LIGHTMAP_ON)
bakedGI = SubtractDirectMainLightFromLightmap(light, normalWS, bakedGI);
#endif
#if defined(LIGHTMAP_ON)

{
half3 halfVec = SafeNormalize(lightDir + viewDir);
half NdotH = saturate(dot(normal, halfVec));
half3 specularReflection = specularGloss.rgb * pow(NdotH, shininess) * specularGloss.a;
half modifier = pow(NdotH, shininess) * specularGloss.a;
half3 specularReflection = specularGloss.rgb * modifier;
return lightColor * specularReflection;
}

}
#endif
half3 finalColor = diffuseColor * diffuse + emission;
finalColor += inputData.vertexLighting * diffuse;
half3 fullDiffuse = diffuseColor + inputData.vertexLighting;
half3 finalColor = fullDiffuse * diffuse + emission;
#if defined(_SPECGLOSSMAP) || defined(_SPECULAR_COLOR)
finalColor += specularColor;

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


float2 texcoord : TEXCOORD0;
float2 lightmapUV : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
float4 lightmapUVOrVertexSH : TEXCOORD1; // holds either lightmapUV or vertex SH. depending on LIGHTMAP_ON
float3 posWS : TEXCOORD2;
half3 normal : TEXCOORD3;
DECLARE_LIGHTMAP_OR_SH(lightmapUV, vertexSH, 1);
float4 posWSShininess : TEXCOORD2; // xyz: posWS, w: Shininess * 128
half3 tangent : TEXCOORD4;
half3 binormal : TEXCOORD5;
half4 normal : TEXCOORD3; // xyz: normal, w: viewDir.x
half4 tangent : TEXCOORD4; // xyz: tangent, w: viewDir.y
half4 binormal : TEXCOORD5; // xyz: binormal, w: viewDir.z
#else
half3 normal : TEXCOORD3;
half3 viewDir : TEXCOORD4;
half3 viewDir : TEXCOORD6;
half4 fogFactorAndVertexLight : TEXCOORD7; // x: fogFactor, yzw: vertex light
half4 fogFactorAndVertexLight : TEXCOORD6; // x: fogFactor, yzw: vertex light
float4 shadowCoord : TEXCOORD8;
float4 shadowCoord : TEXCOORD7;
float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID

void InitializeInputData(LightweightVertexOutput IN, half3 normalTS, out InputData inputData)
{
inputData.positionWS = IN.posWS.xyz;
inputData.positionWS = IN.posWSShininess.xyz;
inputData.normalWS = TangentToWorldNormal(normalTS, IN.tangent, IN.binormal, IN.normal);
#else
inputData.normalWS = normalize(IN.normal);
#endif
#ifdef SHADER_API_MOBILE
// viewDirection should be normalized here, but we avoid doing it as it's close enough and we save some ALU.
inputData.viewDirectionWS = IN.viewDir;
half3 viewDir = half3(IN.normal.w, IN.tangent.w, IN.binormal.w);
inputData.normalWS = TangentToWorldNormal(normalTS, IN.tangent.xyz, IN.binormal.xyz, IN.normal.xyz);
inputData.viewDirectionWS = normalize(IN.viewDir);
half3 viewDir = IN.viewDir;
inputData.normalWS = FragmentNormalWS(IN.normal);
inputData.viewDirectionWS = FragmentViewDirWS(viewDir);
inputData.bakedGI = SampleGI(IN.lightmapUVOrVertexSH, inputData.normalWS);
inputData.bakedGI = SAMPLE_GI(IN.lightmapUV, IN.vertexSH, inputData.normalWS);
}
///////////////////////////////////////////////////////////////////////////////

o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
o.posWS = TransformObjectToWorld(v.vertex.xyz);
o.clipPos = TransformWorldToHClip(o.posWS);
o.viewDir = SafeNormalize(GetCameraPositionWS() - o.posWS);
o.posWSShininess.xyz = TransformObjectToWorld(v.vertex.xyz);
o.posWSShininess.w = _Shininess * 128.0;
o.clipPos = TransformWorldToHClip(o.posWSShininess.xyz);
half3 viewDir = VertexViewDirWS(GetCameraPositionWS() - o.posWSShininess.xyz);
#ifdef _NORMALMAP
o.normal.w = viewDir.x;
o.tangent.w = viewDir.y;
o.binormal.w = viewDir.z;
#else
o.viewDir = viewDir;
#endif
// We either sample GI from lightmap or SH. lightmap UV and vertex SH coefficients
// are packed in lightmapUVOrVertexSH to save interpolator.
// The following funcions initialize
OUTPUT_LIGHTMAP_UV(v.lightmapUV, unity_LightmapST, o.lightmapUVOrVertexSH);
OUTPUT_SH(o.normal, o.lightmapUVOrVertexSH);
// We either sample GI from lightmap or SH.
// Lightmap UV and vertex SH coefficients use the same interpolator ("float2 lightmapUV" for lightmap or "half3 vertexSH" for SH)
// see DECLARE_LIGHTMAP_OR_SH macro.
// The following funcions initialize the correct variable with correct data
OUTPUT_LIGHTMAP_UV(v.lightmapUV, unity_LightmapST, o.lightmapUV);
OUTPUT_SH(o.normal.xyz, o.vertexSH);
half3 vertexLight = VertexLighting(o.posWS, o.normal);
half3 vertexLight = VertexLighting(o.posWSShininess.xyz, o.normal.xyz);
#if SHADOWS_SCREEN
#else
o.shadowCoord = TransformWorldToShadowCoord(o.posWSShininess.xyz);
#endif
return o;
}

half3 emission = Emission(uv);
half4 specularGloss = SpecularGloss(uv, diffuseAlpha.a);
half shininess = _Shininess * 128.0h;
half shininess = IN.posWSShininess.w;
InputData inputData;
InitializeInputData(IN, normalTS, inputData);

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


// so use it in a very dummy way
vertex.z = vertex.z > 0 ? 1.0e-4f : 0.0f;
}
return TransformObjectToHClip(vertex.xyz);
return TransformWorldToHClip(vertex.xyz); // Need to transfer from world to clip compared to legacy
}
half4 MetaFragment(MetaInput IN)

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


float scale = invNdotL * _ShadowBias.y;
// normal bias is negative since we want to apply an inset normal offset
o.posWS = o.normal * scale.xxx + o.posWS;
float4 clipPos = TransformWorldToHClip(o.posWS);
o.posWSShininess.xyz = o.normal * scale.xxx + o.posWSShininess.xyz;
float4 clipPos = TransformWorldToHClip(o.posWSShininess.xyz);
// _ShadowBias.x sign depens on if platform has reversed z buffer
clipPos.z += _ShadowBias.x;

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


float4 projectedPosition : TEXCOORD5;
#endif
float4 posWS : TEXCOORD6; // xyz: position; w = fogFactor;
half4 viewDirShininess : TEXCOORD7; // xyz: viewDir; w = shininess
float4 clipPos : SV_POSITION;
};

return color;
}
void InitializeSurfaceData(VertexOutputLit IN, out SurfaceData surfaceData)
half3 NormalTS(VertexOutputLit IN)
{
#if defined(_NORMALMAP)
#if BUMP_SCALE_NOT_SUPPORTED
return UnpackNormal(readTexture(_BumpMap, sampler_BumpMap, IN));
#else
return UnpackNormalScale(readTexture(_BumpMap, sampler_BumpMap, IN), _BumpScale);
#endif
#else
return half3(0.0h, 0.0h, 1.0h);
#endif
}
half3 Emission(VertexOutputLit IN)
{
#if defined(_EMISSION)
return readTexture(_EmissionMap, sampler_EmissionMap, IN).rgb * _EmissionColor.rgb;
#else
return half3(0.0h, 0.0h, 0.0h);
#endif
}
half4 Albedo(VertexOutputLit IN)
{
half4 albedo = readTexture(TEXTURE2D_PARAM(_MainTex, sampler_MainTex), IN) * IN.color;

fragCameraFading(IN);
#if defined(_METALLICGLOSSMAP)
half2 metallicGloss = readTexture(_MetallicGlossMap, sampler_MetallicGlossMap, IN).ra * half2(1.0, _Glossiness);
return albedo;
}
half4 SpecularGloss(VertexOutputLit IN, half alpha)
{
half4 specularGloss = half4(0.0h, 0.0h, 0.0h, 1.0h);
#ifdef _SPECGLOSSMAP
specularGloss = readTexture(_SpecGlossMap, sampler_SpecGlossMap, IN);
#elif defined(_SPECULAR_COLOR)
specularGloss = _SpecColor;
#endif
#ifdef _GLOSSINESS_FROM_BASE_ALPHA
specularGloss.a = alpha;
#endif
return specularGloss;
}
half AlphaBlendAndTest(half alpha)
{
#if defined(_ALPHABLEND_ON) || defined(_ALPHAPREMULTIPLY_ON) || defined(_ALPHAOVERLAY_ON)
half result = alpha;
half2 metallicGloss = half2(_Metallic, _Glossiness);
half result = 1.0h;
AlphaDiscard(result, _Cutoff, 0.0001h);
#if defined(_NORMALMAP)
half3 normalTS = normalize(UnpackNormalScale(readTexture(_BumpMap, sampler_BumpMap, IN), _BumpScale));
return result;
}
half3 AlphaModulate(half3 albedo, half alpha)
{
#if defined(_ALPHAMODULATE_ON)
return lerp(half3(1.0h, 1.0h, 1.0h), albedo, alpha);
half3 normalTS = float3(0, 0, 1);
return albedo;
}
#if defined(_EMISSION)
half3 emission = readTexture(_EmissionMap, sampler_EmissionMap, IN).rgb;
void InitializeSurfaceData(VertexOutputLit IN, out SurfaceData surfaceData)
{
half4 albedo = Albedo(IN);
#if defined(_METALLICGLOSSMAP)
half2 metallicGloss = readTexture(_MetallicGlossMap, sampler_MetallicGlossMap, IN).ra * half2(1.0, _Glossiness);
half3 emission = 0;
half2 metallicGloss = half2(_Metallic, _Glossiness);
half3 normalTS = NormalTS(IN);
half3 emission = Emission(IN);
surfaceData.specular = half3(0, 0, 0);
surfaceData.specular = half3(0.0h, 0.0h, 0.0h);
surfaceData.emission = emission * _EmissionColor.rgb;
surfaceData.emission = emission;
#if defined(_ALPHABLEND_ON) || defined(_ALPHAPREMULTIPLY_ON) || defined(_ALPHAOVERLAY_ON)
surfaceData.alpha = albedo.a;
#else
surfaceData.alpha = 1;
#endif
#if defined(_ALPHAMODULATE_ON)
surfaceData.albedo = lerp(half3(1.0, 1.0, 1.0), surfaceData.albedo, surfaceData.alpha);
#endif
#if defined(_ALPHATEST_ON)
clip(surfaceData.alpha - _Cutoff + 0.0001);
#endif
surfaceData.alpha = AlphaBlendAndTest(albedo.a);
surfaceData.albedo = AlphaModulate(surfaceData.albedo, surfaceData.alpha);
}
void InitializeInputData(VertexOutputLit IN, half3 normalTS, out InputData input)

#if _NORMALMAP
input.normalWS = TangentToWorldNormal(normalTS, IN.tangent, IN.binormal, IN.normal);
#else
input.normalWS = normalize(IN.normal);
input.normalWS = FragmentNormalWS(IN.normal);
input.viewDirectionWS = SafeNormalize(GetCameraPositionWS() - input.positionWS);
input.viewDirectionWS = FragmentViewDirWS(IN.viewDirShininess.xyz);
input.vertexLighting = half3(0, 0, 0);
input.bakedGI = half3(0, 0, 0);
input.vertexLighting = half3(0.0h, 0.0h, 0.0h);
input.bakedGI = half3(0.0h, 0.0h, 0.0h);
}

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


#define MAX_SHADOW_CASCADES 4
#ifdef SHADER_API_GLES
#define SHADOWS_SCREEN 0
#else
#define SHADOWS_SCREEN 1
#endif
SCREENSPACE_TEXTURE(_ScreenSpaceShadowMap);
SAMPLER(sampler_ScreenSpaceShadowMap);

half attenuation = SAMPLE_TEXTURE2D(_ScreenSpaceShadowMap, sampler_ScreenSpaceShadowMap, shadowCoord.xy).x;
#endif
// Apply shadow strength
return LerpWhiteTo(attenuation, GetShadowStrength());
return attenuation;
}
inline real SampleShadowmap(float4 shadowCoord)

attenuation = SAMPLE_TEXTURE2D_SHADOW(_ShadowMap, sampler_ShadowMap, shadowCoord.xyz);
#endif
#if SHADER_HINT_NICE_QUALITY
// Apply shadow strength
attenuation = LerpWhiteTo(attenuation, GetShadowStrength());
#endif
// Shadow coords that fall out of the light frustum volume must always return attenuation 1.0
return (OUTSIDE_SHADOW_BOUNDS(shadowCoord)) ? 1.0 : attenuation;
}

return 4 - dot(weights, half4(4, 3, 2, 1));
}
float4 ComputeScreenSpaceShadowCoords(float3 positionWS)
float4 TransformWorldToShadowCoord(float3 positionWS)
#ifdef _SHADOWS_CASCADE
#ifdef _SHADOWS_CASCADE
half cascadeIndex = ComputeCascadeIndex(positionWS);
return mul(_WorldToShadow[cascadeIndex], float4(positionWS, 1.0));
#else

half RealtimeShadowAttenuation(float4 shadowCoord)
{
#if NO_SHADOWS
return 1.0h;
#elif SHADOWS_SCREEN
#else
return SampleShadowmap(shadowCoord);
#endif
}
#endif

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


return o;
}
half Fragment(Interpolators i) : SV_Target
half4 Fragment(Interpolators i) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(i);
#if !defined(UNITY_STEREO_INSTANCING_ENABLED)

#if UNITY_REVERSED_Z
deviceDepth = 1 - deviceDepth;
#endif
deviceDepth = 2 * deviceDepth - 1; //NOTE: Currently must massage depth before computing CS position.
deviceDepth = 2 * deviceDepth - 1; //NOTE: Currently must massage depth before computing CS position.
float4 coords = ComputeScreenSpaceShadowCoords(wpos);
float4 coords = TransformWorldToShadowCoord(wpos);
return SampleShadowmap(coords);
}

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


// Required to compile gles 2.0 with standard SRP library
// All shaders must be compiled with HLSLcc and currently only gles is not using HLSLcc by default
#pragma prefer_hlslcc gles
#pragma target 3.0
#pragma target 2.0
// -------------------------------------
// Material Keywords

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


// Only directional light is supported for lit particles
// No shadow
// No distortion
Shader "LightweightPipeline/Particles/Standard"
Shader "LightweightPipeline/Particles/Standard (Physically Based)"
{
Properties
{

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

#pragma shader_feature _REQUIRE_UV2
#define NO_SHADOWS 1
#include "LWRP/ShaderLibrary/Particles.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"

VertexOutputLit o;
#if _NORMALMAP
OutputTangentToWorld(v.tangent, v.normal, o.tangent, o.binormal, o.normal);
#else
o.normal = normalize(TransformObjectToWorldNormal(v.normal));
#endif
o.color = v.color;
OUTPUT_NORMAL(v, o);
o.color = v.color * _Color;
o.viewDirShininess.xyz = VertexViewDirWS(GetCameraPositionWS() - o.posWS.xyz);
vertTexcoord(v, o);
vertFading(o, o.posWS, o.clipPos);
return o;

}
}
Fallback "LightweightPipeline/Particles/Standard Unlit"
Fallback "LightweightPipeline/Particles/Standard (Simple Lighting)"
CustomEditor "LightweightStandardParticlesShaderGUI"
}

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


_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_BumpScale("Scale", Float) = 1.0
_BumpMap("Normal Map", 2D) = "bump" {}
_EmissionColor("Color", Color) = (0,0,0)
_EmissionMap("Emission", 2D) = "white" {}

#pragma prefer_hlslcc gles
#pragma multi_compile __ SOFTPARTICLES_ON
#pragma multi_compile_fog
#pragma target 2.5
#pragma target 2.0
#pragma shader_feature _NORMALMAP
#pragma shader_feature _EMISSION
#pragma shader_feature _FADING_ON
#pragma shader_feature _REQUIRE_UV2

o.posWS.xyz = TransformObjectToWorld(v.vertex.xyz);
o.posWS.w = ComputeFogFactor(o.clipPos.z);
o.clipPos = TransformWorldToHClip(o.posWS.xyz);
o.color = v.color;
o.color = v.color * _Color;
vertColor(o.color);
vertTexcoord(v, o);

half4 fragParticleUnlit(VertexOutputLit IN) : SV_Target
{
half4 albedo = readTexture(TEXTURE2D_PARAM(_MainTex, sampler_MainTex), IN);
albedo *= _Color;
fragColorMode(IN);
fragSoftParticles(IN);
fragCameraFading(IN);
#if defined(_NORMALMAP)
float3 normal = normalize(UnpackNormalScale(readTexture(TEXTURE2D_PARAM(_BumpMap, sampler_BumpMap), IN), _BumpScale));
#else
float3 normal = float3(0,0,1);
#endif
#if defined(_EMISSION)
half3 emission = readTexture(TEXTURE2D_PARAM(_EmissionMap, sampler_EmissionMap), IN).rgb;
#else
half3 emission = 0;
#endif
half4 albedo = Albedo(IN);
half alpha = AlphaBlendAndTest(albedo.a);
half3 emission = Emission(IN);
half3 diffuse = AlphaModulate(albedo.rgb, alpha);
half4 result = albedo;
#if defined(_ALPHAMODULATE_ON)
result.rgb = lerp(half3(1.0, 1.0, 1.0), albedo.rgb, albedo.a);
#endif
result.rgb += emission * _EmissionColor.rgb;
#if !defined(_ALPHABLEND_ON) && !defined(_ALPHAPREMULTIPLY_ON) && !defined(_ALPHAOVERLAY_ON)
result.a = 1;
#endif
#if defined(_ALPHATEST_ON)
clip(albedo.a - _Cutoff + 0.0001);
#endif
half3 result = diffuse + emission;
ApplyFogColor(result.rgb, half3(0, 0, 0), fogFactor);
return result;
ApplyFogColor(result, half3(0, 0, 0), fogFactor);
return half4(result, alpha);
}
ENDHLSL
}

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


HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 3.0
#pragma target 2.0
// -------------------------------------
// Material Keywords

#pragma vertex LitPassVertex
#pragma fragment LitPassFragmentSimple
#define BUMP_SCALE_NOT_SUPPORTED 1
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
ENDHLSL
}

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

#pragma vertex LitPassVertex
#pragma fragment LitPassFragmentSimpleNull
#define BUMP_SCALE_NOT_SUPPORTED 1
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
ENDHLSL
}

2
ScriptableRenderPipeline/LightweightPipeline/package.json


"version": "0.1.33",
"unity": "2018.1",
"dependencies": {
"com.unity.postprocessing": "0.2.0",
"com.unity.postprocessing": "2.0.2-preview",
"com.unity.render-pipelines.core": "0.1.33"
}
}

2
ScriptableRenderPipeline/master-package.json


"version": "0.1.33",
"unity": "2018.1",
"dependencies": {
"com.unity.postprocessing": "0.2.0"
"com.unity.postprocessing": "2.0.2-preview"
},
"subPackages": [
"Core",

13
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/3DObjects/CornelBox/Materials/Cornell Box.mat


m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _IridescenceMaskMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _IridescenceThicknessMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}

- _IOR: 1
- _InitialBend: 1
- _InvTilingScale: 1
- _Ior: 1
- _IridescenceMask: 1
- _IridescenceThickness: 1
- _LinkDetailsWithBase: 1
- _MaterialID: 1
- _Metallic: 0

- _UVEmissive: 0
- _UVSec: 0
- _ZTestDepthEqualForOpaque: 3
- _ZTestGBuffer: 4
- _ZTestMode: 8
- _ZTestModeDistortion: 8
- _ZWrite: 1

- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _InvPrimScale: {r: 1, g: 1, b: 0, a: 0}
- _IridescenceThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
- _ReflectColor: {r: 1, g: 1, b: 1, a: 1}
- _SpecColor: {r: 1, g: 1, b: 1, a: 1}
- _SpecularColor: {r: 1, g: 1, b: 1, a: 1}

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

正在加载...
取消
保存