Rune Stubbe 8 年前
当前提交
8b51c69a
共有 44 个文件被更改,包括 619 次插入426 次删除
  1. 2
      Assets/ScriptableRenderPipeline/Core/Camera/CameraSwitcher.cs
  2. 28
      Assets/ScriptableRenderPipeline/Core/Debugging/DebugActionManager.cs
  3. 40
      Assets/ScriptableRenderPipeline/Core/Debugging/DebugItemHandler.cs
  4. 2
      Assets/ScriptableRenderPipeline/Core/Debugging/DebugItemUI.cs
  5. 8
      Assets/ScriptableRenderPipeline/Core/Debugging/DebugMenuManager.cs
  6. 5
      Assets/ScriptableRenderPipeline/Core/Debugging/DebugMenuUI.cs
  7. 22
      Assets/ScriptableRenderPipeline/Core/Debugging/DebugPanel.cs
  8. 10
      Assets/ScriptableRenderPipeline/Core/Debugging/DebugPanelUI.cs
  9. 4
      Assets/ScriptableRenderPipeline/Core/Debugging/Editor/DebugMenuEditor.cs
  10. 115
      Assets/ScriptableRenderPipeline/Core/Shadow/Shadow.cs
  11. 38
      Assets/ScriptableRenderPipeline/Core/Shadow/ShadowBase.cs
  12. 22
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs
  13. 47
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/LightingDebugPanel.cs
  14. 13
      Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
  15. 10
      Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.asset
  16. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.asset.meta
  17. 80
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/AmbientOcclusion.cs
  18. 38
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/Resources/CommonAmbientOcclusion.hlsl
  19. 8
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/Resources/Denoising.hlsl
  20. 64
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/Resources/Estimation.hlsl
  21. 4
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/ClusteredUtils.hlsl
  22. 30
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/FeatureFlags.hlsl
  23. 4
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/LightingConvexHullUtils.hlsl
  24. 150
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs
  25. 24
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs.hlsl
  26. 14
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePassLoop.hlsl
  27. 14
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/lightlistbuild-bigtile.compute
  28. 12
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/lightlistbuild-clustered.compute
  29. 10
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/lightlistbuild.compute
  30. 4
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/scrbound.compute
  31. 8
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs.hlsl
  32. 10
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs
  33. 24
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs.hlsl
  34. 14
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl
  35. 4
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CombineSubsurfaceScattering.shader
  36. 8
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.cs.hlsl
  37. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/RenderPipelineResources.cs
  38. 20
      Assets/ScriptableRenderPipeline/ShaderGenerator/Editor/CSharpToHLSL.cs
  39. 30
      Assets/ScriptableRenderPipeline/ShaderGenerator/Editor/ShaderTypeGeneration.cs
  40. 92
      Assets/ScriptableRenderPipeline/Core/Shadow/Resources/DebugDisplayShadowMap.shader
  41. 9
      Assets/ScriptableRenderPipeline/Core/Shadow/Resources.meta
  42. 0
      /Assets/ScriptableRenderPipeline/Core/Shadow/Resources/DebugDisplayShadowMap.shader.meta
  43. 0
      /Assets/ScriptableRenderPipeline/Core/Shadow/Resources/DebugDisplayShadowMap.shader

2
Assets/ScriptableRenderPipeline/Core/Camera/CameraSwitcher.cs


m_CameraNames[GetCameraCount() - 1] = new GUIContent("Original Camera");
m_CameraIndices[GetCameraCount() - 1] = GetCameraCount() - 1;
DebugMenuManager.instance.AddDebugItem<int>("Camera", "Camera Switcher", () => m_CurrentCameraIndex, (value) => SetCameraIndex((int)value), false, new DebugItemHandlerIntEnum(m_CameraNames, m_CameraIndices));
DebugMenuManager.instance.AddDebugItem<int>("Camera", "Camera Switcher", () => m_CurrentCameraIndex, (value) => SetCameraIndex((int)value), DebugItemFlag.None, new DebugItemHandlerIntEnum(m_CameraNames, m_CameraIndices));
}
int GetCameraCount()

28
Assets/ScriptableRenderPipeline/Core/Debugging/DebugActionManager.cs


public enum Axis { X, Y, Third, Fourth, Fifth, Sixth, Seventh, Eigth }
public enum Joy { All, First, Second }
public string name;
public string desc;
public string btnNegative;
public string btnPositive;
public string altBtnNegative;
public string altBtnPositive;
public float gravity;
public float deadZone;
public float sensitivity;
public bool snap;
public bool invert;
public Kind kind;
public Axis axis;
public Joy joystick;
public string name = "";
public string desc = "";
public string btnNegative = "";
public string btnPositive = "";
public string altBtnNegative = "";
public string altBtnPositive = "";
public float gravity = 0.0f;
public float deadZone = 0.0f;
public float sensitivity = 0.0f;
public bool snap = false;
public bool invert = false;
public Kind kind = Kind.Axis;
public Axis axis = Axis.X;
public Joy joystick = Joy.All;
bool InputAlreadyRegistered(string name, Kind kind, UnityEditor.SerializedProperty spAxes)
{

40
Assets/ScriptableRenderPipeline/Core/Debugging/DebugItemHandler.cs


public class DebugItemHandlerFloatMinMax
: DefaultDebugItemHandler
{
float m_Min = 0.0f;
float m_Max = 1.0f;
protected float m_Min = 0.0f;
protected float m_Max = 1.0f;
public DebugItemHandlerFloatMinMax(float min, float max)
{
m_Min = min;

if (EditorGUI.EndChangeCheck())
{
m_DebugItem.SetValue(value);
return true;
}
return false;
}
#endif
}
public class DebugItemHandlerUIntMinMax
: DefaultDebugItemHandler
{
protected uint m_Min = 0;
protected uint m_Max = 1;
public DebugItemHandlerUIntMinMax(uint min, uint max)
{
m_Min = min;
m_Max = max;
}
public override void ClampValues(Func<object> getter, Action<object> setter)
{
setter(Math.Min(m_Max, Math.Max(m_Min, (uint)getter())));
}
#if UNITY_EDITOR
public override bool OnEditorGUIImpl()
{
Initialize();
EditorGUI.BeginChangeCheck();
int value = EditorGUILayout.IntSlider(m_DebugItem.name, (int)(uint)m_DebugItem.GetValue(), (int)m_Min, (int)m_Max);
if (EditorGUI.EndChangeCheck())
{
m_DebugItem.SetValue((uint)value);
return true;
}

2
Assets/ScriptableRenderPipeline/Core/Debugging/DebugItemUI.cs


protected GameObject m_Root = null;
protected DebugItem m_DebugItem = null;
public bool dynamicDisplay { get { return m_DebugItem.dynamicDisplay; } }
public bool dynamicDisplay { get { return (m_DebugItem.flags & DebugItemFlag.DynamicDisplay) != 0; } }
protected DebugItemUI(DebugItem debugItem)
{

8
Assets/ScriptableRenderPipeline/Core/Debugging/DebugMenuManager.cs


m_DebugMenuUI.AddDebugPanel(panel);
}
public void AddDebugItem<DebugPanelType, DebugItemType>(string name, Func<object> getter, Action<object> setter = null, bool dynamicDisplay = false, DebugItemHandler handler = null) where DebugPanelType : DebugPanel
public void AddDebugItem<DebugPanelType, DebugItemType>(string name, Func<object> getter, Action<object> setter = null, DebugItemFlag flags = DebugItemFlag.None, DebugItemHandler handler = null) where DebugPanelType : DebugPanel
debugPanel.AddDebugItem<DebugItemType>(name, getter, setter, dynamicDisplay, handler);
debugPanel.AddDebugItem<DebugItemType>(name, getter, setter, flags, handler);
public void AddDebugItem<DebugItemType>(string debugPanelName, string name, Func<object> getter, Action<object> setter = null, bool dynamicDisplay = false, DebugItemHandler handler = null)
public void AddDebugItem<DebugItemType>(string debugPanelName, string name, Func<object> getter, Action<object> setter = null, DebugItemFlag flags = DebugItemFlag.None, DebugItemHandler handler = null)
{
DebugPanel debugPanel = GetDebugPanel(debugPanelName);
// If the menu does not exist, create a generic one. This way, users don't have to explicitely create a new DebugMenu class if they don't need any particular overriding of default behavior.

if (debugPanel != null)
{
debugPanel.AddDebugItem<DebugItemType>(name, getter, setter, dynamicDisplay, handler);
debugPanel.AddDebugItem<DebugItemType>(name, getter, setter, flags, handler);
}
m_DebugMenuStateDirty = true;

5
Assets/ScriptableRenderPipeline/Core/Debugging/DebugMenuUI.cs


m_PersistentPanelRoot.SetActive(false);
DebugMenuUI.CreateTextElement("DebugMenuTitle", "Debug Menu", 14, TextAnchor.MiddleCenter, m_MainPanelLayout);
DebugMenuUI.CreateTextElement("DebugMenuTitle", "Debug Window", 14, TextAnchor.MiddleCenter, m_MainPanelLayout);
m_DebugMenuManager.GetPersistentDebugPanel().panelUI.BuildGUI(m_PersistentPanelLayout);
m_PersistentDebugPanelUI = m_DebugMenuManager.GetPersistentDebugPanel().panelUI;

public void OnEditorGUI()
{
s_UIChanged = false;
m_DebugPanelUIs[m_ActivePanelIndex].OnEditorGUI();
if(!m_DebugPanelUIs[m_ActivePanelIndex].empty)
m_DebugPanelUIs[m_ActivePanelIndex].OnEditorGUI();
if(s_UIChanged)
{
UnityEditorInternal.InternalEditorUtility.RepaintAllViews();

22
Assets/ScriptableRenderPipeline/Core/Debugging/DebugPanel.cs


namespace UnityEngine.Experimental.Rendering
{
[Flags]
public enum DebugItemFlag
{
None,
DynamicDisplay,
EditorOnly
}
public class DebugItem
{
static public event Action<DebugItem> OnItemDirty;

public string panelName { get { return m_PanelName; } }
public DebugItemHandler handler { get { return m_Handler; } }
public bool dynamicDisplay { get { return m_DynamicDisplay; } }
public DebugItemHandler handler { get { return m_Handler; } }
public DebugItemFlag flags { get { return m_Flags; } }
public DebugItem(string name, string panelName, Type type, Func<object> getter, Action<object> setter, bool dynamicDisplay = false, DebugItemHandler handler = null)
public DebugItem(string name, string panelName, Type type, Func<object> getter, Action<object> setter, DebugItemFlag flags = DebugItemFlag.None, DebugItemHandler handler = null)
{
m_Type = type;
m_Setter = setter;

m_Handler = handler;
m_DynamicDisplay = dynamicDisplay;
m_Flags = flags;
}
public Type GetItemType()

string m_Name;
string m_PanelName;
DebugItemHandler m_Handler = null;
bool m_DynamicDisplay = false;
DebugItemFlag m_Flags = DebugItemFlag.None;
}
public class DebugPanel

m_DebugPanelUI.RebuildGUI();
}
public void AddDebugItem<ItemType>(string itemName, Func<object> getter, Action<object> setter, bool dynamicDisplay = false, DebugItemHandler handler = null)
public void AddDebugItem<ItemType>(string itemName, Func<object> getter, Action<object> setter, DebugItemFlag flags = DebugItemFlag.None, DebugItemHandler handler = null)
{
if (handler == null)
handler = new DefaultDebugItemHandler();

RemoveDebugItem(oldItem);
DebugItem newItem = new DebugItem(itemName, m_Name, typeof(ItemType), getter, setter, dynamicDisplay, handler);
DebugItem newItem = new DebugItem(itemName, m_Name, typeof(ItemType), getter, setter, flags, handler);
handler.SetDebugItem(newItem);
m_Items.Add(newItem);
}

10
Assets/ScriptableRenderPipeline/Core/Debugging/DebugPanelUI.cs


protected List<DebugItemUI> m_ItemsUI = new List<DebugItemUI>();
protected int m_SelectedItem = -1;
public bool empty { get { return m_DebugPanel.itemCount == 0; } }
public int itemCount { get { return m_ItemsUI.Count; } }
public DebugPanelUI()

m_ItemsUI.Clear();
for (int i = 0; i < m_DebugPanel.itemCount; i++)
{
DebugItemHandler handler = m_DebugPanel.GetDebugItem(i).handler; // Should never be null, we have at least the default handler
m_ItemsUI.Add(handler.BuildGUI(parent));
DebugItem item = m_DebugPanel.GetDebugItem(i);
if(!((item.flags & DebugItemFlag.EditorOnly) != 0))
{
DebugItemHandler handler = item.handler; // Should never be null, we have at least the default handler
m_ItemsUI.Add(handler.BuildGUI(parent));
}
}
}

4
Assets/ScriptableRenderPipeline/Core/Debugging/Editor/DebugMenuEditor.cs


[SerializeField]
private DebugMenuState m_DebugMenuState;
[MenuItem("HDRenderPipeline/Debug Menu")]
[MenuItem("HDRenderPipeline/Debug Window")]
var window = EditorWindow.GetWindow<DebugMenuEditor>("Debug Menu");
var window = EditorWindow.GetWindow<DebugMenuEditor>("Debug Window");
window.Show();
}

115
Assets/ScriptableRenderPipeline/Core/Shadow/Shadow.cs


protected uint[] m_TmpHeights = new uint[ShadowmapBase.ShadowRequest.k_MaxFaceCount];
protected Vector4[] m_TmpSplits = new Vector4[k_MaxCascadesInShader];
protected ShadowAlgoVector m_SupportedAlgorithms = new ShadowAlgoVector( 0, false );
protected Material m_DebugMaterial = null;
protected struct Key
{

public void Initialize( AtlasInit init )
{
m_ShaderKeyword = init.shaderKeyword;
m_ShaderKeyword = init.shaderKeyword;
m_DebugMaterial = new Material(Shader.Find("Hidden/ScriptableRenderPipeline/DebugDisplayShadowMap")) { hideFlags = HideFlags.HideAndDontSave };
}
override public void ReserveSlots( ShadowContextStorage sc )

{
if( m_Shadowmap != null )
m_Shadowmap.Release();
Object.DestroyImmediate(m_DebugMaterial);
}
override public bool Reserve( FrameId frameId, ref ShadowData shadowData, ShadowRequest sr, uint width, uint height, ref VectorArray<ShadowData> entries, ref VectorArray<ShadowPayload> payload, VisibleLight[] lights )

{
// Nothing to do for this implementation here, as the atlas is reconstructed each frame, instead of keeping state across frames
}
override public void DisplayShadowMap(ScriptableRenderContext renderContext, Vector4 scaleBias, uint slice, float screenX, float screenY, float screenSizeX, float screenSizeY)
{
CommandBuffer debugCB = new CommandBuffer();
debugCB.name = "";
MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
propertyBlock.SetTexture("_AtlasTexture", m_Shadowmap);
propertyBlock.SetVector("_TextureScaleBias", scaleBias);
propertyBlock.SetFloat("_TextureSlice", (float)slice);
debugCB.SetViewport(new Rect(screenX, screenY, screenSizeX, screenSizeY));
debugCB.DrawProcedural(Matrix4x4.identity, m_DebugMaterial, m_DebugMaterial.FindPass("REGULARSHADOW"), MeshTopology.Triangles, 3, 1, propertyBlock);
renderContext.ExecuteCommandBuffer(debugCB);
debugCB.Dispose();
}
}
// -------------------------------------------------------------------------------------------------------------------------------------------------

}
base.PostUpdate( frameId, cb, rendertargetSlice, lights );
}
override public void DisplayShadowMap(ScriptableRenderContext renderContext, Vector4 scaleBias, uint slice, float screenX, float screenY, float screenSizeX, float screenSizeY)
{
CommandBuffer debugCB = new CommandBuffer();
debugCB.name = "";
MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
propertyBlock.SetTexture("_AtlasTexture", m_Shadowmap);
propertyBlock.SetVector("_TextureScaleBias", scaleBias);
propertyBlock.SetFloat("_TextureSlice", (float)slice);
debugCB.SetViewport(new Rect(screenX, screenY, screenSizeX, screenSizeY));
debugCB.DrawProcedural(Matrix4x4.identity, m_DebugMaterial, m_DebugMaterial.FindPass("VARIANCESHADOW"), MeshTopology.Triangles, 3, 1, propertyBlock);
renderContext.ExecuteCommandBuffer(debugCB);
debugCB.Dispose();
}
}
// -------------------------------------------------------------------------------------------------------------------------------------------------
//

// The following vector holds data that are returned to the caller so it can be sent to GPU memory in some form. Contents are stable in between calls to ProcessShadowRequests.
private ShadowIndicesVector m_ShadowIndices = new ShadowIndicesVector( 0, false );
public override uint GetShadowMapCount()
{
return (uint)m_Shadowmaps.Length;
}
public override uint GetShadowMapSliceCount(uint shadowMapIndex)
{
if (shadowMapIndex >= m_Shadowmaps.Length)
return 0;
return m_Shadowmaps[shadowMapIndex].slices;
}
public override uint GetShadowRequestCount()
{
return m_TmpRequests.Count();
}
public override uint GetShadowRequestFaceCount(uint requestIndex)
{
if (requestIndex >= (int)m_TmpRequests.Count())
return 0;
else
return m_TmpRequests[requestIndex].facecount;
}
public override int GetShadowRequestIndex(Light light)
{
for(int i = 0 ; i < m_TmpRequests.Count() ; ++i)
{
if (m_TmpRequests[(uint)i].instanceId == light.GetInstanceID())
return i;
}
return -1;
}
public ShadowManager( ShadowSettings shadowSettings, ref ShadowContext.CtxtInit ctxtInitializer, ShadowmapBase[] shadowmaps )
{
m_ShadowSettings = shadowSettings;

}
}
public override void DisplayShadows(ScriptableRenderContext renderContext, Material displayMaterial, int shadowMapIndex, float screenX, float screenY, float screenSizeX, float screenSizeY)
public override void DisplayShadow(ScriptableRenderContext renderContext, int shadowRequestIndex, uint faceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY)
using (new HDPipeline.Utilities.ProfilingSample("Display Shadows", renderContext))
{
// This code is specific to shadow atlas implementation
MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
if (m_ShadowIndices.Count() == 0)
return;
CommandBuffer debugCB = new CommandBuffer();
debugCB.name = "Display shadow Overlay";
uint index = Math.Max(0, Math.Min((uint)(m_ShadowIndices.Count() - 1), (uint)shadowRequestIndex));
int offset = (m_TmpRequests[index].facecount > 1 ) ? 1 : 0;
VectorArray<ShadowData> shadowDatas = m_ShadowCtxt.shadowDatas;
ShadowData faceData = shadowDatas[(uint)(m_ShadowIndices[index] + offset + faceIndex)];
uint texID, samplerID, slice;
faceData.UnpackShadowmapId(out texID, out samplerID, out slice);
m_Shadowmaps[texID].DisplayShadowMap(renderContext, faceData.scaleOffset, slice, screenX, screenY, screenSizeX, screenSizeY);
}
if (shadowMapIndex == -1) // Display the Atlas
{
propertyBlock.SetVector("_TextureScaleBias", new Vector4(1.0f, 1.0f, 0.0f, 0.0f));
}
else // Display particular index
{
VectorArray<ShadowData> shadowDatas = m_ShadowCtxt.shadowDatas;
uint shadowIdx = Math.Min((uint)shadowMapIndex, shadowDatas.Count());
propertyBlock.SetVector("_TextureScaleBias", shadowDatas[shadowIdx].scaleOffset);
}
public override void DisplayShadowMap(ScriptableRenderContext renderContext, uint shadowMapIndex, uint sliceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY)
{
if(m_Shadowmaps.Length == 0)
return;
debugCB.SetViewport(new Rect(screenX, screenY, screenSizeX, screenSizeY));
debugCB.DrawProcedural(Matrix4x4.identity, displayMaterial, 0, MeshTopology.Triangles, 3, 1, propertyBlock);
renderContext.ExecuteCommandBuffer(debugCB);
}
uint index = Math.Max(0, Math.Min((uint)(m_Shadowmaps.Length - 1), shadowMapIndex));
m_Shadowmaps[index].DisplayShadowMap(renderContext, new Vector4(1.0f, 1.0f, 0.0f, 0.0f), sliceIndex, screenX, screenY, screenSizeX, screenSizeY);
}
public override void SyncData()

38
Assets/ScriptableRenderPipeline/Core/Shadow/ShadowBase.cs


id = texIdx << 24 | sampIdx << 16 | slice;
}
public void UnpackShadowmapId(out uint texIdx, out uint sampIdx, out uint slice)
{
texIdx = (id >> 24) & 0xff;
sampIdx = (id >> 16) & 0xff;
slice = (id & 0xffff);
}
public void PackShadowType( GPUShadowType type, GPUShadowAlgorithm algorithm )
{
shadowType = (uint)type << ShadowConstants.Bits.k_GPUShadowAlgorithm | (uint) algorithm;

protected readonly ShadowSupport m_ShadowSupport;
protected CullResults m_CullResults; // TODO: Temporary, due to CullResults dependency in ShadowUtils' matrix extraction code. Remove this member once that dependency is gone.
public uint width { get { return m_Width; } }
public uint height { get { return m_Height; } }
public uint slices { get { return m_Slices; } }
public struct BaseInit
{
public uint width; // width of the shadowmap

abstract public void ReserveSlots( ShadowContextStorage sc );
abstract public void Fill( ShadowContextStorage cs );
abstract protected void Register( GPUShadowType type, ShadowRegistry registry );
abstract public void DisplayShadowMap(ScriptableRenderContext renderContext, Vector4 scaleBias, uint slice, float screenX, float screenY, float screenSizeX, float screenSizeY);
}
interface IShadowManager

void ProcessShadowRequests( FrameId frameId, CullResults cullResults, Camera camera, VisibleLight[] lights, ref uint shadowRequestsCount, int[] shadowRequests, out int[] shadowDataIndices );
// Renders all shadows for lights the were deemed shadow casters after the last call to ProcessShadowRequests
void RenderShadows( FrameId frameId, ScriptableRenderContext renderContext, CullResults cullResults, VisibleLight[] lights );
// Debug function to display a shadow at the screen coordinate with the provided material.
void DisplayShadows(ScriptableRenderContext renderContext, Material displayMaterial, int shadowMapIndex, float screenX, float screenY, float screenSizeX, float screenSizeY);
// Debug function to display a shadow at the screen coordinate
void DisplayShadow(ScriptableRenderContext renderContext, int shadowIndex, uint faceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY);
void DisplayShadowMap(ScriptableRenderContext renderContext, uint shadowMapIndex, uint sliceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY);
// Synchronize data with GPU buffers
void SyncData();
// Binds resources to shader stages just before rendering the lighting pass

uint GetShadowMapCount();
uint GetShadowMapSliceCount(uint shadowMapIndex);
uint GetShadowRequestCount();
uint GetShadowRequestFaceCount(uint requestIndex);
int GetShadowRequestIndex(Light light);
}
abstract public class ShadowManagerBase : ShadowRegistry, IShadowManager

public abstract void DisplayShadows(ScriptableRenderContext renderContext, Material displayMaterial, int shadowMapIndex, float screenX, float screenY, float screenSizeX, float screenSizeY);
public abstract void DisplayShadow(ScriptableRenderContext renderContext, int shadowIndex, uint faceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY);
public abstract void DisplayShadowMap(ScriptableRenderContext renderContext, uint shadowMapIndex, uint sliceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY);
public abstract void SyncData();
public abstract void BindResources( ScriptableRenderContext renderContext );
public abstract void UpdateCullingParameters( ref CullingParameters cullingParams );

protected abstract void PruneShadowCasters( Camera camera, VisibleLight[] lights, ref VectorArray<int> shadowRequests, ref VectorArray<ShadowmapBase.ShadowRequest> requestsGranted, out uint totalRequestCount );
// allocate the shadow requests in the shadow map, only is called if shadowsCount > 0 - may modify shadowRequests and shadowsCount
protected abstract void AllocateShadows( FrameId frameId, VisibleLight[] lights, uint totalGranted, ref VectorArray<ShadowmapBase.ShadowRequest> grantedRequests, ref VectorArray<int> shadowIndices, ref VectorArray<ShadowData> shadowmapDatas, ref VectorArray<ShadowPayload> shadowmapPayload );
public abstract uint GetShadowMapCount();
public abstract uint GetShadowMapSliceCount(uint shadowMapIndex);
public abstract uint GetShadowRequestCount();
public abstract uint GetShadowRequestFaceCount(uint requestIndex);
public abstract int GetShadowRequestIndex(Light light);
}
} // end of namespace UnityEngine.Experimental.ScriptableRenderLoop

22
Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs


{
public static string kEnableShadowDebug = "Enable Shadows";
public static string kShadowDebugMode = "Shadow Debug Mode";
public static string kShadowSelectionDebug = "Use Selection";
public static string kShadowAtlasIndexDebug = "Shadow Atlas Index";
public static string kLightingDebugMode = "Lighting Debug Mode";
public static string kOverrideSmoothnessDebug = "Override Smoothness";
public static string kOverrideSmoothnessValueDebug = "Override Smoothness Value";

public void RegisterDebug()
{
DebugMenuManager.instance.AddDebugItem<float>("Display Stats", "Frame Rate", () => 1.0f / Time.smoothDeltaTime, null, true);
DebugMenuManager.instance.AddDebugItem<float>("Display Stats", "Frame Time (ms)", () => Time.smoothDeltaTime * 1000.0f, null, true);
DebugMenuManager.instance.AddDebugItem<float>("Display Stats", "Frame Rate", () => 1.0f / Time.smoothDeltaTime, null, DebugItemFlag.DynamicDisplay);
DebugMenuManager.instance.AddDebugItem<float>("Display Stats", "Frame Time (ms)", () => Time.smoothDeltaTime * 1000.0f, null, DebugItemFlag.DynamicDisplay);
DebugMenuManager.instance.AddDebugItem<int>("Material", "Material",() => materialDebugSettings.debugViewMaterial, (value) => SetDebugViewMaterial((int)value), false, new DebugItemHandlerIntEnum(DebugDisplaySettings.debugViewMaterialStrings, DebugDisplaySettings.debugViewMaterialValues));
DebugMenuManager.instance.AddDebugItem<int>("Material", "Engine",() => materialDebugSettings.debugViewEngine, (value) => SetDebugViewEngine((int)value), false, new DebugItemHandlerIntEnum(DebugDisplaySettings.debugViewEngineStrings, DebugDisplaySettings.debugViewEngineValues));
DebugMenuManager.instance.AddDebugItem<int>("Material", "Material",() => materialDebugSettings.debugViewMaterial, (value) => SetDebugViewMaterial((int)value), DebugItemFlag.None, new DebugItemHandlerIntEnum(DebugDisplaySettings.debugViewMaterialStrings, DebugDisplaySettings.debugViewMaterialValues));
DebugMenuManager.instance.AddDebugItem<int>("Material", "Engine",() => materialDebugSettings.debugViewEngine, (value) => SetDebugViewEngine((int)value), DebugItemFlag.None, new DebugItemHandlerIntEnum(DebugDisplaySettings.debugViewEngineStrings, DebugDisplaySettings.debugViewEngineValues));
DebugMenuManager.instance.AddDebugItem<int>("Material", "GBuffer",() => materialDebugSettings.debugViewGBuffer, (value) => SetDebugViewGBuffer((int)value), false, new DebugItemHandlerIntEnum(DebugDisplaySettings.debugViewMaterialGBufferStrings, DebugDisplaySettings.debugViewMaterialGBufferValues));
DebugMenuManager.instance.AddDebugItem<int>("Material", "GBuffer",() => materialDebugSettings.debugViewGBuffer, (value) => SetDebugViewGBuffer((int)value), DebugItemFlag.None, new DebugItemHandlerIntEnum(DebugDisplaySettings.debugViewMaterialGBufferStrings, DebugDisplaySettings.debugViewMaterialGBufferValues));
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, uint>(kShadowMapIndexDebug, () => lightingDebugSettings.shadowMapIndex, (value) => lightingDebugSettings.shadowMapIndex = (uint)value);
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, bool>(kShadowSelectionDebug, () => lightingDebugSettings.shadowDebugUseSelection, (value) => lightingDebugSettings.shadowDebugUseSelection = (bool)value, DebugItemFlag.EditorOnly);
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, uint>(kShadowMapIndexDebug, () => lightingDebugSettings.shadowMapIndex, (value) => lightingDebugSettings.shadowMapIndex = (uint)value, DebugItemFlag.None, new DebugItemHandlerShadowIndex(1));
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, uint>(kShadowAtlasIndexDebug, () => lightingDebugSettings.shadowAtlasIndex, (value) => lightingDebugSettings.shadowAtlasIndex = (uint)value, DebugItemFlag.None, new DebugItemHandlerShadowAtlasIndex(1));
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, float>(kOverrideSmoothnessValueDebug, () => lightingDebugSettings.overrideSmoothnessValue, (value) => lightingDebugSettings.overrideSmoothnessValue = (float)value, false, new DebugItemHandlerFloatMinMax(0.0f, 1.0f));
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, float>(kOverrideSmoothnessValueDebug, () => lightingDebugSettings.overrideSmoothnessValue, (value) => lightingDebugSettings.overrideSmoothnessValue = (float)value, DebugItemFlag.None, new DebugItemHandlerFloatMinMax(0.0f, 1.0f));
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, float>(kSkyReflectionMipmapDebug, () => lightingDebugSettings.skyReflectionMipmap, (value) => lightingDebugSettings.skyReflectionMipmap = (float)value, false, new DebugItemHandlerFloatMinMax(0.0f, 1.0f));
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, float>(kSkyReflectionMipmapDebug, () => lightingDebugSettings.skyReflectionMipmap, (value) => lightingDebugSettings.skyReflectionMipmap = (float)value, DebugItemFlag.None, new DebugItemHandlerFloatMinMax(0.0f, 1.0f));
DebugMenuManager.instance.AddDebugItem<bool>("Rendering", "Display Opaque",() => renderingDebugSettings.displayOpaqueObjects, (value) => renderingDebugSettings.displayOpaqueObjects = (bool)value);
DebugMenuManager.instance.AddDebugItem<bool>("Rendering", "Display Transparency",() => renderingDebugSettings.displayTransparentObjects, (value) => renderingDebugSettings.displayTransparentObjects = (bool)value);

public DebugLightingMode debugLightingMode = DebugLightingMode.None;
public bool enableShadows = true;
public ShadowMapDebugMode shadowDebugMode = ShadowMapDebugMode.None;
public bool shadowDebugUseSelection = false;
public uint shadowAtlasIndex = 0;
public FullScreenDebugMode fullScreenDebugMode = FullScreenDebugMode.None;
public bool overrideSmoothness = false;

47
Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/LightingDebugPanel.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
#if UNITY_EDITOR
using UnityEditor;

{
public class DebugItemHandlerShadowAtlasIndex
: DebugItemHandlerUIntMinMax
{
public DebugItemHandlerShadowAtlasIndex(uint max)
: base(0, max)
{
}
public override void ClampValues(Func<object> getter, Action<object> setter)
{
HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
m_Max = (uint)hdPipeline.GetShadowAtlasCount() - 1;
setter(Math.Min(m_Max, Math.Max(m_Min, (uint)getter())));
}
}
public class DebugItemHandlerShadowIndex
: DebugItemHandlerUIntMinMax
{
public DebugItemHandlerShadowIndex(uint max)
: base(0, max)
{
}
public override void ClampValues(Func<object> getter, Action<object> setter)
{
HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
m_Max = (uint)hdPipeline.GetCurrentShadowCount() - 1;
setter(Math.Min(m_Max, Math.Max(m_Min, (uint)getter())));
}
}
public class LightingDebugPanelUI
: DebugPanelUI
{

if ((ShadowMapDebugMode)shadowDebug.GetValue() == ShadowMapDebugMode.VisualizeShadowMap)
{
EditorGUI.indentLevel++;
m_DebugPanel.GetDebugItem(DebugDisplaySettings.kShadowMapIndexDebug).handler.OnEditorGUI();
DebugItem shadowSelectionDebug = m_DebugPanel.GetDebugItem(DebugDisplaySettings.kShadowSelectionDebug);
shadowSelectionDebug.handler.OnEditorGUI();
if(!(bool)shadowSelectionDebug.GetValue())
m_DebugPanel.GetDebugItem(DebugDisplaySettings.kShadowMapIndexDebug).handler.OnEditorGUI();
EditorGUI.indentLevel--;
}
if ((ShadowMapDebugMode)shadowDebug.GetValue() == ShadowMapDebugMode.VisualizeAtlas)
{
EditorGUI.indentLevel++;
m_DebugPanel.GetDebugItem(DebugDisplaySettings.kShadowAtlasIndexDebug).handler.OnEditorGUI();
DebugItem lightingDebugModeItem = m_DebugPanel.GetDebugItem(DebugDisplaySettings.kLightingDebugMode);
lightingDebugModeItem.handler.OnEditorGUI();
if ((DebugLightingMode)lightingDebugModeItem.GetValue() == DebugLightingMode.SpecularLighting)

13
Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs


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

public DebugDisplaySettings m_DebugDisplaySettings = new DebugDisplaySettings();
private int m_DebugFullScreenTempRT;
private bool m_FullScreenDebugPushed = false;
public SubsurfaceScatteringSettings sssSettings
{

private CommonSettings.Settings m_CommonSettings = CommonSettings.Settings.s_Defaultsettings;
private SkySettings m_SkySettings;
private SkySettings m_SkySettings = null;
private ScreenSpaceAmbientOcclusionSettings.Settings m_SsaoSettings = ScreenSpaceAmbientOcclusionSettings.Settings.s_Defaultsettings;
public CommonSettings.Settings commonSettingsToUse

using (new Utilities.ProfilingSample("Build Light list and render shadows", renderContext))
{
// TODO: Everything here (SSAO, Shadow, Build light list, material and light classification can be parallelize with Async compute)
m_SsaoEffect.Render(ssaoSettingsToUse, this, hdCamera, renderContext, GetDepthTexture(), m_Asset.renderingSettings.useForwardRenderingOnly);
m_SsaoEffect.Render(ssaoSettingsToUse, this, hdCamera, renderContext, m_Asset.renderingSettings.useForwardRenderingOnly);
m_LightLoop.PrepareLightsForGPU(m_ShadowSettings, cullResults, camera);
m_LightLoop.RenderShadows(renderContext, cullResults);
renderContext.SetupCameraProperties(camera); // Need to recall SetupCameraProperties after m_ShadowPass.Render

{
if(debugMode == m_DebugDisplaySettings.lightingDebugSettings.fullScreenDebugMode)
{
m_FullScreenDebugPushed = true; // We need this flag because otherwise if no fullscreen debug is pushed, when we render the result in RenderDebug the temporary RT will not exist.
cb.GetTemporaryRT(m_DebugFullScreenTempRT, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
cb.Blit(textureID, m_DebugFullScreenTempRT);
}

if (camera.camera.cameraType == CameraType.Reflection || camera.camera.cameraType == CameraType.Preview)
return;
// We make sure the depth buffer is bound because we need it to write depth at near plane for overlays otherwise the editor grid end up visible in them.
Utilities.SetRenderTarget(renderContext, BuiltinRenderTextureType.CameraTarget, m_CameraDepthStencilBufferRT);
if(m_DebugDisplaySettings.lightingDebugSettings.fullScreenDebugMode != FullScreenDebugMode.None)
if(m_DebugDisplaySettings.lightingDebugSettings.fullScreenDebugMode != FullScreenDebugMode.None && m_FullScreenDebugPushed)
m_FullScreenDebugPushed = false;
debugCB.SetGlobalTexture("_DebugFullScreenTexture", m_DebugFullScreenTempRT);
m_DebugFullScreen.SetFloat("_FullScreenDebugMode", (float)m_DebugDisplaySettings.lightingDebugSettings.fullScreenDebugMode);
Utilities.DrawFullScreen(debugCB, m_DebugFullScreen, camera, BuiltinRenderTextureType.CameraTarget);

10
Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.asset


useForwardRenderingOnly: 0
useDepthPrepass: 0
sssSettings:
numProfiles: 2
numProfiles: 1
- {fileID: 11400000, guid: d6ee4403015766f4093158d69216c0bf, type: 2}
- {fileID: 11400000, guid: 906339bac2066fc4aa22a3652e1283ef, type: 2}
- {fileID: 0}
tileSettings:
enableTileAndCluster: 1
enableSplitLightEvaluation: 1

spotCookieSize: 128
pointCookieSize: 512
reflectionCubemapSize: 128
m_DefaultDiffuseMaterial: {fileID: 2100000, guid: 73c176f402d2c2f4d929aa5da7585d17,
type: 2}
m_DefaultShader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_DefaultDiffuseMaterial: {fileID: 0}
m_DefaultShader: {fileID: 0}

2
Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.asset.meta


fileFormatVersion: 2
guid: 449281dd2b4fbee49b8397de0541ea3c
timeCreated: 1496162200
timeCreated: 1496931629
licenseType: Pro
NativeFormatImporter:
mainObjectFileID: 11400000

80
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/AmbientOcclusion.cs


internal static readonly int _AOBuffer = Shader.PropertyToID("_AmbientOcclusionTexture");
internal static readonly int _TempTex1 = Shader.PropertyToID("_TempTex1");
internal static readonly int _TempTex2 = Shader.PropertyToID("_TempTex2");
internal static readonly int _CameraDepthTexture = Shader.PropertyToID("_CameraDepthTexture");
CommandBuffer m_Command;
// For the AO buffer, use R8 or RHalf if available.
static RenderTextureFormat GetAOBufferFormat()
{
if (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.R8))
return RenderTextureFormat.R8;
if (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RHalf))
return RenderTextureFormat.RHalf;
return RenderTextureFormat.Default;
}
public ScreenSpaceAmbientOcclusionEffect()
{}

m_Material.hideFlags = HideFlags.DontSave;
}
public void Render(ScreenSpaceAmbientOcclusionSettings.Settings settings, HDRenderPipeline hdRP, HDCamera hdCamera, ScriptableRenderContext renderContext, RenderTargetIdentifier depthID, bool isForward)
public void Render(ScreenSpaceAmbientOcclusionSettings.Settings settings, HDRenderPipeline hdRP, HDCamera hdCamera, ScriptableRenderContext renderContext, bool isForward)
const RenderTextureFormat kFormat = RenderTextureFormat.ARGB32;
const RenderTextureFormat kTempFormat = RenderTextureFormat.ARGB32;
if (m_Command == null)
{
m_Command = new CommandBuffer { name = "Ambient Occlusion" };
}
else
{
m_Command.Clear();
}
var cmd2 = new CommandBuffer { name = "Setup neutral Ambient Occlusion (1x1)" };
cmd2.SetGlobalTexture("_AmbientOcclusionTexture", PostProcessing.RuntimeUtilities.blackTexture); // Neutral is black, see the comment in the shaders
renderContext.ExecuteCommandBuffer(cmd2);
cmd2.Dispose();
return ;
m_Command.SetGlobalTexture(Uniforms._AOBuffer, PostProcessing.RuntimeUtilities.blackTexture); // Neutral is black, see the comment in the shaders
renderContext.ExecuteCommandBuffer(m_Command);
return;
}
var width = hdCamera.camera.pixelWidth;

m_Material.SetFloat(Uniforms._Downsample, 1.0f / downsize);
m_Material.SetFloat(Uniforms._SampleCount, settings.sampleCount);
// Start building a command buffer.
var cmd = new CommandBuffer { name = "Ambient Occlusion" };
cmd.SetGlobalTexture(Uniforms._CameraDepthTexture, depthID);
// Note: GBuffer is automatically bind
cmd.GetTemporaryRT(Uniforms._TempTex1, width / downsize, height / downsize, 0, kFilter, kFormat, kRWMode);
cmd.SetGlobalTexture(Uniforms._MainTex, depthID);
Utilities.DrawFullScreen(cmd, m_Material, hdCamera, Uniforms._TempTex1, null, 0);
hdRP.PushFullScreenDebugTexture(cmd, Uniforms._TempTex1, hdCamera.camera, renderContext, FullScreenDebugMode.SSAOBeforeFiltering);
m_Command.GetTemporaryRT(Uniforms._TempTex1, width / downsize, height / downsize, 0, kFilter, kTempFormat, kRWMode);
Utilities.DrawFullScreen(m_Command, m_Material, hdCamera, Uniforms._TempTex1, null, 0);
hdRP.PushFullScreenDebugTexture(m_Command, Uniforms._TempTex1, hdCamera.camera, renderContext, FullScreenDebugMode.SSAOBeforeFiltering);
cmd.GetTemporaryRT(Uniforms._TempTex2, width, height, 0, kFilter, kFormat, kRWMode);
cmd.SetGlobalTexture(Uniforms._MainTex, Uniforms._TempTex1);
Utilities.DrawFullScreen(cmd, m_Material, hdCamera, Uniforms._TempTex2, null, 1);
cmd.ReleaseTemporaryRT(Uniforms._TempTex1);
m_Command.GetTemporaryRT(Uniforms._TempTex2, width, height, 0, kFilter, kTempFormat, kRWMode);
m_Command.SetGlobalTexture(Uniforms._MainTex, Uniforms._TempTex1);
Utilities.DrawFullScreen(m_Command, m_Material, hdCamera, Uniforms._TempTex2, null, 1);
m_Command.ReleaseTemporaryRT(Uniforms._TempTex1);
cmd.GetTemporaryRT(Uniforms._TempTex1, width, height, 0, kFilter, kFormat, kRWMode);
cmd.SetGlobalTexture(Uniforms._MainTex, Uniforms._TempTex2);
Utilities.DrawFullScreen(cmd, m_Material, hdCamera, Uniforms._TempTex1, null, 2);
cmd.ReleaseTemporaryRT(Uniforms._TempTex2);
m_Command.GetTemporaryRT(Uniforms._TempTex1, width, height, 0, kFilter, kTempFormat, kRWMode);
m_Command.SetGlobalTexture(Uniforms._MainTex, Uniforms._TempTex2);
Utilities.DrawFullScreen(m_Command, m_Material, hdCamera, Uniforms._TempTex1, null, 2);
m_Command.ReleaseTemporaryRT(Uniforms._TempTex2);
cmd.GetTemporaryRT(Uniforms._AOBuffer, width, height, 0, kFilter, kFormat, kRWMode);
cmd.SetGlobalTexture(Uniforms._MainTex, Uniforms._TempTex1);
Utilities.DrawFullScreen(cmd, m_Material, hdCamera, Uniforms._AOBuffer, null, 3);
cmd.ReleaseTemporaryRT(Uniforms._TempTex1);
m_Command.GetTemporaryRT(Uniforms._AOBuffer, width, height, 0, kFilter, GetAOBufferFormat(), kRWMode);
m_Command.SetGlobalTexture(Uniforms._MainTex, Uniforms._TempTex1);
Utilities.DrawFullScreen(m_Command, m_Material, hdCamera, Uniforms._AOBuffer, null, 3);
m_Command.ReleaseTemporaryRT(Uniforms._TempTex1);
cmd.SetGlobalTexture("_AmbientOcclusionTexture", Uniforms._AOBuffer);
hdRP.PushFullScreenDebugTexture(cmd, Uniforms._AOBuffer, hdCamera.camera, renderContext, FullScreenDebugMode.SSAO);
m_Command.SetGlobalTexture("_AmbientOcclusionTexture", Uniforms._AOBuffer);
hdRP.PushFullScreenDebugTexture(m_Command, Uniforms._AOBuffer, hdCamera.camera, renderContext, FullScreenDebugMode.SSAO);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
renderContext.ExecuteCommandBuffer(m_Command);
if (m_Command != null) m_Command.Dispose();
}
}
}

38
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/Resources/CommonAmbientOcclusion.hlsl


#define UNITY_HDRENDERPIPELINE_AMBIENTOCCLUSION_COMMON
#include "../../../../ShaderLibrary/Common.hlsl"
TEXTURE2D(_CameraDepthTexture);
SAMPLER2D(sampler_CameraDepthTexture);
DECLARE_GBUFFER_TEXTURE(_GBufferTexture);

return frac(52.9829189 * frac(f));
}
// Boundary check for depth sampler
// (returns a very large value if it lies out of bounds)
float CheckBounds(float2 uv, float d)
// Check if the depth value is valid.
bool CheckDepth(float rawDepth)
float ob = any(uv < 0) + any(uv > 1);
ob += (d <= 0.00001);
return rawDepth > 0.00001;
ob += (d >= 0.99999);
return rawDepth < 0.99999;
return ob * 1e8;
}
// AO/normal packed format conversion

return p.yzw * 2.0 - 1.0;
}
// Depth/normal sampling
float SampleDepth(uint2 unPositionSS)
{
float z = LOAD_TEXTURE2D(_CameraDepthTexture, unPositionSS).x;
return LinearEyeDepth(z, _ZBufferParams) + CheckBounds(float2(0.5, 0.5), z); // TODO: We should use the stencil to not affect the sky and save CheckBounds cost - also uv can't be out of bounds on xy... so put a constant here
}
half3 SampleNormal(BSDFData bsdfData)
half3 SampleNormal(uint2 unPositionSS)
float3 unused;
BSDFData bsdfData;
FETCH_GBUFFER(gbuffer, _GBufferTexture, unPositionSS);
DECODE_FROM_GBUFFER(gbuffer, 0xFFFFFFFF, bsdfData, unused);
return mul((float3x3)unity_WorldToCamera, bsdfData.normalWS);
}

return smoothstep(kGeometryCoeff, 1.0, dot(d1, d2));
}
// TODO: Test. We may need to use full matrix here to reconver VS position as it may not work in case of oblique projection (planar reflection)
// Reconstruct view-space position from UV and depth.
// p11_22 = (unity_CameraProjection._11, unity_CameraProjection._22)
// p13_31 = (unity_CameraProjection._13, unity_CameraProjection._23)
float3 ReconstructViewPos(float2 uv, float depth, float2 p11_22, float2 p13_31)
{
return float3((uv * 2.0 - 1.0 - p13_31) / p11_22 * depth, depth);
}
// Default vertex shader

8
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/Resources/Denoising.hlsl


half4 p2b = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv + delta * 3.2307692308);
#if defined(AO_DENOISE_CENTER_NORMAL)
half3 unused;
BSDFData bsdfData;
FETCH_GBUFFER(gbuffer, _GBufferTexture, posInput.unPositionSS);
DECODE_FROM_GBUFFER(gbuffer, 0xFFFFFFFF, bsdfData, unused);
half3 n0 = SampleNormal(bsdfData);
half3 n0 = SampleNormal(posInput.unPositionSS);
#else
half3 n0 = GetPackedNormal(p0);
#endif

64
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/Resources/Estimation.hlsl


half _Downsample;
int _SampleCount;
// Sample point picker
float3 PickSamplePoint(float2 uv, float index)
float3 SampleInsideHemisphere(float2 uv, half3 norm, int index)
// Uniformaly distributed points on a unit sphere http://goo.gl/X2F1Ho
// FIXEME: This was added to avoid a NVIDIA driver issue.
// vvvvvvvvvvvv
float u = frac(UVRandom(0.0, index + uv.x * 1e-10) + gn) * 2.0 - 1.0;
float theta = (UVRandom(1.0, index + uv.x * 1e-10) + gn) * TWO_PI;
float3 v = float3(SinCos(theta).yx * sqrt(1.0 - u * u), u);
// Make them distributed between [0, _Radius]
float l = sqrt((index + 1.0) / _SampleCount) * _Radius;
return v * l;
float2 u = frac(Hammersley2d(index, _SampleCount) + gn);
float3 v = SampleSphereUniform(u.x, u.y);
v *= sqrt((index + 1.0) / _SampleCount) * _Radius;
return faceforward(v, -norm, v);
// input.positionCS is SV_Position
PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw / _Downsample);
float2 uv = posInput.positionSS;
PositionInputs posInput = GetPositionInput(input.positionCS.xy / _Downsample, _ScreenSize.zw);
half3 unused;
BSDFData bsdfData;
FETCH_GBUFFER(gbuffer, _GBufferTexture, posInput.unPositionSS / _Downsample);
DECODE_FROM_GBUFFER(gbuffer, 0xFFFFFFFF, bsdfData, unused);
// Get normal, depth and view-space position of the center point.
half3 norm_o = SampleNormal(posInput.unPositionSS);
// Parameters used in coordinate conversion
float3x3 proj = (float3x3)unity_CameraProjection;
float2 p11_22 = float2(unity_CameraProjection._11, unity_CameraProjection._22);
float2 p13_31 = float2(unity_CameraProjection._13, unity_CameraProjection._23);
float depth_o_raw = LOAD_TEXTURE2D(_MainDepthTexture, posInput.unPositionSS).x;
float depth_o = LinearEyeDepth(depth_o_raw, _ZBufferParams);
// View space normal and depth
half3 norm_o = SampleNormal(bsdfData);
float depth_o = SampleDepth(posInput.unPositionSS / _Downsample);
if (!CheckDepth(depth_o_raw)) return PackAONormal(0, norm_o); // TODO: We should use the stencil to not affect the sky
// Reconstruct the view-space position.
float3 vpos_o = ReconstructViewPos(uv, depth_o, p11_22, p13_31);
float3 vpos_o = ComputeViewSpacePosition(posInput.positionSS, depth_o_raw, _InvProjMatrix);
float ao = 0.0;

// Sample point
float3 v_s1 = PickSamplePoint(uv, s);
v_s1 = faceforward(v_s1, -norm_o, v_s1);
float3 vpos_s1 = vpos_o + v_s1;
// Reproject the sample point
float3 spos_s1 = mul(proj, vpos_s1);
float2 uv_s1_01 = (spos_s1.xy / vpos_s1.z + 1.0) * 0.5;
// Depth at the sample point
float depth_s1 = SampleDepth(uint2(uv_s1_01 * _ScreenSize.xy));
// Sample inside the hemisphere defined by the normal.
float3 vpos_s1 = vpos_o + SampleInsideHemisphere(posInput.positionSS, norm_o, s);
// Relative position of the sample point
float3 vpos_s2 = ReconstructViewPos(uv_s1_01, depth_s1, p11_22, p13_31);
float3 v_s2 = vpos_s2 - vpos_o;
// Project the sample point and get the view-space position.
float2 spos_s1 = float2(dot(unity_CameraProjection[0].xyz, vpos_s1),
dot(unity_CameraProjection[1].xyz, vpos_s1));
float2 uv_s1_01 = (spos_s1 / vpos_s1.z + 1.0) * 0.5;
float depth_s1_raw = LOAD_TEXTURE2D(_MainDepthTexture, uint2(uv_s1_01 * _ScreenSize.xy)).x;
float3 vpos_s2 = ComputeViewSpacePosition(uv_s1_01, depth_s1_raw, _InvProjMatrix);
float3 v_s2 = vpos_s2 - vpos_o;
ao += a1 / a2;
ao += CheckDepth(depth_s1_raw) ? a1 / a2 : 0;
}
// Apply intensity normalization/amplifier/contrast.

4
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/ClusteredUtils.hlsl


int SnapToClusterIdxFlex(float z_in, float suggestedBase, bool logBasePerTile)
{
#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
float z = z_in;
#else
float z = -z_in;

float dist = (PositivePow(suggestedBase, (float)k) - 1.0) / (userscale * (suggestedBase - 1.0f));
res = dist + g_fNearPlane;
#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
return res;
#else
return -res;

30
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/FeatureFlags.hlsl


static const uint FeatureVariantFlags[NUM_FEATURE_VARIANTS] =
{
/* 0 */ 0 | FEATURE_FLAG_MATERIAL_MASK,
/* 1 */ FEATURE_FLAG_LIGHT_SKY | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_MATERIAL_LIT_STANDARD,
/* 2 */ FEATURE_FLAG_LIGHT_SKY | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_LIGHT_ENV | FEATURE_FLAG_MATERIAL_LIT_STANDARD,
/* 3 */ FEATURE_FLAG_LIGHT_SKY | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_LIGHT_PUNCTUAL | FEATURE_FLAG_MATERIAL_LIT_STANDARD,
/* 3 */ FEATURE_FLAG_LIGHT_SKY | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_LIGHT_PUNCTUAL | FEATURE_FLAG_LIGHT_ENV | FEATURE_FLAG_MATERIAL_LIT_STANDARD,
/* 5 */ FEATURE_FLAG_LIGHT_SKY | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_LIGHT_AREA | FEATURE_FLAG_MATERIAL_LIT_STANDARD,
/* 6 */ FEATURE_FLAG_LIGHT_SKY | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_LIGHT_AREA | FEATURE_FLAG_LIGHT_PUNCTUAL | FEATURE_FLAG_LIGHT_ENV | FEATURE_FLAG_MATERIAL_LIT_STANDARD,
/* 7 */ FEATURE_FLAG_LIGHT_MASK | FEATURE_FLAG_MATERIAL_LIT_STANDARD,
/* 8 */ FEATURE_FLAG_LIGHT_SKY | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_MATERIAL_MASK,
/* 9 */ FEATURE_FLAG_LIGHT_SKY | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_LIGHT_ENV | FEATURE_FLAG_MATERIAL_MASK,
/* 10 */ FEATURE_FLAG_LIGHT_SKY | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_LIGHT_PUNCTUAL | FEATURE_FLAG_MATERIAL_MASK,
/* 11 */ FEATURE_FLAG_LIGHT_SKY | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_LIGHT_PUNCTUAL | FEATURE_FLAG_LIGHT_ENV | FEATURE_FLAG_MATERIAL_MASK,
/* 12 */ FEATURE_FLAG_LIGHT_SKY | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_LIGHT_AREA | FEATURE_FLAG_MATERIAL_MASK,
/* 13 */ FEATURE_FLAG_LIGHT_SKY | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_LIGHT_AREA | FEATURE_FLAG_LIGHT_PUNCTUAL | FEATURE_FLAG_LIGHT_ENV | FEATURE_FLAG_MATERIAL_MASK,
/* 14 */ FEATURE_FLAG_LIGHT_MASK | FEATURE_FLAG_MATERIAL_MASK,
/* 0 */ 0 | MATERIALFEATUREFLAGS_MASK,
/* 1 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 2 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 3 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 3 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 5 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 6 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 7 */ LIGHTFEATUREFLAGS_MASK | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 8 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | MATERIALFEATUREFLAGS_MASK,
/* 9 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_MASK,
/* 10 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_MASK,
/* 11 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_MASK,
/* 12 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_MASK,
/* 13 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_MASK,
/* 14 */ LIGHTFEATUREFLAGS_MASK | MATERIALFEATUREFLAGS_MASK,
/* 15 */ 0xFFFFFFFF // shouldn't be needed
};

4
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/LightingConvexHullUtils.hlsl


p0 = center + (vA + vB - vC); // center + vA is center of face when scaleXY is 1.0
float3 vNout = cross( vB2, 0.5*(vA-vA2) - vC );
#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
vNout = -vNout;
#endif

#endif
// enlarge sphere so it overlaps the center of the tile assuming it overlaps the tile to begin with.
#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
float sphRadius = sphRadiusIn + (sphCen.z+offs)*halfTileSizeAtZDistOne;
#else
float sphRadius = sphRadiusIn - (sphCen.z-offs)*halfTileSizeAtZDistOne;

150
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs


}
[GenerateHLSL]
public class LightFeatureFlags
public enum LightFeatureFlags
public static uint FEATURE_FLAG_LIGHT_PUNCTUAL = 1 << 0;
public static uint FEATURE_FLAG_LIGHT_AREA = 1 << 1;
public static uint FEATURE_FLAG_LIGHT_DIRECTIONAL = 1 << 2;
public static uint FEATURE_FLAG_LIGHT_PROJECTOR = 1 << 3;
public static uint FEATURE_FLAG_LIGHT_ENV = 1 << 4;
public static uint FEATURE_FLAG_LIGHT_SKY = 1 << 5;
public static uint FEATURE_FLAG_LIGHT_MASK = 0xFFF;
public static uint FEATURE_FLAG_MATERIAL_MASK = 0xF000; // don't use all bits just to be safe from signed and/or float conversions :/
Punctual = 1 << 0,
Area = 1 << 1,
Directional = 1 << 2,
Projector = 1 << 3,
Env = 1 << 4,
Sky = 1 << 5
public static int MAX_NR_LIGHTS_PER_CAMERA = 1024;
public static int MAX_NR_BIGTILE_LIGHTS_PLUSONE = 512; // may be overkill but the footprint is 2 bits per pixel using uint16.
public static float VIEWPORT_SCALE_Z = 1.0f;
public static int s_MaxNrLightsPerCamera = 1024;
public static int s_MaxNrBigTileLightsPlusOne = 512; // may be overkill but the footprint is 2 bits per pixel using uint16.
public static float s_ViewportScaleZ = 1.0f;
public static int USE_LEFTHAND_CAMERASPACE = 1;
public static int s_UseLeftHandCameraSpace = 1;
public static int TILE_SIZE_FPTL = 16;
public static int TILE_SIZE_CLUSTERED = 32;
public static int s_TileSizeFptl = 16;
public static int s_TileSizeClustered = 32;
// flags
public static int IS_CIRCULAR_SPOT_SHAPE = 1;
public static int HAS_COOKIE_TEXTURE = 2;
public static int IS_BOX_PROJECTED = 4;
public static int HAS_SHADOW = 8;
// feature variants
public static int s_NumFeatureVariants = 16;
// feature variants
public static int NUM_FEATURE_VARIANTS = 16;
public static uint LIGHTFEATUREFLAGS_MASK = 0xFFF;
public static uint MATERIALFEATUREFLAGS_MASK = 0xF000; // don't use all bits just to be safe from signed and/or float conversions :/
}
[GenerateHLSL]

static int s_shadeOpaqueDirectFptlKernel;
static int s_shadeOpaqueDirectClusteredDebugDisplayKernel;
static int s_shadeOpaqueDirectFptlDebugDisplayKernel;
static int[] s_shadeOpaqueIndirectClusteredKernels = new int[LightDefinitions.NUM_FEATURE_VARIANTS];
static int[] s_shadeOpaqueIndirectFptlKernels = new int[LightDefinitions.NUM_FEATURE_VARIANTS];
static int[] s_shadeOpaqueIndirectClusteredKernels = new int[LightDefinitions.s_NumFeatureVariants];
static int[] s_shadeOpaqueIndirectFptlKernels = new int[LightDefinitions.s_NumFeatureVariants];
static ComputeBuffer s_LightVolumeDataBuffer = null;
static ComputeBuffer s_ConvexBoundsBuffer = null;

Light m_CurrentSunLight = null;
public Light GetCurrentSunLight() { return m_CurrentSunLight; }
// For displaying shadow map
Material m_DebugDisplayShadowMap;
// shadow related stuff
FrameId m_FrameId = new FrameId();
ShadowSetup m_ShadowSetup; // doesn't actually have to reside here, it would be enough to pass the IShadowManager in from the outside

int GetNumTileFtplX(Camera camera)
{
return (camera.pixelWidth + (LightDefinitions.TILE_SIZE_FPTL - 1)) / LightDefinitions.TILE_SIZE_FPTL;
return (camera.pixelWidth + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
return (camera.pixelHeight + (LightDefinitions.TILE_SIZE_FPTL - 1)) / LightDefinitions.TILE_SIZE_FPTL;
return (camera.pixelHeight + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
return (camera.pixelWidth + (LightDefinitions.TILE_SIZE_CLUSTERED - 1)) / LightDefinitions.TILE_SIZE_CLUSTERED;
return (camera.pixelWidth + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
return (camera.pixelHeight + (LightDefinitions.TILE_SIZE_CLUSTERED - 1)) / LightDefinitions.TILE_SIZE_CLUSTERED;
return (camera.pixelHeight + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
}
bool GetFeatureVariantsEnabled()

s_AABBBoundsBuffer = new ComputeBuffer(2 * k_MaxLightsOnScreen, 3 * sizeof(float));
s_ConvexBoundsBuffer = new ComputeBuffer(k_MaxLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(SFiniteLightBound)));
s_LightVolumeDataBuffer = new ComputeBuffer(k_MaxLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(LightVolumeData)));
s_DispatchIndirectBuffer = new ComputeBuffer(LightDefinitions.NUM_FEATURE_VARIANTS * 3, sizeof(uint), ComputeBufferType.IndirectArguments);
s_DispatchIndirectBuffer = new ComputeBuffer(LightDefinitions.s_NumFeatureVariants * 3, sizeof(uint), ComputeBufferType.IndirectArguments);
if (m_TileSettings.enableClustered)
{

s_shadeOpaqueDirectClusteredDebugDisplayKernel = shadeOpaqueShader.FindKernel("ShadeOpaque_Direct_Clustered_DebugDisplay");
s_shadeOpaqueDirectFptlDebugDisplayKernel = shadeOpaqueShader.FindKernel("ShadeOpaque_Direct_Fptl_DebugDisplay");
for (int variant = 0; variant < LightDefinitions.NUM_FEATURE_VARIANTS; variant++)
for (int variant = 0; variant < LightDefinitions.s_NumFeatureVariants; variant++)
{
s_shadeOpaqueIndirectClusteredKernels[variant] = shadeOpaqueShader.FindKernel("ShadeOpaque_Indirect_Clustered_Variant" + variant);
s_shadeOpaqueIndirectFptlKernels[variant] = shadeOpaqueShader.FindKernel("ShadeOpaque_Indirect_Fptl_Variant" + variant);

m_SingleDeferredMaterialMRT.SetInt("_DstBlend", (int)BlendMode.Zero);
m_DebugViewTilesMaterial = Utilities.CreateEngineMaterial(m_Resources.debugViewTilesShader);
m_DebugDisplayShadowMap = Utilities.CreateEngineMaterial(m_Resources.debugDisplayShadowMapShader);
m_DefaultTexture2DArray = new Texture2DArray(1, 1, 1, TextureFormat.ARGB32, false);
m_DefaultTexture2DArray.SetPixels32(new Color32[1] { new Color32(128, 128, 128, 128) }, 0);

Utilities.Destroy(m_SingleDeferredMaterialSRT);
Utilities.Destroy(m_SingleDeferredMaterialMRT);
Utilities.Destroy(m_DebugDisplayShadowMap);
Utilities.Destroy(s_DefaultAdditionalLightDataGameObject);
s_DefaultAdditionalLightDataGameObject = null;
s_DefaultAdditionalLightData = null;

public void AllocResolutionDependentBuffers(int width, int height)
{
var nrTilesX = (width + LightDefinitions.TILE_SIZE_FPTL - 1) / LightDefinitions.TILE_SIZE_FPTL;
var nrTilesY = (height + LightDefinitions.TILE_SIZE_FPTL - 1) / LightDefinitions.TILE_SIZE_FPTL;
var nrTilesX = (width + LightDefinitions.s_TileSizeFptl - 1) / LightDefinitions.s_TileSizeFptl;
var nrTilesY = (height + LightDefinitions.s_TileSizeFptl - 1) / LightDefinitions.s_TileSizeFptl;
s_TileList = new ComputeBuffer((int)LightDefinitions.NUM_FEATURE_VARIANTS * nrTiles, sizeof(uint));
s_TileList = new ComputeBuffer((int)LightDefinitions.s_NumFeatureVariants * nrTiles, sizeof(uint));
var nrClustersX = (width + LightDefinitions.TILE_SIZE_CLUSTERED - 1) / LightDefinitions.TILE_SIZE_CLUSTERED;
var nrClustersY = (height + LightDefinitions.TILE_SIZE_CLUSTERED - 1) / LightDefinitions.TILE_SIZE_CLUSTERED;
var nrClustersX = (width + LightDefinitions.s_TileSizeClustered - 1) / LightDefinitions.s_TileSizeClustered;
var nrClustersY = (height + LightDefinitions.s_TileSizeClustered - 1) / LightDefinitions.s_TileSizeClustered;
var nrClusterTiles = nrClustersX * nrClustersY;
s_PerVoxelOffset = new ComputeBuffer((int)LightCategory.Count * (1 << k_Log2NumClusters) * nrClusterTiles, sizeof(uint));

var nrBigTilesX = (width + 63) / 64;
var nrBigTilesY = (height + 63) / 64;
var nrBigTiles = nrBigTilesX * nrBigTilesY;
s_BigTileLightList = new ComputeBuffer(LightDefinitions.MAX_NR_BIGTILE_LIGHTS_PLUSONE * nrBigTiles, sizeof(uint));
s_BigTileLightList = new ComputeBuffer(LightDefinitions.s_MaxNrBigTileLightsPlusOne * nrBigTiles, sizeof(uint));
}
}

bool isLeftHand = ((int)LightDefinitions.USE_LEFTHAND_CAMERASPACE) != 0;
bool isLeftHand = ((int)LightDefinitions.s_UseLeftHandCameraSpace) != 0;
if (isLeftHand) flip.SetColumn(2, new Vector4(0.0f, 0.0f, -1.0f, 0.0f));
return flip;
}

lightVolumeData.lightPos = worldToView.MultiplyPoint(lightPos);
lightVolumeData.radiusSq = range * range;
lightVolumeData.cotan = cota;
lightVolumeData.featureFlags = (gpuLightType == GPULightType.Spot) ? LightFeatureFlags.FEATURE_FLAG_LIGHT_PUNCTUAL
: LightFeatureFlags.FEATURE_FLAG_LIGHT_PROJECTOR;
lightVolumeData.featureFlags = (gpuLightType == GPULightType.Spot) ? (uint)LightFeatureFlags.Punctual
: (uint)LightFeatureFlags.Projector;
}
else if (gpuLightType == GPULightType.Point)
{

lightVolumeData.lightAxisZ = vz;
lightVolumeData.lightPos = bound.center;
lightVolumeData.radiusSq = range * range;
lightVolumeData.featureFlags = LightFeatureFlags.FEATURE_FLAG_LIGHT_PUNCTUAL;
lightVolumeData.featureFlags = (uint)LightFeatureFlags.Punctual;
}
else if (gpuLightType == GPULightType.Rectangle)
{

lightVolumeData.lightAxisZ = zAxisVS;
lightVolumeData.boxInnerDist = dimensions;
lightVolumeData.boxInvRange.Set(1e5f, 1e5f, 1e5f);
lightVolumeData.featureFlags = LightFeatureFlags.FEATURE_FLAG_LIGHT_AREA;
lightVolumeData.featureFlags = (uint)LightFeatureFlags.Area;
}
else if (gpuLightType == GPULightType.Line)
{

lightVolumeData.lightAxisZ = zAxisVS;
lightVolumeData.boxInnerDist = new Vector3(lightData.size.x * 0.5f, 0.01f, 0.01f);
lightVolumeData.boxInvRange.Set(1.0f / radius, 1.0f / radius, 1.0f / radius);
lightVolumeData.featureFlags = LightFeatureFlags.FEATURE_FLAG_LIGHT_AREA;
lightVolumeData.featureFlags = (uint)LightFeatureFlags.Area;
}
else if (gpuLightType == GPULightType.ProjectorOrtho)
{

lightVolumeData.lightAxisZ = zAxisVS;
lightVolumeData.boxInnerDist = halfDims; // No idea what this is. Document your code
lightVolumeData.boxInvRange.Set(1.0f / halfDims.x, 1.0f / halfDims.y, 1.0f / halfDims.z); // No idea what this is. Document your code
lightVolumeData.featureFlags = LightFeatureFlags.FEATURE_FLAG_LIGHT_PROJECTOR;
lightVolumeData.featureFlags = (uint)LightFeatureFlags.Projector;
}
else
{

lightVolumeData.lightCategory = (uint)LightCategory.Env;
lightVolumeData.lightVolume = (uint)lightVolumeType;
lightVolumeData.featureFlags = LightFeatureFlags.FEATURE_FLAG_LIGHT_ENV;
lightVolumeData.featureFlags = (uint)LightFeatureFlags.Env;
lightVolumeData.lightPos = Cw;
lightVolumeData.lightAxisX = vx;

public int GetCurrentShadowCount()
{
return m_ShadowRequests.Count;
}
public int GetShadowAtlasCount()
{
return (int)m_ShadowMgr.GetShadowMapCount();
}
public void UpdateCullingParameters(ref CullingParameters cullingParams)

uint baseFeatureFlags = 0;
if (m_lightList.directionalLights.Count > 0)
{
baseFeatureFlags |= LightFeatureFlags.FEATURE_FLAG_LIGHT_DIRECTIONAL;
baseFeatureFlags |= (uint)LightFeatureFlags.Directional;
baseFeatureFlags |= LightFeatureFlags.FEATURE_FLAG_LIGHT_SKY;
baseFeatureFlags |= (uint)LightFeatureFlags.Sky;
baseFeatureFlags |= LightFeatureFlags.FEATURE_FLAG_MATERIAL_MASK;
baseFeatureFlags |= LightDefinitions.MATERIALFEATUREFLAGS_MASK;
}
cmd.SetComputeIntParam(buildPerTileLightListShader, "g_BaseFeatureFlags", (int)baseFeatureFlags);
cmd.SetComputeBufferParam(buildPerTileLightListShader, s_GenListPerTileKernel, "g_TileFeatureFlags", s_TileFeatureFlags);

if (!m_TileSettings.enableComputeLightVariants)
{
buildMaterialFlagsKernel = s_BuildMaterialFlagsWriteKernel;
baseFeatureFlags |= LightFeatureFlags.FEATURE_FLAG_LIGHT_MASK;
baseFeatureFlags |= LightDefinitions.LIGHTFEATUREFLAGS_MASK;
}
cmd.SetComputeIntParam(buildMaterialFlagsShader, "g_BaseFeatureFlags", (int)baseFeatureFlags);

int numVariants = 1;
if (enableFeatureVariants)
numVariants = LightDefinitions.NUM_FEATURE_VARIANTS;
numVariants = LightDefinitions.s_NumFeatureVariants;
for (int variant = 0; variant < numVariants; variant++)
{

public void RenderDebugOverlay(Camera camera, ScriptableRenderContext renderContext, DebugDisplaySettings debugDisplaySettings, ref float x, ref float y, float overlaySize, float width)
{
LightingDebugSettings lightingDebug = debugDisplaySettings.lightingDebugSettings;
if (lightingDebug.shadowDebugMode != ShadowMapDebugMode.None)
using (new Utilities.ProfilingSample("Display Shadows", renderContext))
m_ShadowMgr.DisplayShadows(renderContext, m_DebugDisplayShadowMap, (int)lightingDebug.shadowMapIndex, x, y, overlaySize, overlaySize);
Utilities.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, camera.pixelWidth);
int index = (int)lightingDebug.shadowMapIndex;
// TODO: @Julien exchange shadowmapIndex by lightIndex and draw all slide like below
/*
for (int slice = 0; slice < shadowLight.shadowSliceCount; ++slice)
#if UNITY_EDITOR
if(lightingDebug.shadowDebugUseSelection)
ShadowSliceData sliceData = m_ShadowsResult.shadowSlices[shadowLight.shadowSliceIndex + slice];
index = -1;
if (UnityEditor.Selection.activeObject is GameObject)
{
GameObject go = UnityEditor.Selection.activeObject as GameObject;
Light light = go.GetComponent<Light>();
if (light != null)
{
index = m_ShadowMgr.GetShadowRequestIndex(light);
}
}
}
#endif
Vector4 texcoordScaleBias = new Vector4((float)sliceData.shadowResolution / m_Owner.shadowSettings.shadowAtlasWidth,
(float)sliceData.shadowResolution / m_Owner.shadowSettings.shadowAtlasHeight,
(float)sliceData.atlasX / m_Owner.shadowSettings.shadowAtlasWidth,
(float)sliceData.atlasY / m_Owner.shadowSettings.shadowAtlasHeight);
propertyBlock.SetVector("_TextureScaleBias", texcoordScaleBias);
debugCB.SetViewport(new Rect(x, y, overlaySize, overlaySize));
debugCB.DrawProcedural(Matrix4x4.identity, m_DebugDisplayShadowMap, 0, MeshTopology.Triangles, 3, 1, propertyBlock);
Utilities.NextOverlayCoord(ref x, ref y, overlaySize, camera.pixelWidth);
if(index != -1)
{
uint faceCount = m_ShadowMgr.GetShadowRequestFaceCount((uint)index);
for (uint i = 0; i < faceCount; ++i)
{
m_ShadowMgr.DisplayShadow(renderContext, index, i, x, y, overlaySize, overlaySize);
Utilities.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, camera.pixelWidth);
}
*/
m_ShadowMgr.DisplayShadows(renderContext, m_DebugDisplayShadowMap, -1, x, y, overlaySize, overlaySize);
m_ShadowMgr.DisplayShadowMap(renderContext, lightingDebug.shadowAtlasIndex, 0, x, y, overlaySize, overlaySize);
Utilities.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, camera.pixelWidth);
}
}

24
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs.hlsl


//
// UnityEngine.Experimental.Rendering.HDPipeline.TilePass.LightFeatureFlags: static fields
//
#define FEATURE_FLAG_LIGHT_PUNCTUAL (1)
#define FEATURE_FLAG_LIGHT_AREA (2)
#define FEATURE_FLAG_LIGHT_DIRECTIONAL (4)
#define FEATURE_FLAG_LIGHT_PROJECTOR (8)
#define FEATURE_FLAG_LIGHT_ENV (16)
#define FEATURE_FLAG_LIGHT_SKY (32)
#define FEATURE_FLAG_LIGHT_MASK (4095)
#define FEATURE_FLAG_MATERIAL_MASK (61440)
#define LIGHTFEATUREFLAGS_PUNCTUAL (1)
#define LIGHTFEATUREFLAGS_AREA (2)
#define LIGHTFEATUREFLAGS_DIRECTIONAL (4)
#define LIGHTFEATUREFLAGS_PROJECTOR (8)
#define LIGHTFEATUREFLAGS_ENV (16)
#define LIGHTFEATUREFLAGS_SKY (32)
#define MAX_NR_BIGTILE_LIGHTS_PLUSONE (512)
#define MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE (512)
#define USE_LEFTHAND_CAMERASPACE (1)
#define USE_LEFT_HAND_CAMERA_SPACE (1)
#define IS_CIRCULAR_SPOT_SHAPE (1)
#define HAS_COOKIE_TEXTURE (2)
#define IS_BOX_PROJECTED (4)
#define HAS_SHADOW (8)
#define LIGHTFEATUREFLAGS_MASK (4095)
#define MATERIALFEATUREFLAGS_MASK (61440)
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.TilePass.SFiniteLightBound
// PackingRules = Exact

14
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePassLoop.hlsl


uint i = 0; // Declare once to avoid the D3D11 compiler warning.
#ifdef PROCESS_DIRECTIONAL_LIGHT
if(featureFlags & FEATURE_FLAG_LIGHT_DIRECTIONAL)
if(featureFlags & LIGHTFEATUREFLAGS_DIRECTIONAL)
{
for(i = 0; i < _DirectionalLightCount; ++i)
{

#endif
#ifdef PROCESS_PUNCTUAL_LIGHT
if(featureFlags & FEATURE_FLAG_LIGHT_PUNCTUAL)
if(featureFlags & LIGHTFEATUREFLAGS_PUNCTUAL)
{
// TODO: Convert the for loop below to a while on each type as we know we are sorted!
uint punctualLightStart;

#endif
#ifdef PROCESS_AREA_LIGHT
if(featureFlags & FEATURE_FLAG_LIGHT_AREA)
if(featureFlags & LIGHTFEATUREFLAGS_AREA)
{
// TODO: Convert the for loop below to a while on each type as we know we are sorted!
uint areaLightStart;

#endif
#ifdef PROCESS_PROJECTOR_LIGHT
if(featureFlags & FEATURE_FLAG_LIGHT_PROJECTOR)
if(featureFlags & LIGHTFEATUREFLAGS_PROJECTOR)
{
// TODO: Convert the for loop below to a while on each type as we know we are sorted!
uint projectorLightStart;

float3 iblSpecularLighting = float3(0.0, 0.0, 0.0);
// Only apply sky IBL if the sky texture is available.
if(featureFlags & FEATURE_FLAG_LIGHT_SKY)
if(featureFlags & LIGHTFEATUREFLAGS_SKY)
{
if(_EnvLightSkyEnabled)
{

}
if(featureFlags & FEATURE_FLAG_LIGHT_ENV)
if(featureFlags & LIGHTFEATUREFLAGS_ENV)
{
uint envLightStart;
uint envLightCount;

out float3 diffuseLighting,
out float3 specularLighting)
{
LightLoopContext context;
LightLoopContext context;
// Note: When we ImageLoad outside of texture size, the value returned by Load is 0 (Note: On Metal maybe it clamp to value of texture which is also fine)
// We use this property to have a neutral value for AO that doesn't consume a sampler and work also with compute shader (i.e use ImageLoad)
// We store inverse AO so neutral is black. So either we sample inside or outside the texture it return 0 in case of neutral

14
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/lightlistbuild-bigtile.compute


#define EXACT_EDGE_TESTS
#define PERFORM_SPHERICAL_INTERSECTION_TESTS
#define MAX_NR_BIGTILE_LIGHTS (MAX_NR_BIGTILE_LIGHTS_PLUSONE-1)
#define MAX_NR_BIGTILE_LIGHTS (MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE-1)
uniform int g_iNrVisibLights;

// 2kB (room for roughly 30 wavefronts)
groupshared unsigned int lightsListLDS[MAX_NR_BIGTILE_LIGHTS_PLUSONE];
groupshared unsigned int lightsListLDS[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE];
groupshared uint lightOffs;

float fSy = g_mScrProjection[1].y;
float fCy = g_mScrProjection[1].z;
#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
return fLinDepth*float3( ((v2ScrPos.x-fCx)/fSx), ((v2ScrPos.y-fCy)/fSy), 1.0 );
#else
return fLinDepth*float3( -((v2ScrPos.x+fCx)/fSx), -((v2ScrPos.y+fCy)/fSy), 1.0 );

// sort lights
SORTLIST(lightsListLDS, iNrCoarseLights, MAX_NR_BIGTILE_LIGHTS_PLUSONE, t, NR_THREADS);
SORTLIST(lightsListLDS, iNrCoarseLights, MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE, t, NR_THREADS);
if(t==0) lightOffs = 0;
GroupMemoryBarrierWithGroupSync();

int offs = tileIDX.y*nrBigTilesX + tileIDX.x;
for(i=t; i<(iNrCoarseLights+1); i+=NR_THREADS)
g_vLightList[MAX_NR_BIGTILE_LIGHTS_PLUSONE*offs + i] = i==0 ? iNrCoarseLights : lightsListLDS[max(i-1, 0)];
g_vLightList[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE*offs + i] = i==0 ? iNrCoarseLights : lightsListLDS[max(i-1, 0)];
}

#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
float3 V = GetViewPosFromLinDepth( screenCoordinate, 1.0);
#else
float3 V = GetViewPosFromLinDepth( screenCoordinate, -1.0);

float x = (i&1)==0 ? viTilLL.x : viTilUR.x;
float y = (i&2)==0 ? viTilLL.y : viTilUR.y;
float z = (i&4)==0 ? g_fNearPlane : fTileFarPlane;
#if !USE_LEFTHAND_CAMERASPACE
#if !USE_LEFT_HAND_CAMERA_SPACE
z = -z;
#endif
return GetViewPosFromLinDepth( float2(x, y), z);

12
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/lightlistbuild-clustered.compute


float fSy = g_mScrProjection[1].y;
float fCy = g_mScrProjection[1].z;
#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
return fLinDepth*float3( ((v2ScrPos.x-fCx)/fSx), ((v2ScrPos.y-fCy)/fSy), 1.0 );
#else
return fLinDepth*float3( -((v2ScrPos.x+fCx)/fSx), -((v2ScrPos.y+fCy)/fSy), 1.0 );

int NrBigTilesX = (nrTilesX+((1<<log2BigTileToClustTileRatio)-1))>>log2BigTileToClustTileRatio;
const int bigTileIdx = (tileIDX.y>>log2BigTileToClustTileRatio)*NrBigTilesX + (tileIDX.x>>log2BigTileToClustTileRatio); // map the idx to 64x64 tiles
int nrBigTileLights = g_vBigTileLightList[MAX_NR_BIGTILE_LIGHTS_PLUSONE*bigTileIdx+0];
int nrBigTileLights = g_vBigTileLightList[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE*bigTileIdx+0];
int l = g_vBigTileLightList[MAX_NR_BIGTILE_LIGHTS_PLUSONE*bigTileIdx+l0+1];
int l = g_vBigTileLightList[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE*bigTileIdx+l0+1];
#else
for(int l=(int) t; l<(int) g_iNrVisibLights; l += NR_THREADS)
{

#ifdef ENABLE_DEPTH_TEXTURE_BACKPLANE
#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
float fTileFarPlane = GetLinearDepth(dpt_ma);
#else
float fTileFarPlane = -GetLinearDepth(dpt_ma);

#ifdef PERFORM_SPHERICAL_INTERSECTION_TESTS
int SphericalIntersectionTests(uint threadID, int iNrCoarseLights, float2 screenCoordinate)
{
#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
float3 V = GetViewPosFromLinDepth( screenCoordinate, 1.0);
#else
float3 V = GetViewPosFromLinDepth( screenCoordinate, -1.0);

float x = (i&1)==0 ? viTilLL.x : viTilUR.x;
float y = (i&2)==0 ? viTilLL.y : viTilUR.y;
float z = (i&4)==0 ? g_fNearPlane : fTileFarPlane;
#if !USE_LEFTHAND_CAMERASPACE
#if !USE_LEFT_HAND_CAMERA_SPACE
z = -z;
#endif
return GetViewPosFromLinDepth( float2(x, y), z);

10
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/lightlistbuild.compute


float fSy = g_mScrProjection[1].y;
float fCy = g_mScrProjection[1].z;
#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
return fLinDepth*float3( ((v2ScrPos.x-fCx)/fSx), ((v2ScrPos.y-fCy)/fSy), 1.0 );
#else
return fLinDepth*float3( -((v2ScrPos.x+fCx)/fSx), -((v2ScrPos.y+fCy)/fSy), 1.0 );

int NrBigTilesX = (nrTilesX+((1<<log2BigTileToTileRatio)-1))>>log2BigTileToTileRatio;
const int bigTileIdx = (tileIDX.y>>log2BigTileToTileRatio)*NrBigTilesX + (tileIDX.x>>log2BigTileToTileRatio); // map the idx to 64x64 tiles
int nrBigTileLights = g_vBigTileLightList[MAX_NR_BIGTILE_LIGHTS_PLUSONE*bigTileIdx+0];
int nrBigTileLights = g_vBigTileLightList[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE*bigTileIdx+0];
int l = g_vBigTileLightList[MAX_NR_BIGTILE_LIGHTS_PLUSONE*bigTileIdx+l0+1];
int l = g_vBigTileLightList[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE*bigTileIdx+l0+1];
#else
for(int l=(int) t; l<(int) g_iNrVisibLights; l += NR_THREADS)
{

uint featureFlags = ldsFeatureFlags | g_BaseFeatureFlags;
if(ldsZMax < ldsZMin) // is background pixel
{
featureFlags &= ~(FEATURE_FLAG_LIGHT_PUNCTUAL | FEATURE_FLAG_LIGHT_AREA | FEATURE_FLAG_LIGHT_DIRECTIONAL | FEATURE_FLAG_LIGHT_ENV | 0xFFFFF); // list of features that are not enabled on background
featureFlags &= ~(LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_AREA | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | 0xFFFFF); // list of features that are not enabled on background
}
g_TileFeatureFlags[tileIDX.y * nrTilesX + tileIDX.x] = featureFlags;

GroupMemoryBarrierWithGroupSync();
#endif
#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
float3 V = GetViewPosFromLinDepth( screenCoordinate, 1.0);
#else
float3 V = GetViewPosFromLinDepth( screenCoordinate, -1.0);

4
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/scrbound.compute


vMax.xy = bMa ? min(vMax.xy, vMa) : vMax.xy;
}
#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
if((center.z-radius)>0.0)
{
float4 vPosF = mul(g_mProjection, float4(0,0,center.z-radius,1));

float4 planeY = EvalPlanePair(validY, float2(pos_view_space.y, pos_view_space.z), r);
#if USE_LEFTHAND_CAMERASPACE
#if USE_LEFT_HAND_CAMERA_SPACE
planeX = planeX.zwxy; // need to swap left/right and top/bottom planes when using left hand system
planeY = planeY.zwxy;
#endif

8
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs.hlsl


#ifndef BUILTINDATA_CS_HLSL
#define BUILTINDATA_CS_HLSL
//
// UnityEngine.Experimental.Rendering.HDPipeline.Builtin.BuiltinData: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Builtin+BuiltinData: static fields
//
#define DEBUGVIEW_BUILTIN_BUILTINDATA_OPACITY (100)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_BAKE_DIFFUSE_LIGHTING (101)

#define DEBUGVIEW_BUILTIN_BUILTINDATA_DEPTH_OFFSET (107)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Builtin.LightTransportData: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Builtin+LightTransportData: static fields
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Builtin.BuiltinData
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Builtin+BuiltinData
// PackingRules = Exact
struct BuiltinData
{

float depthOffset;
};
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Builtin.LightTransportData
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Builtin+LightTransportData
// PackingRules = Exact
struct LightTransportData
{

10
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs


};
[GenerateHLSL]
public class MaterialFeatureFlags
public enum MaterialFeatureFlags
public static uint FEATURE_FLAG_MATERIAL_LIT_SSS = 1 << 12;
public static uint FEATURE_FLAG_MATERIAL_LIT_STANDARD = 1 << 13;
public static uint FEATURE_FLAG_MATERIAL_LIT_SPECULAR = 1 << 14;
public static uint FEATURE_FLAG_MATERIAL_LIT_ANISO = 1 << 15;
LitSSS = 1 << 12,
LitStandard = 1 << 13,
LitSpecular = 1 << 14,
LitAniso = 1 << 15
}
//-----------------------------------------------------------------------------

24
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs.hlsl


#ifndef LIT_CS_HLSL
#define LIT_CS_HLSL
//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit.MaterialId: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+MaterialId: static fields
//
#define MATERIALID_LIT_SSS (0)
#define MATERIALID_LIT_STANDARD (1)

//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit.MaterialFeatureFlags: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+MaterialFeatureFlags: static fields
#define FEATURE_FLAG_MATERIAL_LIT_SSS (4096)
#define FEATURE_FLAG_MATERIAL_LIT_STANDARD (8192)
#define FEATURE_FLAG_MATERIAL_LIT_SPECULAR (16384)
#define FEATURE_FLAG_MATERIAL_LIT_ANISO (32768)
#define MATERIALFEATUREFLAGS_LIT_SSS (4096)
#define MATERIALFEATUREFLAGS_LIT_STANDARD (8192)
#define MATERIALFEATUREFLAGS_LIT_SPECULAR (16384)
#define MATERIALFEATUREFLAGS_LIT_ANISO (32768)
// UnityEngine.Experimental.Rendering.HDPipeline.Lit.SurfaceData: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+SurfaceData: static fields
//
#define DEBUGVIEW_LIT_SURFACEDATA_BASE_COLOR (1000)
#define DEBUGVIEW_LIT_SURFACEDATA_SPECULAR_OCCLUSION (1001)

#define DEBUGVIEW_LIT_SURFACEDATA_SPECULAR_COLOR (1013)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit.TransmissionType: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+TransmissionType: static fields
//
#define TRANSMISSIONTYPE_NONE (0)
#define TRANSMISSIONTYPE_REGULAR (1)

// UnityEngine.Experimental.Rendering.HDPipeline.Lit.BSDFData: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+BSDFData: static fields
//
#define DEBUGVIEW_LIT_BSDFDATA_DIFFUSE_COLOR (1030)
#define DEBUGVIEW_LIT_BSDFDATA_FRESNEL0 (1031)

#define DEBUGVIEW_LIT_BSDFDATA_TRANSMITTANCE (1047)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit.GBufferMaterial: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+GBufferMaterial: static fields
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Lit.SurfaceData
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Lit+SurfaceData
// PackingRules = Exact
struct SurfaceData
{

float3 specularColor;
};
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Lit.BSDFData
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Lit+BSDFData
// PackingRules = Exact
struct BSDFData
{

14
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl


bsdfData.roughness = PerceptualRoughnessToRoughness(bsdfData.perceptualRoughness);
int supportsStandard = (featureFlags & (FEATURE_FLAG_MATERIAL_LIT_STANDARD | FEATURE_FLAG_MATERIAL_LIT_ANISO)) != 0;
int supportsSSS = (featureFlags & (FEATURE_FLAG_MATERIAL_LIT_SSS)) != 0;
int supportsSpecular = (featureFlags & (FEATURE_FLAG_MATERIAL_LIT_SPECULAR)) != 0;
int supportsStandard = (featureFlags & (MATERIALFEATUREFLAGS_LIT_STANDARD | MATERIALFEATUREFLAGS_LIT_ANISO)) != 0;
int supportsSSS = (featureFlags & (MATERIALFEATUREFLAGS_LIT_SSS)) != 0;
int supportsSpecular = (featureFlags & (MATERIALFEATUREFLAGS_LIT_SPECULAR)) != 0;
if(supportsStandard + supportsSSS + supportsSpecular > 1)
{

float3 tangentWS = UnpackNormalOctEncode(float2(inGBuffer2.rg * 2.0 - 1.0));
FillMaterialIdStandardData(baseColor, specular, metallic, bsdfData.roughness, bsdfData.normalWS, tangentWS, anisotropy, bsdfData);
if ((featureFlags & FEATURE_FLAG_MATERIAL_LIT_ANISO) && (featureFlags & FEATURE_FLAG_MATERIAL_LIT_STANDARD) == 0 || anisotropy > 0)
if ((featureFlags & MATERIALFEATUREFLAGS_LIT_ANISO) && (featureFlags & MATERIALFEATUREFLAGS_LIT_STANDARD) == 0 || anisotropy > 0)
{
bsdfData.materialId = MATERIALID_LIT_ANISO;
}

uint featureFlags = 0;
if (materialId == MATERIALID_LIT_STANDARD)
{
featureFlags |= (anisotropy > 0) ? FEATURE_FLAG_MATERIAL_LIT_ANISO : FEATURE_FLAG_MATERIAL_LIT_STANDARD;
featureFlags |= (anisotropy > 0) ? MATERIALFEATUREFLAGS_LIT_ANISO : MATERIALFEATUREFLAGS_LIT_STANDARD;
featureFlags |= FEATURE_FLAG_MATERIAL_LIT_SSS;
featureFlags |= MATERIALFEATUREFLAGS_LIT_SSS;
featureFlags |= FEATURE_FLAG_MATERIAL_LIT_SPECULAR;
featureFlags |= MATERIALFEATUREFLAGS_LIT_SPECULAR;
}
return featureFlags;
}

4
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CombineSubsurfaceScattering.shader


#pragma fragment Frag
#define SSS_PASS 1
#define SSS_BILATERAL 1
#define SSS_DEBUG 0
#define MILLIMETERS_PER_METER 1000

// Computes F(x)/P(x), s.t. x = sqrt(r^2 + t^2).
float3 ComputeBilateralWeight(float3 S, float r, float t, float rcpDistScale, float rcpPdf)
{
#if (SSS_BILATERAL == 0)
t = 0;
#endif
// Reducing the integration distance is equivalent to stretching the integration axis.
float3 valX = KernelValCircle(sqrt(r * r + t * t) * rcpDistScale, S);

8
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.cs.hlsl


#ifndef UNLIT_CS_HLSL
#define UNLIT_CS_HLSL
//
// UnityEngine.Experimental.Rendering.HDPipeline.Unlit.SurfaceData: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Unlit+SurfaceData: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Unlit.BSDFData: static fields
// UnityEngine.Experimental.Rendering.HDPipeline.Unlit+BSDFData: static fields
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Unlit.SurfaceData
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Unlit+SurfaceData
// PackingRules = Exact
struct SurfaceData
{

// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Unlit.BSDFData
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Unlit+BSDFData
// PackingRules = Exact
struct BSDFData
{

2
Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/RenderPipelineResources.cs


var instance = CreateInstance<RenderPipelineResources>();
instance.debugDisplayLatlongShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayLatlong.Shader");
instance.debugDisplayShadowMapShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayShadowMap.Shader");
instance.debugViewMaterialGBufferShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugViewMaterialGBuffer.Shader");
instance.debugViewTilesShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugViewTiles.Shader");
instance.debugFullScreenShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugFullScreen.Shader");

#endif
// Debug
public Shader debugDisplayLatlongShader;
public Shader debugDisplayShadowMapShader;
public Shader debugViewMaterialGBufferShader;
public Shader debugViewTilesShader;
public Shader debugFullScreenShader;

20
Assets/ScriptableRenderPipeline/ShaderGenerator/Editor/CSharpToHLSL.cs


{
if (attr is GenerateHLSL)
{
var parent = type.DeclaringType;
if (parent != null)
ShaderTypeGenerator gen;
if (s_TypeName.TryGetValue(type.FullName, out gen))
Debug.LogError("The GenerateHLSL attribute not supported on nested classes (" + type.FullName + "), skipping.");
}
else
{
ShaderTypeGenerator gen;
if (s_TypeName.TryGetValue(type.FullName, out gen))
{
Debug.LogError("Duplicate typename with the GenerateHLSL attribute detected: " + type.FullName +
" declared in both " + gen.type.Assembly.FullName + " and " + type.Assembly.FullName + ". Skipping the second instance.");
}
s_TypeName[type.FullName] = new ShaderTypeGenerator(type, attr as GenerateHLSL);
Debug.LogError( "Duplicate typename with the GenerateHLSL attribute detected: " + type.FullName +
" declared in both " + gen.type.Assembly.FullName + " and " + type.Assembly.FullName + ". Skipping the second instance.");
s_TypeName[type.FullName] = new ShaderTypeGenerator(type, attr as GenerateHLSL);
}
}
}

{
writer.Write(gen.EmitFunctions() + "\n");
}
}
}
writer.Write("\n#endif\n");

30
Assets/ScriptableRenderPipeline/ShaderGenerator/Editor/ShaderTypeGeneration.cs


public string fieldName;
public Type fieldType;
public bool isDirection;
public bool isSRGB;
public bool isSRGB;
}
void Error(string error)

if (!attr.needParamDebug)
return shaderText;
// Specific to HDRenderPipeline
// Specific to HDRenderPipeline
string lowerStructName = type.Name.ToLower();
shaderText += "//\n";

{
shaderText += " result = " + lowerStructName + "." + debugField.fieldName + ".xxx * 0.5 + 0.5;\n";
}
else
else
{
shaderText += " result = " + lowerStructName + "." + debugField.fieldName + ".xxx;\n";
}

{
shaderText += " result = " + lowerStructName + "." + debugField.fieldName + " * 0.5 + 0.5;\n";
}
else
else
}
}
}
else if (debugField.fieldType == typeof(Vector4))
{

}
else // This case left is suppose to be a complex structure. Either we don't support it or it is an enum. Consider it is an enum with GetIndexColor, user can override it if he want.
{
shaderText += " result = GetIndexColor(" + lowerStructName + "." + debugField.fieldName + ");\n";
shaderText += " result = GetIndexColor(" + lowerStructName + "." + debugField.fieldName + ");\n";
if (debugField.isSRGB)
{
shaderText += " needLinearToSRGB = true;\n";

}
shaderText += " }\n";
shaderText += "}\n";
shaderText += "}\n";
return shaderText;
}

{
if (field.FieldType.IsPrimitive)
{
m_Statics[field.Name] = field.GetValue(null).ToString();
// Unity convention is to start static of constant with k_ or s_, remove this part
string name = InsertUnderscore(field.Name);
if (name.StartsWith("k_") || name.StartsWith("s_"))
{
name = name.Substring(2);
}
string defineName = name.ToUpper();
m_Statics[defineName] = field.GetValue(null).ToString();
}
continue;
}

string subNamespace = type.Namespace.Substring(type.Namespace.LastIndexOf((".")) + 1);
string className = type.FullName.Substring(type.FullName.LastIndexOf((".")) + 1); // ClassName include nested class
className = className.Replace('+', '_'); // FullName is Class+NestedClass replace by Class_NestedClass
string defineName = ("DEBUGVIEW_" + subNamespace + "_" + type.Name + "_" + name).ToUpper();
string defineName = ("DEBUGVIEW_" + className + "_" + name).ToUpper();
m_Statics[defineName] = Convert.ToString(attr.paramDefinesStart + debugCounter++);
bool isDirection = false;

92
Assets/ScriptableRenderPipeline/Core/Shadow/Resources/DebugDisplayShadowMap.shader


Shader "Hidden/HDRenderPipeline/DebugDisplayShadowMap"
Shader "Hidden/ScriptableRenderPipeline/DebugDisplayShadowMap"
HLSLINCLUDE
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#include "../../../ShaderLibrary/Common.hlsl"
float4 _TextureScaleBias;
float _TextureSlice;
SamplerState ltc_linear_clamp_sampler;
TEXTURE2D_ARRAY(_AtlasTexture);
struct Attributes
{
uint vertexID : SV_VertexID;
};
struct Varyings
{
float4 positionCS : SV_POSITION;
float2 texcoord : TEXCOORD0;
};
Varyings Vert(Attributes input)
{
Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
output.texcoord = GetFullScreenTriangleTexcoord(input.vertexID) * _TextureScaleBias.xy + _TextureScaleBias.zw;
return output;
}
ENDHLSL
ZWrite Off
Name "RegularShadow"
ZWrite On
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#pragma fragment Frag
#include "../../ShaderLibrary/Common.hlsl"
#define SHADOW_TILEPASS // TODO: Not sure it must be define, ask uygar
#include "../../ShaderLibrary/Shadow/Shadow.hlsl"
#undef SHADOW_TILEPASS
SamplerState ltc_linear_clamp_sampler;
float4 _TextureScaleBias;
struct Attributes
#pragma fragment FragRegular
float4 FragRegular(Varyings input) : SV_Target
uint vertexID : SV_VertexID;
};
return SAMPLE_TEXTURE2D_ARRAY(_AtlasTexture, ltc_linear_clamp_sampler, input.texcoord, _TextureSlice).xxxx;
}
struct Varyings
{
float4 positionCS : SV_POSITION;
float2 texcoord : TEXCOORD0;
};
ENDHLSL
}
Varyings Vert(Attributes input)
{
Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
output.texcoord = GetFullScreenTriangleTexcoord(input.vertexID) * _TextureScaleBias.xy + _TextureScaleBias.zw;
Pass
{
Name "VarianceShadow"
ZTest Off
Blend One Zero
Cull Off
ZWrite On
return output;
}
HLSLPROGRAM
float4 Frag(Varyings input) : SV_Target
#pragma vertex Vert
#pragma fragment FragVariance
float4 FragVariance(Varyings input) : SV_Target
ShadowContext shadowContext = InitShadowContext();
// Caution: ShadowContext is define in Shadowcontext.hlsl for current render pipeline. This shader must be in sync with its content else it doesn't work.
return SAMPLE_TEXTURE2D_ARRAY(_ShadowmapExp_PCF, ltc_linear_clamp_sampler, input.texcoord, 0).xxxx;
return SAMPLE_TEXTURE2D_ARRAY(_AtlasTexture, ltc_linear_clamp_sampler, input.texcoord, _TextureSlice).rgba; // Might want something more clever like a channel selector.
}
Fallback Off
}

9
Assets/ScriptableRenderPipeline/Core/Shadow/Resources.meta


fileFormatVersion: 2
guid: 17c6560a19ee38a488a305b841122612
folderAsset: yes
timeCreated: 1496931301
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

/Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayShadowMap.shader.meta → /Assets/ScriptableRenderPipeline/Core/Shadow/Resources/DebugDisplayShadowMap.shader.meta

/Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayShadowMap.shader → /Assets/ScriptableRenderPipeline/Core/Shadow/Resources/DebugDisplayShadowMap.shader

正在加载...
取消
保存