浏览代码

Merge master

/main
Frédéric Vauchelles 6 年前
当前提交
4bd00e90
共有 76 个文件被更改,包括 2203 次插入327 次删除
  1. 2
      ScriptableRenderPipeline/Core/CoreRP/Editor/ShaderGenerator/CSharpToHLSL.cs
  2. 73
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Common.hlsl
  3. 2
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/EntityLighting.hlsl
  4. 12
      ScriptableRenderPipeline/Core/CoreRP/Utilities/CoreUtils.cs
  5. 25
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDAdditionalCameraData.cs
  6. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.cs
  7. 170
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalSystem.cs
  8. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/GlobalDecalSettings.cs
  9. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/SerializedHDCamera.cs
  10. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/EditorRenderPipelineResources/ReflectionProbesPreview.shader
  11. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.Styles.cs
  12. 49
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.cs
  13. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs
  14. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/GlobalDecalSettingsUI.cs
  15. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/SerializedGlobalDecalSettings.cs
  16. 125
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs
  17. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs
  18. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs
  19. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDAdditionalLightData.cs
  20. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs
  21. 111
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.hlsl
  22. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopDef.hlsl
  23. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-bigtile.compute
  24. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-clustered.compute
  25. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild.compute
  26. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/materialflags.compute
  27. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/scrbound.compute
  28. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DBufferManager.cs
  29. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs
  30. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs.hlsl
  31. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.hlsl
  32. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalData.hlsl
  33. 94
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalUtilities.hlsl
  34. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLit.shader
  35. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitTessellation.shader
  36. 48
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl
  37. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitTessellation.shader
  38. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Material.hlsl
  39. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Unlit/Unlit.shader
  40. 33
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/Blit.shader
  41. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassDBuffer.hlsl
  42. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyRenderingContext.cs
  43. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDAdditionalCameraEditor.cs
  44. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDAdditionalCameraEditor.cs.meta
  45. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/AdditionalShadowDataEditor.cs
  46. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/AdditionalShadowDataEditor.cs.meta
  47. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDAdditionalLightDataEditor.cs
  48. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDAdditionalLightDataEditor.cs.meta
  49. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/StackLit.meta
  50. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit.meta
  51. 195
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Texture2DAtlas.cs
  52. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Texture2DAtlas.cs.meta
  53. 101
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/StackLit/StackLitUI.cs
  54. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/StackLit/StackLitUI.cs.meta
  55. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass.meta
  56. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass/StackLitDepthPass.hlsl
  57. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass/StackLitDepthPass.hlsl.meta
  58. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass/StackLitDistortionPass.hlsl
  59. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass/StackLitDistortionPass.hlsl.meta
  60. 43
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass/StackLitSharePass.hlsl
  61. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass/StackLitSharePass.hlsl.meta
  62. 41
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.cs
  63. 78
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.cs.hlsl
  64. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.cs.hlsl.meta
  65. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.cs.meta
  66. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.hlsl.meta
  67. 300
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.shader
  68. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.shader.meta
  69. 71
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLitData.hlsl
  70. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLitData.hlsl.meta
  71. 45
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLitProperties.hlsl
  72. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLitProperties.hlsl.meta
  73. 560
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.hlsl

2
ScriptableRenderPipeline/Core/CoreRP/Editor/ShaderGenerator/CSharpToHLSL.cs


// Iterate over assemblyList, discover all applicable types with fully qualified names
var assemblyList = AppDomain.CurrentDomain.GetAssemblies()
// We need to exclude dynamic assemblies (their type can't be queried, throwing an exception below)
.Where(ass => !ass.IsDynamic)
.Where(ass => !(ass.ManifestModule is System.Reflection.Emit.ModuleBuilder))
.ToList();
foreach (var assembly in assemblyList)

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


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

// Texture utilities
// ----------------------------------------------------------------------------
float ComputeTextureLOD(float2 uvdx, float2 uvdy, float2 scale)
{
float2 ddx_ = scale * uvdx;
float2 ddy_ = scale * uvdy;
float d = max(dot(ddx_, ddx_), dot(ddy_, ddy_));
return max(0.5 * log2(d), 0.0);
}
float d = max(dot(ddx_, ddx_), dot(ddy_, ddy_));
return max(0.5 * log2(d), 0.0);
return ComputeTextureLOD(ddx_, ddy_, 1.0);
}
// x contains width, w contains height

return float4(uv * 2.0 - 1.0, z, 1.0);
}
// draw procedural with 2 triangles has index order (0,1,2) (0,2,3)
// 0 - 0,0
// 1 - 0,1
// 2 - 1,1
// 3 - 1,0
float2 GetQuadTexCoord(uint vertexID)
{
uint topBit = vertexID >> 1;
uint botBit = (vertexID & 1);
float u = topBit;
float v = (topBit + botBit) & 1; // produces 0 for indices 0,3 and 1 for 1,2
#if UNITY_UV_STARTS_AT_TOP
v = 1.0 - v;
#endif
return float2(u, v);
}
// 0 - 0,1
// 1 - 0,0
// 2 - 1,0
// 3 - 1,1
float4 GetQuadVertexPosition(uint vertexID, float z = UNITY_NEAR_CLIP_VALUE)
{
uint topBit = vertexID >> 1;
uint botBit = (vertexID & 1);
float x = topBit;
float y = 1 - (topBit + botBit) & 1; // produces 1 for indices 0,3 and 0 for 1,2
return float4(x, y, z, 1.0);
}
#if !defined(SHADER_API_GLES)
// LOD dithering transition helper

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

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


#ifndef UNITY_ENTITY_LIGHTING_INCLUDED
#define UNITY_ENTITY_LIGHTING_INCLUDED
#include "common.hlsl"
#include "Common.hlsl"
// TODO: Check if PI is correctly handled!

12
ScriptableRenderPipeline/Core/CoreRP/Utilities/CoreUtils.cs


mesh.triangles = triangles;
return mesh;
}
public static void DisplayUnsupportedAPIMessage()
{
Debug.LogError("Platform " + SystemInfo.operatingSystem + " with device " + SystemInfo.graphicsDeviceType.ToString() + " is not supported, no rendering will occur");
#if UNITY_EDITOR
foreach (UnityEditor.SceneView sv in Resources.FindObjectsOfTypeAll(typeof(UnityEditor.SceneView)))
sv.ShowNotification(new GUIContent("Platform " + SystemInfo.operatingSystem + " with device " + SystemInfo.graphicsDeviceType.ToString() + " is not supported, no rendering will occur"));
#endif
}
}
}

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


// Default is the default rendering path define by the HDRendeRPipelineAsset FrameSettings.
// Custom allow users to define the FrameSettigns for this path
// Then enum can contain either preset of FrameSettings or hard coded path
// Unlit below is a hard coded path (a path that can't be implemented only with FrameSettings)
// FullscreenPassthrough below is a hard coded path (a path that can't be implemented only with FrameSettings)
Unlit // Hard coded path
FullscreenPassthrough // Hard coded path
};
public enum ClearColorMode

void UnRegisterDebug()
{
if (m_camera == null)
if (m_camera == null)
return;
if (m_IsDebugRegistered)

// 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)
if (m_camera == null)
m_camera.allowHDR = false;
// Tag as dirty so frameSettings are correctly initialize at next HDRenderPipeline.Render() call

// When FrameSettings are manipulated or RenderPath change we reset them to reflect the change, discarding all the Debug Windows change.
// Tag as dirty so frameSettings are correctly initialize at next HDRenderPipeline.Render() call
m_frameSettingsIsDirty = true;
}
// This is called at the creation of the HD Additional Camera Data, to convert the legacy camera settings to HD
public static void InitDefaultHDAdditionalCameraData(HDAdditionalCameraData cameraData)
{
var camera = cameraData.gameObject.GetComponent<Camera>();
cameraData.clearDepth = camera.clearFlags != CameraClearFlags.Nothing;
if (camera.clearFlags == CameraClearFlags.Skybox)
cameraData.clearColorMode = ClearColorMode.Sky;
else if (camera.clearFlags == CameraClearFlags.SolidColor)
cameraData.clearColorMode = ClearColorMode.BackgroundColor;
else // None
cameraData.clearColorMode = ClearColorMode.None;
}
}
}

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


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

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


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

{
public const int kInvalidIndex = -1;
public const int kDecalAtlasSize = 128;
public class DecalHandle
{
public DecalHandle(int index, int materialID)

}
}
public TextureCache2D TextureAtlas
{
get
{
if (m_DecalAtlas == null)
{
m_DecalAtlas = new TextureCache2D("DecalAtlas");
m_DecalAtlas.AllocTextureArray(2048, kDecalAtlasSize, kDecalAtlasSize, TextureFormat.ARGB32, true);
}
return m_DecalAtlas;
}
}
public Camera CurrentCamera
{
get

static public float[] m_BoundingDistances = new float[1];
private Dictionary<int, DecalSet> m_DecalSets = new Dictionary<int, DecalSet>();
private TextureCache2D m_DecalAtlas = null;
// current camera
private Camera m_Camera;

private Texture2DAtlas m_Atlas = null;
public bool m_AllocationSuccess = true;
public Texture2DAtlas Atlas
{
get
{
if (m_Atlas == null)
{
m_Atlas = new Texture2DAtlas(HDUtils.hdrpSettings.decalSettings.atlasWidth, HDUtils.hdrpSettings.decalSettings.atlasHeight, RenderTextureFormat.ARGB32);
}
return m_Atlas;
}
}
public class TextureScaleBias : IComparable
{
public Texture m_Texture = null;
public Vector4 m_ScaleBias = Vector4.zero;
public int CompareTo(object obj)
{
TextureScaleBias other = obj as TextureScaleBias;
int size = m_Texture.width * m_Texture.height;
int otherSize = other.m_Texture.width * other.m_Texture.height;
if(size > otherSize)
{
return -1;
}
else if( size < otherSize)
{
return 1;
}
else
{
return 0;
}
}
}
private List<TextureScaleBias> m_TextureList = new List<TextureScaleBias>();
private void InitializeMaterialValues()
public void InitializeMaterialValues()
m_DiffuseTexture = m_Material.GetTexture("_BaseColorMap");
m_NormalTexture = m_Material.GetTexture("_NormalMap");
m_MaskTexture = m_Material.GetTexture("_MaskMap");
m_Diffuse.m_Texture = m_Material.GetTexture("_BaseColorMap");
m_Normal.m_Texture = m_Material.GetTexture("_NormalMap");
m_Mask.m_Texture = m_Material.GetTexture("_MaskMap");
m_Blend = m_Material.GetFloat("_DecalBlend");
}

return m_NumResults;
}
private void GetDecalVolumeDataAndBound(Matrix4x4 decalToWorld, Matrix4x4 worldToView)
{
var influenceX = decalToWorld.GetColumn(0) * 0.5f;

normalToWorldBatch[instanceCount] = m_CachedNormalToWorld[decalIndex];
float fadeFactor = Mathf.Clamp((cullDistance - distanceToDecal) / (cullDistance * (1.0f - m_CachedDrawDistances[decalIndex].y)), 0.0f, 1.0f);
normalToWorldBatch[instanceCount].m03 = fadeFactor * m_Blend; // vector3 rotation matrix so bottom row and last column can be used for other data to save space
normalToWorldBatch[instanceCount].m13 = m_DiffuseTexIndex; // texture atlas indices needed for clustered
normalToWorldBatch[instanceCount].m23 = m_NormalTexIndex;
normalToWorldBatch[instanceCount].m33 = m_MaskTexIndex;
m_DecalDatas[m_DecalDatasCount].diffuseScaleBias = m_Diffuse.m_ScaleBias;
m_DecalDatas[m_DecalDatasCount].normalScaleBias = m_Normal.m_ScaleBias;
m_DecalDatas[m_DecalDatasCount].maskScaleBias = m_Mask.m_ScaleBias;
GetDecalVolumeDataAndBound(decalToWorldBatch[instanceCount], worldToView);
m_DecalDatasCount++;

}
}
void UpdateTextureCache(CommandBuffer cmd)
{
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()
public void AddToTextureList(ref List<TextureScaleBias> textureList)
if (m_DiffuseTexture != null)
if(m_Diffuse.m_Texture != null)
instance.TextureAtlas.RemoveEntryFromSlice(m_DiffuseTexture);
textureList.Add(m_Diffuse);
if (m_NormalTexture != null)
if (m_Normal.m_Texture != null)
instance.TextureAtlas.RemoveEntryFromSlice(m_NormalTexture);
textureList.Add(m_Normal);
if (m_MaskTexture != null)
if (m_Mask.m_Texture != null)
instance.TextureAtlas.RemoveEntryFromSlice(m_MaskTexture);
textureList.Add(m_Mask);
public void UpdateCachedMaterialData(CommandBuffer cmd)
{
InitializeMaterialValues(); // refresh in case they changed in the UI
UpdateTextureCache(cmd);
}
public void RenderIntoDBuffer(CommandBuffer cmd)
{

private Matrix4x4[] m_CachedNormalToWorld = new Matrix4x4[kDecalBlockSize];
private Vector2[] m_CachedDrawDistances = new Vector2[kDecalBlockSize]; // x - draw distance, y - fade scale
private Material m_Material;
private Texture m_DiffuseTexture = null;
private Texture m_NormalTexture = null;
private Texture m_MaskTexture = null;
private int m_DiffuseTexIndex = -1;
private int m_NormalTexIndex = -1;
private int m_MaskTexIndex = -1;
TextureScaleBias m_Diffuse = new TextureScaleBias();
TextureScaleBias m_Normal = new TextureScaleBias();
TextureScaleBias m_Mask = new TextureScaleBias();
}
public DecalHandle AddDecal(Transform transform, float drawDistance, float fadeScale, Material material)

decalSet.RemoveDecal(handle);
if (decalSet.Count == 0)
{
decalSet.RemoveFromTextureCache();
m_DecalSets.Remove(key);
}
}

public void SetAtlas(CommandBuffer cmd)
{
cmd.SetGlobalTexture(HDShaderIDs._DecalAtlasID, TextureAtlas.GetTexCache());
cmd.SetGlobalTexture(HDShaderIDs._DecalAtlas2DID, Atlas.AtlasTexture);
}
public void AddTexture(CommandBuffer cmd, TextureScaleBias textureScaleBias)
{
if (textureScaleBias.m_Texture != null)
{
if (!Atlas.AddTexture(cmd, ref textureScaleBias.m_ScaleBias,textureScaleBias.m_Texture))
{
m_AllocationSuccess = false;
}
}
else
{
textureScaleBias.m_ScaleBias = Vector4.zero;
}
public void UpdateCachedMaterialData(CommandBuffer cmd)
public void UpdateCachedMaterialData()
//instance.m_AllocationSuccess = true;
m_TextureList.Clear();
pair.Value.UpdateCachedMaterialData(cmd);
pair.Value.InitializeMaterialValues();
pair.Value.AddToTextureList(ref m_TextureList);
}
}
public void UpdateTextureAtlas(CommandBuffer cmd)
{
m_AllocationSuccess = true;
foreach (TextureScaleBias textureScaleBias in m_TextureList)
{
AddTexture(cmd, textureScaleBias);
}
if (!m_AllocationSuccess) // texture failed to find space in the atlas
{
m_TextureList.Sort(); // sort the texture list largest to smallest for better packing
Atlas.ResetAllocator(); // clear all allocations
// try again
m_AllocationSuccess = true;
foreach (TextureScaleBias textureScaleBias in m_TextureList)
{
AddTexture(cmd, textureScaleBias);
}
if(!m_AllocationSuccess) // still failed to allocate, decal atlas size needs to increase
{
Debug.LogWarning("Decal texture atlas out of space, decals on transparent geometry might not render correctly, atlas size can be changed in HDRenderPipelineAsset");
}
}
}

public void Cleanup()
{
if (m_DecalAtlas != null)
m_DecalAtlas.Release();
if (m_Atlas != null)
m_Atlas.Release();
m_DecalAtlas = null;
m_Atlas = null;
}
}
}

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/GlobalDecalSettings.cs


public class GlobalDecalSettings
{
public int drawDistance = 1000;
public int atlasSize = 8192;
public int atlasWidth = 4096;
public int atlasHeight = 4096;
}
}

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/SerializedHDCamera.cs


public SerializedHDCamera(SerializedObject serializedObject)
{
this.serializedObject = serializedObject;
var additionals = CoreEditorUtils.GetAdditionalData<HDAdditionalCameraData>(serializedObject.targetObjects);
var additionals = CoreEditorUtils.GetAdditionalData<HDAdditionalCameraData>(serializedObject.targetObjects, HDAdditionalCameraData.InitDefaultHDAdditionalCameraData);
hideFlags.intValue = (int)HideFlags.HideInInspector;
// We don't hide additional camera data anymore on UX team request. To be compatible with already author scene we force to be visible
//hideFlags.intValue = (int)HideFlags.HideInInspector;
hideFlags.intValue = (int)HideFlags.None;
serializedAdditionalDataObject.ApplyModifiedProperties();
//backgroundColor = serializedObject.FindProperty("m_BackGroundColor");

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/EditorRenderPipelineResources/ReflectionProbesPreview.shader


#pragma vertex vert
#pragma fragment frag
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "HDRP/ShaderVariables.hlsl"
struct appdata

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


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

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


public SerializedProperty affectSpecular;
public SerializedProperty lightTypeExtent;
public SerializedProperty spotLightShape;
public SerializedProperty enableSpotReflector;
public SerializedProperty shapeWidth;
public SerializedProperty shapeHeight;
public SerializedProperty aspectRatio;

affectSpecular = o.Find(x => x.affectSpecular),
lightTypeExtent = o.Find(x => x.lightTypeExtent),
spotLightShape = o.Find(x => x.spotLightShape),
enableSpotReflector = o.Find(x => x.enableSpotReflector),
shapeWidth = o.Find(x => x.shapeWidth),
shapeHeight = o.Find(x => x.shapeHeight),
aspectRatio = o.Find(x => x.aspectRatio),

if (spotLightShape == SpotLightShape.Cone)
{
settings.DrawSpotAngle();
EditorGUILayout.PropertyField(m_AdditionalLightData.enableSpotReflector, s_Styles.enableSpotReflector);
EditorGUILayout.Slider(m_AdditionalLightData.spotInnerPercent, 0f, 100f, s_Styles.spotInnerPercent);
}
// TODO : replace with angle and ratio

EditorGUILayout.PropertyField(m_AdditionalLightData.enableSpotReflector, s_Styles.enableSpotReflector);
EditorGUILayout.Slider(m_AdditionalLightData.aspectRatio, 0.05f, 20.0f, s_Styles.aspectRatioPyramid);
}
else if (spotLightShape == SpotLightShape.Box)

m_AdditionalLightData.directionalIntensity.floatValue = Mathf.Max(0, m_AdditionalLightData.directionalIntensity.floatValue);
m_AdditionalLightData.punctualIntensity.floatValue = Mathf.Max(0, m_AdditionalLightData.punctualIntensity.floatValue);
m_AdditionalLightData.areaIntensity.floatValue = Mathf.Max(0, m_AdditionalLightData.areaIntensity.floatValue);
switch (m_LightShape)
{
case LightShape.Directional:

case LightShape.Spot:
// Spot should used conversion which take into account the angle, and thus the intensity vary with angle.
// This is not easy to manipulate for lighter, so we simply consider any spot light as just occluded point light. So reuse the same code.
settings.intensity.floatValue = LightUtils.ConvertPointLightIntensity(m_AdditionalLightData.punctualIntensity.floatValue);
// TODO: What to do with box shape ?
// var spotLightShape = (SpotLightShape)m_AdditionalLightData.spotLightShape.enumValueIndex;
var spotLightShape = (SpotLightShape)m_AdditionalLightData.spotLightShape.enumValueIndex;
if (m_AdditionalLightData.enableSpotReflector.boolValue)
{
if (spotLightShape == SpotLightShape.Cone)
{
settings.intensity.floatValue = LightUtils.ConvertSpotLightIntensity(m_AdditionalLightData.punctualIntensity.floatValue, settings.spotAngle.floatValue * Mathf.Deg2Rad, true );
}
else if (spotLightShape == SpotLightShape.Pyramid)
{
var aspectRatio = m_AdditionalLightData.aspectRatio.floatValue;
// Since the smallest angles is = to the fov, and we don't care of the angle order, simply make sure the aspect ratio is > 1
if ( aspectRatio < 1f ) aspectRatio = 1f/aspectRatio;
var angleA = settings.spotAngle.floatValue * Mathf.Deg2Rad;
var halfAngle = angleA * 0.5f; // half of the smallest angle
var length = Mathf.Tan(halfAngle); // half length of the smallest side of the rectangle
length *= aspectRatio; // half length of the bigest side of the rectangle
halfAngle = Mathf.Atan(length); // half of the bigest angle
var angleB = halfAngle * 2f;
settings.intensity.floatValue = LightUtils.ConvertFrustrumLightIntensity(m_AdditionalLightData.punctualIntensity.floatValue, angleA, angleB );
}
else // Box shape, fallback to punctual light.
{
settings.intensity.floatValue = LightUtils.ConvertPointLightIntensity(m_AdditionalLightData.punctualIntensity.floatValue);
}
}
else // Reflector disabled, fallback to punctual light.
{
settings.intensity.floatValue = LightUtils.ConvertPointLightIntensity(m_AdditionalLightData.punctualIntensity.floatValue);
}
break;
case LightShape.Rectangle:

// Internal utilities
void ApplyAdditionalComponentsVisibility(bool hide)
{
var flags = hide ? HideFlags.HideInInspector : HideFlags.None;
// UX team decided thta we should always show component in inspector.
// However already authored scene save this settings, so force the component to be visible
// var flags = hide ? HideFlags.HideInInspector : HideFlags.None;
var flags = HideFlags.None;
foreach (var t in m_SerializedAdditionalLightData.targetObjects)
((HDAdditionalLightData)t).hideFlags = flags;

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs


TextureCombiner maskMapCombiner = new TextureCombiner(
metallicMap, 0, // R: Metallic from red
occlusionMap, 0, // G: Occlusion from red
detailMaskMap, 0, // B: Detail Mask from red
occlusionMap, 1, // G: Occlusion from green
detailMaskMap, 3, // B: Detail Mask from alpha
smoothnessMap, (srcMaterial.shader.name == Standard_Rough)?-4:3 // A: Smoothness Texture from inverse greyscale for roughness setup, or alpha
);

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/GlobalDecalSettingsUI.cs


EditorGUILayout.LabelField(_.GetContent("Decals"), EditorStyles.boldLabel);
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(d.drawDistance, _.GetContent("Draw Distance"));
EditorGUILayout.PropertyField(d.atlasSize, _.GetContent("Atlas Size"));
EditorGUILayout.PropertyField(d.atlasWidth, _.GetContent("Atlas Width"));
EditorGUILayout.PropertyField(d.atlasHeight, _.GetContent("Atlas Height"));
--EditorGUI.indentLevel;
}
}

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/SerializedGlobalDecalSettings.cs


public SerializedProperty root;
public SerializedProperty drawDistance;
public SerializedProperty atlasSize;
public SerializedProperty atlasWidth;
public SerializedProperty atlasHeight;
public SerializedGlobalDecalSettings(SerializedProperty root)
{

atlasSize = root.Find((GlobalDecalSettings s) => s.atlasSize);
atlasWidth = root.Find((GlobalDecalSettings s) => s.atlasWidth);
atlasHeight = root.Find((GlobalDecalSettings s) => s.atlasHeight);
}
}
}

125
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs


if (!IsSupportedPlatform())
{
Debug.LogError("Platform " + SystemInfo.operatingSystem + " with device " + SystemInfo.graphicsDeviceType.ToString() + " is not supported, no rendering will occur");
#if UNITY_EDITOR
foreach (UnityEditor.SceneView sv in Resources.FindObjectsOfTypeAll(typeof(UnityEditor.SceneView)))
sv.ShowNotification(new GUIContent("Platform " + SystemInfo.operatingSystem + " with device " + SystemInfo.graphicsDeviceType.ToString() + " is not supported, no rendering will occur"));
#endif
CoreUtils.DisplayUnsupportedAPIMessage();
return false;
}

Mathf.Log(Mathf.Min(previousColorPyramidRT.rt.width, previousColorPyramidRT.rt.height), 2),
0.0f
));
}
}
}
bool IsConsolePlatform()

RenderPipeline.BeginCameraRendering(camera);
if (camera.cameraType != CameraType.Reflection)
// TODO: Render only visible probes
ReflectionSystem.RenderAllRealtimeViewerDependentProbesFor(ReflectionProbeType.PlanarReflection, camera);
// First, get aggregate of frame settings base on global settings, camera frame settings and debug settings
// Note: the SceneView camera will never have additionalCameraData
var additionalCameraData = camera.GetComponent<HDAdditionalCameraData>();

// This is the main command buffer used for the frame.
var cmd = CommandBufferPool.Get("");
// Specific pass to simply display the content of the camera buffer if users have fill it themselves (like video player)
if (additionalCameraData && additionalCameraData.renderingPath == HDAdditionalCameraData.RenderingPath.FullscreenPassthrough)
{
renderContext.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
renderContext.Submit();
continue;
}
if (camera.cameraType != CameraType.Reflection)
// TODO: Render only visible probes
ReflectionSystem.RenderAllRealtimeViewerDependentProbesFor(ReflectionProbeType.PlanarReflection, camera);
// Init material if needed
// TODO: this should be move outside of the camera loop but we have no command buffer, ask details to Tim or Julien to do this
if (!m_IBLFilterGGX.IsInitialized())

{
DecalSystem.instance.EndCull();
m_DbufferManager.vsibleDecalCount = DecalSystem.m_DecalsVisibleThisFrame;
DecalSystem.instance.UpdateCachedMaterialData(cmd); // textures, alpha or fade distances could've changed
DecalSystem.instance.UpdateCachedMaterialData(); // textures, alpha or fade distances could've changed
DecalSystem.instance.UpdateTextureAtlas(cmd); // as this is only used for transparent pass, would've been nice not to have to do this if no transparent renderers are visible
DecalSystem.instance.CreateDrawData(); // prepare data is separate from draw
}
}

// We have to bind the material specific global parameters in this mode
m_MaterialList.ForEach(material => material.Bind());
if (additionalCameraData && additionalCameraData.renderingPath == HDAdditionalCameraData.RenderingPath.Unlit)
{
// TODO: Add another path dedicated to planar reflection / real time cubemap that implement simpler lighting
// It is up to the users to only send unlit object for this camera path
using (new ProfilingSample(cmd, "Forward", CustomSamplerId.Forward.GetSampler()))
{
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer, ClearFlag.Color | ClearFlag.Depth);
RenderOpaqueRenderList(m_CullResults, camera, renderContext, cmd, HDShaderPassNames.s_ForwardName);
RenderTransparentRenderList(m_CullResults, camera, renderContext, cmd, HDShaderPassNames.s_ForwardName);
}
renderContext.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
renderContext.Submit();
continue;
}
// Frustum cull density volumes on the CPU. Can be performed as soon as the camera is set up.
DensityVolumeList densityVolumes = m_VolumetricLightingSystem.PrepareVisibleDensityVolumeList(hdCamera, cmd);

// During rendering we use our own depth buffer instead of the one provided by the scene view (because we need to be able to control its life cycle)
// In order for scene view gizmos/icons etc to be depth test correctly, we need to copy the content of our own depth buffer into the scene view depth buffer.
// On subtlety here is that our buffer can be bigger than the camera one so we need to copy only the corresponding portion
// (it's handled automatically by the copy shader because it uses a load in pxiel coordinates based on the target).
// (it's handled automatically by the copy shader because it uses a load in pixel coordinates based on the target).
// This copy will also have the effect of re-binding this depth buffer correctly for subsequent editor rendering.
// NOTE: This needs to be done before the call to RenderDebug because debug overlays need to update the depth for the scene view as well.

// Depth texture is now ready, bind it.
cmd.SetGlobalTexture(HDShaderIDs._MainDepthTexture, GetDepthTexture());
// for alpha compositing, color is cleared to 0, alpha to 1
// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Color clearColor = new Color(0.0f, 0.0f, 0.0f, 1.0f);
HDUtils.SetRenderTarget(cmd, camera, m_DbufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer, ClearFlag.Color, clearColor);
// we need to do a separate clear for normals, because they are cleared to a different color
Color clearColorNormal = new Color(0.5f, 0.5f, 0.5f, 1.0f); // for normals 0.5 is neutral
m_DbufferManager.ClearNormalTargetAndHTile(cmd, camera, clearColorNormal);
m_DbufferManager.ClearTargets(cmd, camera);
HDUtils.SetRenderTarget(cmd, camera, m_DbufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer); // do not clear anymore
m_DbufferManager.SetHTile(m_DbufferManager.bufferCount, cmd);
DecalSystem.instance.RenderIntoDBuffer(cmd);

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

switch (pass)
{
case ForwardPass.Opaque:
{
// In case of forward SSS we will bind all the required target. It is up to the shader to write into it or not.
if (m_FrameSettings.enableSubsurfaceScattering)
// In case of forward SSS we will bind all the required target. It is up to the shader to write into it or not.
if (m_FrameSettings.enableSubsurfaceScattering)
RenderTargetIdentifier[] m_MRTWithSSS =
new RenderTargetIdentifier[2 + m_SSSBufferManager.sssBufferCount];
m_MRTWithSSS[0] = m_CameraColorBuffer; // Store the specular color
m_MRTWithSSS[1] = m_CameraSssDiffuseLightingBuffer;
for (int i = 0; i < m_SSSBufferManager.sssBufferCount; ++i)
RenderTargetIdentifier[] m_MRTWithSSS =
new RenderTargetIdentifier[2 + m_SSSBufferManager.sssBufferCount];
m_MRTWithSSS[0] = m_CameraColorBuffer; // Store the specular color
m_MRTWithSSS[1] = m_CameraSssDiffuseLightingBuffer;
for (int i = 0; i < m_SSSBufferManager.sssBufferCount; ++i)
{
m_MRTWithSSS[i + 2] = m_SSSBufferManager.GetSSSBuffer(i);
}
HDUtils.SetRenderTarget(cmd, hdCamera, m_MRTWithSSS, m_CameraDepthStencilBuffer);
}
else
{
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer);
m_MRTWithSSS[i + 2] = m_SSSBufferManager.GetSSSBuffer(i);
m_ForwardAndForwardOnlyPassNames[0] = m_ForwardOnlyPassNames[0] =
HDShaderPassNames.s_ForwardOnlyName;
m_ForwardAndForwardOnlyPassNames[1] = HDShaderPassNames.s_ForwardName;
HDUtils.SetRenderTarget(cmd, hdCamera, m_MRTWithSSS, m_CameraDepthStencilBuffer);
}
else
{
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer);
}
var passNames = m_FrameSettings.enableForwardRenderingOnly
? m_ForwardAndForwardOnlyPassNames
: m_ForwardOnlyPassNames;
m_ForwardAndForwardOnlyPassNames[0] = m_ForwardOnlyPassNames[0] =
HDShaderPassNames.s_ForwardOnlyName;
m_ForwardAndForwardOnlyPassNames[1] = HDShaderPassNames.s_ForwardName;
var passNames = m_FrameSettings.enableForwardRenderingOnly
? m_ForwardAndForwardOnlyPassNames
: m_ForwardOnlyPassNames;
var debugSSTThisPass = debugScreenSpaceTracing && (m_CurrentDebugDisplaySettings.lightingDebugSettings.debugLightingMode == DebugLightingMode.ScreenSpaceTracingReflection);
if (debugSSTThisPass)
{

RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, passNames, m_currentRendererConfigurationBakedLighting);
RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, passNames, m_currentRendererConfigurationBakedLighting);
}
}
{
{
if (m_FrameSettings.enableDBuffer) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
if (m_FrameSettings.enableDBuffer && (DecalSystem.m_DecalsVisibleThisFrame > 0)) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
{
{
}
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, m_AllTransparentPassNames, m_currentRendererConfigurationBakedLighting, pass == ForwardPass.PreRefraction ? HDRenderQueue.k_RenderQueue_PreRefraction : HDRenderQueue.k_RenderQueue_Transparent);
}
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, m_AllTransparentPassNames, m_currentRendererConfigurationBakedLighting, pass == ForwardPass.PreRefraction ? HDRenderQueue.k_RenderQueue_PreRefraction : HDRenderQueue.k_RenderQueue_Transparent);
cmd.ClearRandomWriteTargets();
cmd.ClearRandomWriteTargets();
break;
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs


// all decal properties
public static readonly int _NormalToWorldID = Shader.PropertyToID("_NormalToWorld");
public static readonly int _DecalAtlas2DID = Shader.PropertyToID("_DecalAtlas2D");
public static readonly int _DecalAtlasID = Shader.PropertyToID("_DecalAtlas");
public static readonly int _DecalHTileTexture = Shader.PropertyToID("_DecalHTileTexture");
public static readonly int _DecalIndexShift = Shader.PropertyToID("_DecalIndexShift");

public static readonly int _BlitTexture = Shader.PropertyToID("_BlitTexture");
public static readonly int _BlitScaleBias = Shader.PropertyToID("_BlitScaleBias");
public static readonly int _BlitMipLevel = Shader.PropertyToID("_BlitMipLevel");
public static readonly int _BlitScaleBiasRt = Shader.PropertyToID("_BlitScaleBiasRt");
public static readonly int _WorldScales = Shader.PropertyToID("_WorldScales");
public static readonly int _FilterKernels = Shader.PropertyToID("_FilterKernels");

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs


}
}
public static void BlitTexture(CommandBuffer cmd, RTHandleSystem.RTHandle source, RTHandleSystem.RTHandle destination, Vector4 scaleBias, float mipLevel, bool bilinear)
public static void BlitQuad(CommandBuffer cmd, Texture source, Vector4 scaleBiasTex, Vector4 scaleBiasRT, int mipLevelTex, bool bilinear)
{
s_PropertyBlock.SetTexture(HDShaderIDs._BlitTexture, source);
s_PropertyBlock.SetVector(HDShaderIDs._BlitScaleBias, scaleBiasTex);
s_PropertyBlock.SetVector(HDShaderIDs._BlitScaleBiasRt, scaleBiasRT);
s_PropertyBlock.SetFloat(HDShaderIDs._BlitMipLevel, mipLevelTex);
cmd.DrawProcedural(Matrix4x4.identity, GetBlitMaterial(), bilinear ? 2 : 3, MeshTopology.Quads, 4, 1, s_PropertyBlock);
}
public static void BlitTexture(CommandBuffer cmd, RTHandleSystem.RTHandle source, RTHandleSystem.RTHandle destination, Vector4 scaleBias, float mipLevel, bool bilinear)
{
s_PropertyBlock.SetTexture(HDShaderIDs._BlitTexture, source);
s_PropertyBlock.SetVector(HDShaderIDs._BlitScaleBias, scaleBias);

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


// Only for Spotlight, should be hide for other light
public SpotLightShape spotLightShape = SpotLightShape.Cone;
// Only for Spotlight, should be hide for other light
public bool enableSpotReflector = false;
// Only for Rectangle/Line/box projector lights
public float shapeWidth = 0.5f;

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


public void RenderDeferredDirectionalShadow(HDCamera hdCamera, RTHandleSystem.RTHandle deferredShadowRT, RenderTargetIdentifier depthTexture, CommandBuffer cmd)
{
if (m_CurrentSunLight == null || m_CurrentSunLight.GetComponent<AdditionalShadowData>() == null)
if (m_CurrentSunLight == null || m_CurrentSunLight.GetComponent<AdditionalShadowData>() == null || m_CurrentSunLightShadowIndex < 0)
{
cmd.SetGlobalTexture(HDShaderIDs._DeferredShadowTexture, RuntimeUtilities.blackTexture);
return;

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


#include "CoreRP/ShaderLibrary/Macros.hlsl"
//-----------------------------------------------------------------------------
// LightLoop
// ----------------------------------------------------------------------------

}
}
float reflectionHierarchyWeight = 0.0; // Max: 1.0
float refractionHierarchyWeight = 0.0; // Max: 1.0
// First loop iteration is:
// 1. Screen Space Refraction / Reflection
// 2. Environment Reflection / Refraction
// 3. Sky Reflection / Refraction
//
// Following loop iterations are:
// 1. Environment Reflection / Refraction
// 2. Sky Reflection / Refraction
// Common variable for all iterations
#ifdef LIGHTLOOP_TILE_PASS
uint envLightStart;
# define FETCHINDEX(index) FetchIndex(envLightStart, index);
#else
# define FETCHINDEX(index) index
#endif
uint envLightCount;
#define CONCAT(L, R) L##R
#define EVALUATE_BSDF_ENV(envLightData, TYPE, type) {\
IndirectLighting lighting = EvaluateBSDF_Env( context, V, posInput, preLightData, envLightData, bsdfData, \
envLightData.influenceShapeType, \
CONCAT(GPUIMAGEBASEDLIGHTINGTYPE_, TYPE), CONCAT(type, HierarchyWeight)); \
AccumulateIndirectLighting(lighting, aggregateLighting);\
}
#define EVALUATE_BSDF_ENV(envLightData, TYPE, type) \
IndirectLighting lighting = EvaluateBSDF_Env(context, V, posInput, preLightData, envLightData, bsdfData, envLightData.influenceShapeType, MERGE_NAME(GPUIMAGEBASEDLIGHTINGTYPE_, TYPE), MERGE_NAME(type, HierarchyWeight)); \
AccumulateIndirectLighting(lighting, aggregateLighting);
if (featureFlags & (
LIGHTFEATUREFLAGS_ENV
| LIGHTFEATUREFLAGS_SKY
| LIGHTFEATUREFLAGS_SSREFRACTION
| LIGHTFEATUREFLAGS_SSREFLECTION
)
)
if (featureFlags & (LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_SSREFRACTION | LIGHTFEATUREFLAGS_SSREFLECTION))
float reflectionHierarchyWeight = 0.0; // Max: 1.0
float refractionHierarchyWeight = 0.0; // Max: 1.0
uint envLightStart, envLightCount;
EnvLightData envLightData;
ZERO_INITIALIZE(EnvLightData, envLightData);
{
envLightStart = 0;
// Reflection / Refraction hierarchy is
// 1. Screen Space Refraction / Reflection
// 2. Environment Reflection / Refraction
// 3. Sky Reflection / Refraction
EnvLightData envLightData;
uint envLightIndex = FETCHINDEX(0);
envLightData = _EnvLightDatas[envLightIndex];
envLightData = FetchEnvLight(envLightStart, 0);
{
envLightData = InitSkyEnvLightData(0);
}

AccumulateIndirectLighting(lighting, aggregateLighting);
}
if ((featureFlags & LIGHTFEATUREFLAGS_ENV) && envLightCount > 0)
{
context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES;
EVALUATE_BSDF_ENV(envLightData, REFLECTION, reflection);
EVALUATE_BSDF_ENV(envLightData, REFRACTION, refraction);
}
// Only apply the sky IBL if the sky texture is available
if ((featureFlags & LIGHTFEATUREFLAGS_SKY) && _EnvLightSkyEnabled)
// The sky is a single cubemap texture separate from the reflection probe texture array (different resolution and compression)
context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_SKY;
// The sky data are generated on the fly so the compiler can optimize the code
EnvLightData envLightSky = InitSkyEnvLightData(0);
EVALUATE_BSDF_ENV(envLightSky, REFLECTION, reflection);
if (featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION)
EVALUATE_BSDF_ENV(envLightSky, REFRACTION, refraction);
}
IndirectLighting lighting = EvaluateBSDF_SSLighting( context, V, posInput, preLightData, bsdfData, envLightData,
GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION, refractionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
// Following loop iterations
if (featureFlags & LIGHTFEATUREFLAGS_ENV || featureFlags & LIGHTFEATUREFLAGS_SKY)
{
// Reflection probes are sorted by volume (in the increasing order).
if (featureFlags & LIGHTFEATUREFLAGS_ENV)
{

for (i = 0; i < envLightCount && reflectionHierarchyWeight < 1.0; ++i)
{
uint envLightIndex = FETCHINDEX(i);
EVALUATE_BSDF_ENV(_EnvLightDatas[envLightIndex], REFLECTION, reflection);
EVALUATE_BSDF_ENV(FetchEnvLight(envLightStart, i), REFLECTION, reflection);
}
// Refraction probe and reflection probe will process exactly the same weight. It will be good for performance to be able to share this computation

// We reuse LIGHTFEATUREFLAGS_SSREFRACTION flag as refraction is mainly base on the screen. Would be aa waste to not use screen and only cubemap.
// We reuse LIGHTFEATUREFLAGS_SSREFRACTION flag as refraction is mainly base on the screen. Would be a waste to not use screen and only cubemap.
uint envLightIndex = FETCHINDEX(i);
EVALUATE_BSDF_ENV(_EnvLightDatas[envLightIndex], REFRACTION, refraction);
EVALUATE_BSDF_ENV(FetchEnvLight(envLightStart, i), REFRACTION, refraction);
if (featureFlags & LIGHTFEATUREFLAGS_SKY && _EnvLightSkyEnabled)
if ((featureFlags & LIGHTFEATUREFLAGS_SKY) && _EnvLightSkyEnabled)
// Only apply the sky if we haven't yet accumulated enough IBL lighting.
if (reflectionHierarchyWeight < 1.0)
{
// Only apply the sky if we haven't yet accumulated enough IBL lighting.
if (reflectionHierarchyWeight < 1.0)
{
EVALUATE_BSDF_ENV(envLightSky, REFLECTION, reflection);
}

{
// The sky is a single cubemap texture separate from the reflection probe texture array (different resolution and compression)
context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_SKY;
// The sky data are generated on the fly so the compiler can optimize the code
EnvLightData envLightSky = InitSkyEnvLightData(0);
EVALUATE_BSDF_ENV(envLightSky, REFRACTION, refraction);
}
}

#undef CONCAT
#undef FETCHINDEX
// Also Apply indiret diffuse (GI)
// PostEvaluateBSDF will perform any operation wanted by the material and sum everything into diffuseLighting and specularLighting

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopDef.hlsl


color.rgb = SAMPLE_TEXTURE2D_ARRAY_LOD(_Env2DTextures, s_trilinear_clamp_sampler, ndc.xy, index, lod).rgb;
color.a = any(ndc.xyz < 0) || any(ndc.xyz > 1) ? 0.0 : 1.0;
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_ENVIRONMENT_SAMPLE_COORDINATES)
color = float4(ndc.xy, 0, color.a);

return _LightDatas[j];
}
EnvLightData FetchEnvLight(uint start, uint i)
{
int j = FetchIndex(start, i);
return _EnvLightDatas[j];
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-bigtile.compute


#pragma kernel BigTileLightListGen
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "LightLoop.cs.hlsl"
#include "LightingConvexHullUtils.hlsl"
#include "SortingComputeUtils.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-clustered.compute


#pragma kernel TileLightListGen_DepthRT_MSAA_SrcBigTile LIGHTLISTGEN=TileLightListGen_DepthRT_MSAA_SrcBigTile ENABLE_DEPTH_TEXTURE_BACKPLANE MSAA_ENABLED USE_TWO_PASS_TILED_LIGHTING
#pragma kernel ClearAtomic
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "ShaderBase.hlsl"
#include "LightLoop.cs.hlsl"
#include "LightingConvexHullUtils.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild.compute


//#pragma #pragma enable_d3d11_debug_symbols
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "ShaderBase.hlsl"
#include "LightLoop.cs.hlsl"
#include "LightingConvexHullUtils.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/materialflags.compute


// #pragma enable_d3d11_debug_symbols
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "ShaderBase.hlsl"
#include "LightLoop.cs.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/scrbound.compute


#pragma kernel ScreenBoundsAABB
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "LightLoop.cs.hlsl"
#include "LightCullUtils.hlsl"

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DBufferManager.cs


RTHandles.Release(m_HTile);
}
public void ClearNormalTargetAndHTile(CommandBuffer cmd, HDCamera camera, Color clearColor)
public void ClearTargets(CommandBuffer cmd, HDCamera camera)
// index 1 is normals
HDUtils.SetRenderTarget(cmd, camera, m_RTs[1], ClearFlag.Color, clearColor);
// for alpha compositing, color is cleared to 0, alpha to 1
// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Color clearColor = new Color(0.0f, 0.0f, 0.0f, 1.0f);
Color clearColorNormal = new Color(0.5f, 0.5f, 0.5f, 1.0f); // for normals 0.5 is neutral
HDUtils.SetRenderTarget(cmd, camera, m_RTs[0], ClearFlag.Color, clearColor);
HDUtils.SetRenderTarget(cmd, camera, m_RTs[1], ClearFlag.Color, clearColorNormal);
HDUtils.SetRenderTarget(cmd, camera, m_RTs[2], ClearFlag.Color, clearColor);
HDUtils.SetRenderTarget(cmd, camera, m_HTile, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}

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

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs


{
public Matrix4x4 worldToDecal;
public Matrix4x4 normalToWorld;
public Vector4 diffuseScaleBias;
public Vector4 normalScaleBias;
public Vector4 maskScaleBias;
};
}

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


{
float4x4 worldToDecal;
float4x4 normalToWorld;
float4 diffuseScaleBias;
float4 normalScaleBias;
float4 maskScaleBias;
};
//

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.hlsl


TEXTURE2D_ARRAY(_DecalAtlas);
SAMPLER(sampler_DecalAtlas);
TEXTURE2D(_DecalAtlas2D);
SAMPLER(_trilinear_clamp_sampler_DecalAtlas2D);
// Must be in sync with RT declared in HDRenderPipeline.cs ::Rebuild
void EncodeIntoDBuffer( DecalSurfaceData surfaceData,
out DBufferType0 outDBuffer0,

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


#include "CoreRP/ShaderLibrary/Packing.hlsl"
#include "CoreRP/ShaderLibrary/Sampling/SampleUVMapping.hlsl"
void GetSurfaceData(float2 texCoordDS, float4x4 decalToWorld, out DecalSurfaceData surfaceData)
void GetSurfaceData(float2 texCoordDS, float4x4 normalToWorld, out DecalSurfaceData surfaceData)
float totalBlend = clamp(decalToWorld[0][3], 0.0f, 1.0f);
float totalBlend = clamp(normalToWorld[0][3], 0.0f, 1.0f);
totalBlend = surfaceData.baseColor.w; // base alpha affects aall other channels;
totalBlend = surfaceData.baseColor.w; // base alpha affects all other channels;
surfaceData.normalWS.xyz = mul((float3x3)decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoordDS))) * 0.5f + 0.5f;
surfaceData.normalWS.xyz = mul((float3x3)normalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoordDS))) * 0.5f + 0.5f;
surfaceData.normalWS.w = totalBlend;
surfaceData.HTileMask |= DBUFFERHTILEBIT_NORMAL;
#endif

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


// 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
void ApplyBlendNormal(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float3x3 decalToWorld, float blend, float lod)
void ApplyBlendNormal(inout float4 dst, inout int matMask, float2 texCoords, int mapMask, float3x3 decalToWorld, float blend, float lod)
src.xyz = mul(decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, lod))) * 0.5f + 0.5f;
src.xyz = mul(decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D_LOD(_DecalAtlas2D, _trilinear_clamp_sampler_DecalAtlas2D, texCoords, lod))) * 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, inout float blend, float lod)
void ApplyBlendDiffuse(inout float4 dst, inout int matMask, float2 texCoords, int mapMask, inout float blend, float lod)
float4 src = SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, lod);
float4 src = SAMPLE_TEXTURE2D_LOD(_DecalAtlas2D, _trilinear_clamp_sampler_DecalAtlas2D, texCoords, lod);
src.w *= blend;
blend = src.w; // diffuse texture alpha affects all other channels
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);

void ApplyBlendMask(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float blend, float lod)
void ApplyBlendMask(inout float4 dst, inout int matMask, float2 texCoords, int mapMask, float blend, float lod)
float4 src = SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, lod);
float4 src = SAMPLE_TEXTURE2D_LOD(_DecalAtlas2D, _trilinear_clamp_sampler_DecalAtlas2D, texCoords, lod);
src.z = src.w;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);

decalCount = _DecalCount;
decalStart = 0;
#endif
uint i = 0;
UNITY_LOOP
for (i = 0; i < decalCount; i++)
// get world space ddx/ddy for adjacent pixels to be used later in mipmap lod calculation
float3 positionWSDdx = ddx(positionWS);
float3 positionWSDdy = ddy(positionWS);
for (uint i = 0; i < decalCount; i++)
positionDS = positionDS * float3(1.0, -1.0, 1.0) + float3(0.5, 0.0f, 0.5);
float decalBlend = decalData.normalToWorld[0][3];
int diffuseIndex = decalData.normalToWorld[1][3];
int normalIndex = decalData.normalToWorld[2][3];
int maskIndex = decalData.normalToWorld[3][3];
float lod = ComputeTextureLOD(positionDS.xz, _DecalAtlasResolution);
decalBlend = ((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f))) ? decalBlend : 0; // use blend of 0 instead of an 'if' because compiler moves the lod calculation inside the 'if' which causes incorrect values
// if any of the pixels in the 2x2 quad gets rejected
positionDS = positionDS * float3(1.0, -1.0, 1.0) + float3(0.5, 0.0f, 0.5); // decal clip space
if ((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f)))
{
// clamp by half a texel to avoid sampling neighboring textures in the atlas
float2 clampAmount = float2(0.5f / _DecalAtlasResolution.x, 0.5f / _DecalAtlasResolution.y);
// Verified that lod calculation works with a test texture, looking at the shader code in Razor the lod calculation is outside the dynamic branches where the texture fetch happens,
// however compiler was placing it inside the branch that was rejecting the pixel, which was causing incorrect lod to be calculated for any 2x2 quad where any of the pixels were rejected,
// so had to use alpha blend of 0 instead of branching to solve that issue."
float2 diffuseMin = decalData.diffuseScaleBias.zw + clampAmount; // offset into atlas is in .zw
float2 diffuseMax = decalData.diffuseScaleBias.zw + decalData.diffuseScaleBias.xy - clampAmount; // scale relative to full atlas size is in .xy so total texture extent in atlas is (1,1) * scale
if(diffuseIndex != -1)
{
ApplyBlendDiffuse(DBuffer0, mask, positionDS.xz, diffuseIndex, DBUFFERHTILEBIT_DIFFUSE, decalBlend, lod);
alpha = alpha < decalBlend ? decalBlend : alpha; // use decal alpha if it higher than transparent alpha
}
float2 normalMin = decalData.normalScaleBias.zw + clampAmount;
float2 normalMax = decalData.normalScaleBias.zw + decalData.normalScaleBias.xy - clampAmount;
float2 maskMin = decalData.maskScaleBias.zw + clampAmount;
float2 maskMax = decalData.maskScaleBias.zw + decalData.maskScaleBias.xy - clampAmount;
float2 sampleDiffuse = clamp(positionDS.xz * decalData.diffuseScaleBias.xy + decalData.diffuseScaleBias.zw, diffuseMin, diffuseMax);
float2 sampleNormal = clamp(positionDS.xz * decalData.normalScaleBias.xy + decalData.normalScaleBias.zw, normalMin, normalMax);
float2 sampleMask = clamp(positionDS.xz * decalData.maskScaleBias.xy + decalData.maskScaleBias.zw, maskMin, maskMax);
// need to compute the mipmap LOD manually because we are sampling inside a loop
float3 positionDSDdx = mul(decalData.worldToDecal, float4(positionWSDdx, 0.0)).xyz; // transform the derivatives to decal space, any translation is irrelevant
float3 positionDSDdy = mul(decalData.worldToDecal, float4(positionWSDdy, 0.0)).xyz;
float2 sampleDiffuseDdx = positionDSDdx.xz * decalData.diffuseScaleBias.xy; // factor in the atlas scale
float2 sampleDiffuseDdy = positionDSDdy.xz * decalData.diffuseScaleBias.xy;
float lodDiffuse = ComputeTextureLOD(sampleDiffuseDdx, sampleDiffuseDdy, _DecalAtlasResolution);
float2 sampleNormalDdx = positionDSDdx.xz * decalData.normalScaleBias.xy;
float2 sampleNormalDdy = positionDSDdy.xz * decalData.normalScaleBias.xy;
float lodNormal = ComputeTextureLOD(sampleNormalDdx, sampleNormalDdy, _DecalAtlasResolution);
float2 sampleMaskDdx = positionDSDdx.xz * decalData.maskScaleBias.xy;
float2 sampleMaskDdy = positionDSDdy.xz * decalData.maskScaleBias.xy;
float lodMask = ComputeTextureLOD(sampleMaskDdx, sampleMaskDdy, _DecalAtlasResolution);
if(normalIndex != -1)
{
ApplyBlendNormal(DBuffer1, mask, positionDS.xz, normalIndex, DBUFFERHTILEBIT_NORMAL, (float3x3)decalData.normalToWorld, decalBlend, lod);
}
float decalBlend = decalData.normalToWorld[0][3];
if((decalData.diffuseScaleBias.x > 0) && (decalData.diffuseScaleBias.y > 0))
{
ApplyBlendDiffuse(DBuffer0, mask, sampleDiffuse, DBUFFERHTILEBIT_DIFFUSE, decalBlend, lodDiffuse);
alpha = alpha < decalBlend ? decalBlend : alpha; // use decal alpha if it is higher than transparent alpha
}
if ((decalData.normalScaleBias.x > 0) && (decalData.normalScaleBias.y > 0))
{
ApplyBlendNormal(DBuffer1, mask, sampleNormal, DBUFFERHTILEBIT_NORMAL, (float3x3)decalData.normalToWorld, decalBlend, lodNormal);
}
if(maskIndex != -1)
{
ApplyBlendMask(DBuffer2, mask, positionDS.xz, maskIndex, DBUFFERHTILEBIT_MASK, decalBlend, lod);
if ((decalData.maskScaleBias.x > 0) && (decalData.maskScaleBias.y > 0))
{
ApplyBlendMask(DBuffer2, mask, sampleMask, DBUFFERHTILEBIT_MASK, decalBlend, lodMask);
}
}
}
#else

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


// Include
//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/Wind.hlsl"
#include "../../ShaderPass/FragInputs.hlsl"
#include "../../ShaderPass/ShaderPass.cs.hlsl"

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


// Include
//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/tessellation.hlsl"
#include "CoreRP/ShaderLibrary/Tessellation.hlsl"
#include "../../ShaderPass/FragInputs.hlsl"
#include "../../ShaderPass/ShaderPass.cs.hlsl"

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


specularLighting *= 1.0 + bsdfData.fresnel0 * preLightData.energyCompensation;
#ifdef DEBUG_DISPLAY
switch(_DebugLightingMode)
if (_DebugLightingMode != 0)
switch (_DebugLightingMode)
{
diffuseLighting = lighting.direct.diffuse + bakeLightingData.bakeDiffuseLighting;
diffuseLighting = lighting.direct.diffuse + bakeLightingData.bakeDiffuseLighting;
diffuseLighting = indirectAmbientOcclusion;
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
diffuseLighting = indirectAmbientOcclusion;
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
diffuseLighting = specularOcclusion;
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
diffuseLighting = specularOcclusion;
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
#if GTAO_MULTIBOUNCE_APPROX
#if GTAO_MULTIBOUNCE_APPROX
diffuseLighting = GTAOMultiBounce(indirectAmbientOcclusion, bsdfData.diffuseColor);
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
diffuseLighting = GTAOMultiBounce(indirectAmbientOcclusion, bsdfData.diffuseColor);
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
diffuseLighting = GTAOMultiBounce(specularOcclusion, bsdfData.fresnel0);
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
break;
#endif
case DEBUGMIPMAPMODE_NONE:
diffuseLighting = bsdfData.diffuseColor;
diffuseLighting = GTAOMultiBounce(specularOcclusion, bsdfData.fresnel0);
#endif
{
{
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
}
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
}
}
else if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE)
{
diffuseLighting = bsdfData.diffuseColor;
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
}
#endif
}

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


// Include
//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/tessellation.hlsl"
#include "CoreRP/ShaderLibrary/Tessellation.hlsl"
#include "../../ShaderPass/FragInputs.hlsl"
#include "../../ShaderPass/ShaderPass.cs.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Material.hlsl


#include "Lit/Lit.hlsl"
#elif defined(UNITY_MATERIAL_UNLIT)
#include "Unlit/Unlit.hlsl"
#elif defined(UNITY_MATERIAL_STACKLIT)
#include "StackLit/StackLit.hlsl"
#endif
//-----------------------------------------------------------------------------

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Unlit/Unlit.shader


// Include
//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "../../ShaderVariables.hlsl"
#include "../../ShaderPass/FragInputs.hlsl"
#include "../../ShaderPass/ShaderPass.cs.hlsl"

33
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/Blit.shader


SamplerState sampler_PointClamp;
SamplerState sampler_LinearClamp;
uniform float4 _BlitScaleBias;
uniform float4 _BlitScaleBiasRt;
uniform float _BlitMipLevel;
struct Attributes

output.texcoord = GetFullScreenTriangleTexCoord(input.vertexID) * _BlitScaleBias.xy + _BlitScaleBias.zw;
return output;
}
Varyings VertQuad(Attributes input)
{
Varyings output;
output.positionCS = GetQuadVertexPosition(input.vertexID) * float4(_BlitScaleBiasRt.x, _BlitScaleBiasRt.y, 1, 1) + float4(_BlitScaleBiasRt.z, _BlitScaleBiasRt.w, 0, 0);
output.positionCS.xy = output.positionCS.xy * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f); //convert to -1..1
output.texcoord = GetQuadTexCoord(input.vertexID) * _BlitScaleBias.xy + _BlitScaleBias.zw;
return output;
}
float4 FragNearest(Varyings input) : SV_Target
{

#pragma fragment FragBilinear
ENDHLSL
}
// 2: Nearest quad
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
HLSLPROGRAM
#pragma vertex VertQuad
#pragma fragment FragNearest
ENDHLSL
}
// 3: Bilinear quad
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
HLSLPROGRAM
#pragma vertex VertQuad
#pragma fragment FragBilinear
ENDHLSL
}
}
Fallback Off

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassDBuffer.hlsl


clip(1.0 - positionDS); // Clip value above one
DecalSurfaceData surfaceData;
float4x4 decalToWorld = UNITY_ACCESS_INSTANCED_PROP(matrix, _NormalToWorld);
GetSurfaceData(positionDS.xz, decalToWorld, surfaceData);
float4x4 normalToWorld = UNITY_ACCESS_INSTANCED_PROP(matrix, _NormalToWorld);
GetSurfaceData(positionDS.xz, normalToWorld, surfaceData);
// have to do explicit test since compiler behavior is not defined for RW resources and discard instructions
if((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f)))

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


{
if (skyContext.skyParametersHash != 0)
{
CoreUtils.ClearCubemap(cmd, m_SkyboxCubemapRT, Color.black, true);
if (m_SupportsConvolution)
using (new ProfilingSample(cmd, "Clear Sky Environment Pass"))
CoreUtils.ClearCubemap(cmd, m_SkyboxGGXCubemapRT, Color.black, true);
CoreUtils.ClearCubemap(cmd, m_SkyboxCubemapRT, Color.black, true);
if (m_SupportsConvolution)
{
CoreUtils.ClearCubemap(cmd, m_SkyboxGGXCubemapRT, Color.black, true);
}
}
skyContext.skyParametersHash = 0;

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDAdditionalCameraEditor.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering
{
[CanEditMultipleObjects]
[CustomEditor(typeof(HDAdditionalCameraData))]
class HDAdditionalCameraDataEditor : Editor
{
public override void OnInspectorGUI()
{
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDAdditionalCameraEditor.cs.meta


fileFormatVersion: 2
guid: 7d13c99eb3063b943ad3ff72bb597a40
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/AdditionalShadowDataEditor.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
[CanEditMultipleObjects]
[CustomEditor(typeof(AdditionalShadowData))]
class AdditionalShadowDataEditor : Editor
{
public override void OnInspectorGUI()
{
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/AdditionalShadowDataEditor.cs.meta


fileFormatVersion: 2
guid: a4c41e6de0507a14487dd227f7d08b5f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDAdditionalLightDataEditor.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
[CanEditMultipleObjects]
[CustomEditor(typeof(HDAdditionalLightData))]
class HDAdditionalLightDataEditor : Editor
{
public override void OnInspectorGUI()
{
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDAdditionalLightDataEditor.cs.meta


fileFormatVersion: 2
guid: bf761ccb3da263c4cbcfa1c0ecbd05fc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/StackLit.meta


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

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit.meta


fileFormatVersion: 2
guid: 86c95bf966685564ba869d965bb5efe0
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

195
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Texture2DAtlas.cs


using System;
using System.Collections.Generic;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.Experimental.Rendering
{
public class AtlasAllocator
{
private class AtlasNode
{
public AtlasNode m_RightChild = null;
public AtlasNode m_BottomChild = null;
public Vector4 m_Rect = new Vector4(0,0,0,0); // x,y is width and height (scale) z,w offset into atlas (bias)
public AtlasNode Allocate(int width, int height)
{
// not a leaf node, try children
if(m_RightChild != null)
{
AtlasNode node = m_RightChild.Allocate(width, height);
if(node == null)
{
node = m_BottomChild.Allocate(width, height);
}
return node;
}
//leaf node, check for fit
if ((width <= m_Rect.x) && (height <= m_Rect.y))
{
// perform the split
m_RightChild = new AtlasNode();
m_BottomChild = new AtlasNode();
if (width > height) // logic to decide which way to split
{ // +--------+------+
m_RightChild.m_Rect.z = m_Rect.z + width; // | | |
m_RightChild.m_Rect.w = m_Rect.w; // +--------+------+
m_RightChild.m_Rect.x = m_Rect.x - width; // | |
m_RightChild.m_Rect.y = height; // | |
// +---------------+
m_BottomChild.m_Rect.z = m_Rect.z;
m_BottomChild.m_Rect.w = m_Rect.w + height;
m_BottomChild.m_Rect.x = m_Rect.x;
m_BottomChild.m_Rect.y = m_Rect.y - height;
}
else
{ // +---+-----------+
m_RightChild.m_Rect.z = m_Rect.z + width; // | | |
m_RightChild.m_Rect.w = m_Rect.w; // | | |
m_RightChild.m_Rect.x = m_Rect.x - width; // +---+ +
m_RightChild.m_Rect.y = m_Rect.y; // | | |
// +---+-----------+
m_BottomChild.m_Rect.z = m_Rect.z;
m_BottomChild.m_Rect.w = m_Rect.w + height;
m_BottomChild.m_Rect.x = width;
m_BottomChild.m_Rect.y = m_Rect.y - height;
}
m_Rect.x = width;
m_Rect.y = height;
return this;
}
return null;
}
public void Release()
{
if (m_RightChild != null)
{
m_RightChild.Release();
m_BottomChild.Release();
}
m_RightChild = null;
m_BottomChild = null;
}
}
private AtlasNode m_Root;
private int m_Width;
private int m_Height;
public AtlasAllocator(int width, int height)
{
m_Root = new AtlasNode();
m_Root.m_Rect.Set(width, height, 0, 0);
m_Width = width;
m_Height = height;
}
public bool Allocate(ref Vector4 result, int width, int height)
{
AtlasNode node = m_Root.Allocate(width, height);
if(node != null)
{
result = node.m_Rect;
return true;
}
else
{
result = Vector4.zero;
return false;
}
}
public void Release()
{
m_Root.Release();
m_Root = new AtlasNode();
m_Root.m_Rect.Set(m_Width, m_Height, 0, 0);
}
}
public class Texture2DAtlas
{
private RTHandleSystem.RTHandle m_AtlasTexture = null;
private int m_Width;
private int m_Height;
private RenderTextureFormat m_Format;
private AtlasAllocator m_AtlasAllocator = null;
private Dictionary<IntPtr, Vector4> m_AllocationCache = new Dictionary<IntPtr, Vector4>();
public RTHandleSystem.RTHandle AtlasTexture
{
get
{
return m_AtlasTexture;
}
}
public Texture2DAtlas(int width, int height, RenderTextureFormat format)
{
m_Width = width;
m_Height = height;
m_Format = format;
m_AtlasTexture = RTHandles.Alloc(m_Width,
m_Height,
1,
DepthBits.None,
m_Format,
FilterMode.Point,
TextureWrapMode.Clamp,
TextureDimension.Tex2D,
false,
false,
true,
false);
m_AtlasAllocator = new AtlasAllocator(width, height);
}
public void Release()
{
ResetAllocator();
RTHandles.Release(m_AtlasTexture);
}
public void ResetAllocator()
{
m_AtlasAllocator.Release();
m_AllocationCache.Clear();
}
public bool AddTexture(CommandBuffer cmd, ref Vector4 scaleBias, Texture texture)
{
IntPtr key = texture.GetNativeTexturePtr();
if (!m_AllocationCache.TryGetValue(key, out scaleBias))
{
int width = texture.width;
int height = texture.height;
if (m_AtlasAllocator.Allocate(ref scaleBias, width, height))
{
scaleBias.Scale(new Vector4(1.0f / m_Width, 1.0f / m_Height, 1.0f / m_Width, 1.0f / m_Height));
for (int mipLevel = 0; mipLevel < (texture as Texture2D).mipmapCount; mipLevel++)
{
cmd.SetRenderTarget(m_AtlasTexture, mipLevel);
HDUtils.BlitQuad(cmd, texture, new Vector4(1, 1, 0, 0), scaleBias, mipLevel, false);
}
m_AllocationCache.Add(key, scaleBias);
return true;
}
else
{
return false;
}
}
return true;
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Texture2DAtlas.cs.meta


fileFormatVersion: 2
guid: 081cfbdef2e1c014aa1d1c9aa16fb952
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

101
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/StackLit/StackLitUI.cs


using System;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
class StackLitGUI : BaseUnlitGUI
{
protected static class Styles
{
public static string InputsText = "Inputs";
public static GUIContent baseColorText = new GUIContent("Base Color + Opacity", "Albedo (RGB) and Opacity (A)");
public static GUIContent emissiveText = new GUIContent("Emissive Color", "Emissive");
public static GUIContent emissiveIntensityText = new GUIContent("Emissive Intensity", "Emissive");
public static GUIContent albedoAffectEmissiveText = new GUIContent("Albedo Affect Emissive", "Specifies whether or not the emissive color is multiplied by the albedo.");
}
protected MaterialProperty baseColor = null;
protected const string kBaseColor = "_BaseColor";
protected MaterialProperty baseColorMap = null;
protected const string kBaseColorMap = "_BaseColorMap";
protected MaterialProperty emissiveColor = null;
protected const string kEmissiveColor = "_EmissiveColor";
protected MaterialProperty emissiveColorMap = null;
protected const string kEmissiveColorMap = "_EmissiveColorMap";
protected MaterialProperty emissiveIntensity = null;
protected const string kEmissiveIntensity = "_EmissiveIntensity";
protected MaterialProperty albedoAffectEmissive = null;
protected const string kAlbedoAffectEmissive = "_AlbedoAffectEmissive";
override protected void FindMaterialProperties(MaterialProperty[] props)
{
baseColor = FindProperty(kBaseColor, props);
baseColorMap = FindProperty(kBaseColorMap, props);
emissiveColor = FindProperty(kEmissiveColor, props);
emissiveColorMap = FindProperty(kEmissiveColorMap, props);
emissiveIntensity = FindProperty(kEmissiveIntensity, props);
albedoAffectEmissive = FindProperty(kAlbedoAffectEmissive, props);
}
protected override void MaterialPropertiesGUI(Material material)
{
EditorGUILayout.LabelField(Styles.InputsText, EditorStyles.boldLabel);
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText, baseColorMap, baseColor);
m_MaterialEditor.TextureScaleOffsetProperty(baseColorMap);
m_MaterialEditor.TexturePropertySingleLine(Styles.emissiveText, emissiveColorMap, emissiveColor);
m_MaterialEditor.TextureScaleOffsetProperty(emissiveColorMap);
m_MaterialEditor.ShaderProperty(emissiveIntensity, Styles.emissiveIntensityText);
m_MaterialEditor.ShaderProperty(albedoAffectEmissive, Styles.albedoAffectEmissiveText);
var surfaceTypeValue = (SurfaceType)surfaceType.floatValue;
if (surfaceTypeValue == SurfaceType.Transparent)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField(StylesBaseUnlit.TransparencyInputsText, EditorStyles.boldLabel);
++EditorGUI.indentLevel;
DoDistortionInputsGUI();
--EditorGUI.indentLevel;
}
}
protected override void MaterialPropertiesAdvanceGUI(Material material)
{
}
protected override void VertexAnimationPropertiesGUI()
{
}
protected override bool ShouldEmissionBeEnabled(Material mat)
{
return mat.GetFloat(kEmissiveIntensity) > 0.0f;
}
protected override void SetupMaterialKeywordsAndPassInternal(Material material)
{
SetupMaterialKeywordsAndPass(material);
}
// All Setup Keyword functions must be static. It allow to create script to automatically update the shaders with a script if code change
static public void SetupMaterialKeywordsAndPass(Material material)
{
SetupBaseUnlitKeywords(material);
SetupBaseUnlitMaterialPass(material);
CoreUtils.SetKeyword(material, "_EMISSIVE_COLOR_MAP", material.GetTexture(kEmissiveColorMap));
}
}
} // namespace UnityEditor

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/StackLit/StackLitUI.cs.meta


fileFormatVersion: 2
guid: 1299689b419a58340b4da4d67c678769
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass.meta


fileFormatVersion: 2
guid: 9fd26622ba7766c4f9285e0cd3f8199c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass/StackLitDepthPass.hlsl


#ifndef SHADERPASS
#error Undefine_SHADERPASS
#endif
// NEWLITTODO : Handling of TESSELATION, DISPLACEMENT, WIND
#ifdef _ALPHATEST_ON
#define ATTRIBUTES_NEED_TEXCOORD0
#define VARYINGS_NEED_TEXCOORD0
#endif //..._ALPHATEST_ON
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass/StackLitDepthPass.hlsl.meta


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

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass/StackLitDistortionPass.hlsl


#ifndef SHADERPASS
#error Undefine_SHADERPASS
#endif
// NEWLITTODO : Handling of TESSELATION, DISPLACEMENT, HEIGHTMAP, WIND
#define ATTRIBUTES_NEED_TEXCOORD0
#define VARYINGS_NEED_TEXCOORD0
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass/StackLitDistortionPass.hlsl.meta


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

43
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass/StackLitSharePass.hlsl


#ifndef SHADERPASS
#error Undefine_SHADERPASS
#endif
// NOTE: Copied from LitSharePass.hlsl, we will need most of this, but at first, vs the unlit, we have
// diffuse lighting, and also consider the _DOUBLESIDED_ON option.
// This first set of define allow to say which attributes will be use by the mesh in the vertex and domain shader (for tesselation)
// Attributes
#define ATTRIBUTES_NEED_NORMAL
#define ATTRIBUTES_NEED_TANGENT // Always present as we require it also in case of anisotropic lighting
#define ATTRIBUTES_NEED_TEXCOORD0
#define ATTRIBUTES_NEED_TEXCOORD1
#define ATTRIBUTES_NEED_COLOR
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3) || defined(DYNAMICLIGHTMAP_ON) || defined(DEBUG_DISPLAY) || (SHADERPASS == SHADERPASS_LIGHT_TRANSPORT)
#define ATTRIBUTES_NEED_TEXCOORD2
#endif
#if defined(_REQUIRE_UV3) || defined(DEBUG_DISPLAY)
#define ATTRIBUTES_NEED_TEXCOORD3
#endif
// Varying - Use for pixel shader
// This second set of define allow to say which varyings will be output in the vertex (no more tesselation)
#define VARYINGS_NEED_POSITION_WS
#define VARYINGS_NEED_TANGENT_TO_WORLD
#define VARYINGS_NEED_TEXCOORD0
#define VARYINGS_NEED_TEXCOORD1
#ifdef ATTRIBUTES_NEED_TEXCOORD2
#define VARYINGS_NEED_TEXCOORD2
#endif
#ifdef ATTRIBUTES_NEED_TEXCOORD3
#define VARYINGS_NEED_TEXCOORD3
#endif
#define VARYINGS_NEED_COLOR
#ifdef _DOUBLESIDED_ON
#define VARYINGS_NEED_CULLFACE
#endif
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/ShaderPass/StackLitSharePass.hlsl.meta


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

41
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.cs


using UnityEngine;
using System;
//-----------------------------------------------------------------------------
// structure definition
//-----------------------------------------------------------------------------
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class StackLit : RenderPipelineMaterial
{
//-----------------------------------------------------------------------------
// SurfaceData
//-----------------------------------------------------------------------------
// Main structure that store the user data (i.e user input of master node in material graph)
[GenerateHLSL(PackingRules.Exact, false, true, 1300)]
public struct SurfaceData
{
// Standard
[SurfaceDataAttributes("Base Color", false, true)]
public Vector3 baseColor;
[SurfaceDataAttributes(new string[]{"Normal", "Normal View Space"}, true)]
public Vector3 normalWS;
};
//-----------------------------------------------------------------------------
// BSDFData
//-----------------------------------------------------------------------------
[GenerateHLSL(PackingRules.Exact, false, true, 1400)]
public struct BSDFData
{
[SurfaceDataAttributes("", false, true)]
public Vector3 diffuseColor;
[SurfaceDataAttributes(new string[] { "Normal WS", "Normal View Space" }, true)]
public Vector3 normalWS;
};
}
}

78
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.cs.hlsl


//
// This file was automatically generated. Please don't edit by hand.
//
#ifndef STACKLIT_CS_HLSL
#define STACKLIT_CS_HLSL
//
// UnityEngine.Experimental.Rendering.HDPipeline.StackLit+SurfaceData: static fields
//
#define DEBUGVIEW_STACKLIT_SURFACEDATA_BASE_COLOR (1300)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_NORMAL (1301)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_NORMAL_VIEW_SPACE (1302)
//
// UnityEngine.Experimental.Rendering.HDPipeline.StackLit+BSDFData: static fields
//
#define DEBUGVIEW_STACKLIT_BSDFDATA_DIFFUSE_COLOR (1400)
#define DEBUGVIEW_STACKLIT_BSDFDATA_NORMAL_WS (1401)
#define DEBUGVIEW_STACKLIT_BSDFDATA_NORMAL_VIEW_SPACE (1402)
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.StackLit+SurfaceData
// PackingRules = Exact
struct SurfaceData
{
float3 baseColor;
float3 normalWS;
};
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.StackLit+BSDFData
// PackingRules = Exact
struct BSDFData
{
float3 diffuseColor;
float3 normalWS;
};
//
// Debug functions
//
void GetGeneratedSurfaceDataDebug(uint paramId, SurfaceData surfacedata, inout float3 result, inout bool needLinearToSRGB)
{
switch (paramId)
{
case DEBUGVIEW_STACKLIT_SURFACEDATA_BASE_COLOR:
result = surfacedata.baseColor;
needLinearToSRGB = true;
break;
case DEBUGVIEW_STACKLIT_SURFACEDATA_NORMAL:
result = surfacedata.normalWS * 0.5 + 0.5;
break;
case DEBUGVIEW_STACKLIT_SURFACEDATA_NORMAL_VIEW_SPACE:
result = surfacedata.normalWS * 0.5 + 0.5;
break;
}
}
//
// Debug functions
//
void GetGeneratedBSDFDataDebug(uint paramId, BSDFData bsdfdata, inout float3 result, inout bool needLinearToSRGB)
{
switch (paramId)
{
case DEBUGVIEW_STACKLIT_BSDFDATA_DIFFUSE_COLOR:
result = bsdfdata.diffuseColor;
needLinearToSRGB = true;
break;
case DEBUGVIEW_STACKLIT_BSDFDATA_NORMAL_WS:
result = bsdfdata.normalWS * 0.5 + 0.5;
break;
case DEBUGVIEW_STACKLIT_BSDFDATA_NORMAL_VIEW_SPACE:
result = bsdfdata.normalWS * 0.5 + 0.5;
break;
}
}
#endif

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.cs.hlsl.meta


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

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.cs.meta


fileFormatVersion: 2
guid: c791362c2eaa3a94c807d88c81a53119
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.hlsl.meta


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

300
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.shader


Shader "HDRenderPipeline/StackLit"
{
Properties
{
// Following set of parameters represent the parameters node inside the MaterialGraph.
// They are use to fill a SurfaceData. With a MaterialGraph this should not exist.
// Reminder. Color here are in linear but the UI (color picker) do the conversion sRGB to linear
// Be careful, do not change the name here to _Color. It will conflict with the "fake" parameters (see end of properties) required for GI.
_BaseColor("BaseColor", Color) = (1,1,1,1)
_BaseColorMap("BaseColorMap", 2D) = "white" {}
_EmissiveColor("EmissiveColor", Color) = (1, 1, 1)
_EmissiveColorMap("EmissiveColorMap", 2D) = "white" {}
_EmissiveIntensity("EmissiveIntensity", Float) = 0
[ToggleUI] _AlbedoAffectEmissive("Albedo Affect Emissive", Float) = 0.0
_DistortionVectorMap("DistortionVectorMap", 2D) = "black" {}
[ToggleUI] _DistortionEnable("Enable Distortion", Float) = 0.0
[ToggleUI] _DistortionOnly("Distortion Only", Float) = 0.0
[ToggleUI] _DistortionDepthTest("Distortion Depth Test Enable", Float) = 1.0
[Enum(Add, 0, Multiply, 1)] _DistortionBlendMode("Distortion Blend Mode", Int) = 0
[HideInInspector] _DistortionSrcBlend("Distortion Blend Src", Int) = 0
[HideInInspector] _DistortionDstBlend("Distortion Blend Dst", Int) = 0
[HideInInspector] _DistortionBlurSrcBlend("Distortion Blur Blend Src", Int) = 0
[HideInInspector] _DistortionBlurDstBlend("Distortion Blur Blend Dst", Int) = 0
[HideInInspector] _DistortionBlurBlendMode("Distortion Blur Blend Mode", Int) = 0
_DistortionScale("Distortion Scale", Float) = 1
_DistortionVectorScale("Distortion Vector Scale", Float) = 2
_DistortionVectorBias("Distortion Vector Bias", Float) = -1
_DistortionBlurScale("Distortion Blur Scale", Float) = 1
_DistortionBlurRemapMin("DistortionBlurRemapMin", Float) = 0.0
_DistortionBlurRemapMax("DistortionBlurRemapMax", Float) = 1.0
// Transparency
[ToggleUI] _PreRefractionPass("PreRefractionPass", Float) = 0.0
[ToggleUI] _AlphaCutoffEnable("Alpha Cutoff Enable", Float) = 0.0
_AlphaCutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_TransparentSortPriority("_TransparentSortPriority", Float) = 0
// Stencil state
[HideInInspector] _StencilRef("_StencilRef", Int) = 2 // StencilLightingUsage.RegularLighting (fixed at compile time)
[HideInInspector] _StencilWriteMask("_StencilWriteMask", Int) = 7 // StencilMask.Lighting (fixed at compile time)
[HideInInspector] _StencilRefMV("_StencilRefMV", Int) = 128 // StencilLightingUsage.RegularLighting (fixed at compile time)
[HideInInspector] _StencilWriteMaskMV("_StencilWriteMaskMV", Int) = 128 // StencilMask.ObjectsVelocity (fixed at compile time)
// Blending state
[HideInInspector] _SurfaceType("__surfacetype", Float) = 0.0
[HideInInspector] _BlendMode("__blendmode", Float) = 0.0
[HideInInspector] _SrcBlend("__src", Float) = 1.0
[HideInInspector] _DstBlend("__dst", Float) = 0.0
[HideInInspector] _ZWrite("__zw", Float) = 1.0
[HideInInspector] _CullMode("__cullmode", Float) = 2.0
[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
[ToggleUI] _EnableFogOnTransparent("Enable Fog", Float) = 1.0
[ToggleUI] _EnableBlendModePreserveSpecularLighting("Enable Blend Mode Preserve Specular Lighting", Float) = 1.0
[ToggleUI] _DoubleSidedEnable("Double sided enable", Float) = 0.0
[Enum(Flip, 0, Mirror, 1, None, 2)] _DoubleSidedNormalMode("Double sided normal mode", Float) = 1 // This is for the editor only, see BaseLitUI.cs: _DoubleSidedConstants will be set based on the mode.
[HideInInspector] _DoubleSidedConstants("_DoubleSidedConstants", Vector) = (1, 1, -1, 0)
// Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor"
// value that exist to identify if the GI emission need to be enabled.
// In our case we don't use such a mechanism but need to keep the code quiet. We declare the value and always enable it.
// TODO: Fix the code in legacy unity so we can customize the beahvior for GI
_EmissionColor("Color", Color) = (1, 1, 1)
// HACK: GI Baking system relies on some properties existing in the shader ("_MainTex", "_Cutoff" and "_Color") for opacity handling, so we need to store our version of those parameters in the hard-coded name the GI baking system recognizes.
_MainTex("Albedo", 2D) = "white" {}
_Color("Color", Color) = (1,1,1,1)
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
}
HLSLINCLUDE
#pragma target 4.5
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
//-------------------------------------------------------------------------------------
// Variant
//-------------------------------------------------------------------------------------
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _DOUBLESIDED_ON
#pragma shader_feature _EMISSIVE_COLOR_MAP
// Keyword for transparent
#pragma shader_feature _SURFACE_TYPE_TRANSPARENT
#pragma shader_feature _ _BLENDMODE_ALPHA _BLENDMODE_ADD _BLENDMODE_PRE_MULTIPLY
#pragma shader_feature _BLENDMODE_PRESERVE_SPECULAR_LIGHTING // easily handled in material.hlsl, so adding this already.
#pragma shader_feature _ENABLE_FOG_ON_TRANSPARENT
//enable GPU instancing support
#pragma multi_compile_instancing
//-------------------------------------------------------------------------------------
// Define
//-------------------------------------------------------------------------------------
#define UNITY_MATERIAL_STACKLIT // Need to be define before including Material.hlsl
//-------------------------------------------------------------------------------------
// Include
//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "../../ShaderPass/FragInputs.hlsl"
#include "../../ShaderPass/ShaderPass.cs.hlsl"
//-------------------------------------------------------------------------------------
// variable declaration
//-------------------------------------------------------------------------------------
#include "../../Material/StackLit/StackLitProperties.hlsl"
// All our shaders use same name for entry point
#pragma vertex Vert
#pragma fragment Frag
ENDHLSL
SubShader
{
// This tags allow to use the shader replacement features
Tags{ "RenderPipeline" = "HDRenderPipeline" "RenderType" = "HDStackLitShader" }
// Caution: The outline selection in the editor use the vertex shader/hull/domain shader of the first pass declare. So it should not be the meta pass.
Pass
{
Name "Depth prepass"
Tags{ "LightMode" = "DepthForwardOnly" }
Cull[_CullMode]
ZWrite On
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DEPTH_ONLY
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/StackLitDepthPass.hlsl"
#include "StackLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL
}
// Extracts information for lightmapping, GI (emission, albedo, ...)
// This pass it not used during regular rendering.
Pass
{
Name "META"
Tags{ "LightMode" = "Meta" }
Cull Off
HLSLPROGRAM
// Lightmap memo
// DYNAMICLIGHTMAP_ON is used when we have an "enlighten lightmap" ie a lightmap updated at runtime by enlighten.This lightmap contain indirect lighting from realtime lights and realtime emissive material.Offline baked lighting(from baked material / light,
// both direct and indirect lighting) will hand up in the "regular" lightmap->LIGHTMAP_ON.
#define SHADERPASS SHADERPASS_LIGHT_TRANSPORT
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/StackLitSharePass.hlsl"
#include "StackLitData.hlsl"
#include "../../ShaderPass/ShaderPassLightTransport.hlsl"
ENDHLSL
}
Pass
{
Name "ShadowCaster"
Tags{ "LightMode" = "ShadowCaster" }
Cull[_CullMode]
ZClip [_ZClip]
ZWrite On
ZTest LEqual
ColorMask 0
HLSLPROGRAM
#define SHADERPASS SHADERPASS_SHADOWS
#define USE_LEGACY_UNITY_MATRIX_VARIABLES
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/StackLitDepthPass.hlsl"
#include "StackLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL
}
Pass
{
Name "Distortion" // Name is not used
Tags { "LightMode" = "DistortionVectors" } // This will be only for transparent object based on the RenderQueue index
Blend [_DistortionSrcBlend] [_DistortionDstBlend], [_DistortionBlurSrcBlend] [_DistortionBlurDstBlend]
BlendOp Add, [_DistortionBlurBlendOp]
ZTest [_ZTestModeDistortion]
ZWrite off
Cull [_CullMode]
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DISTORTION
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/StackLitDistortionPass.hlsl"
#include "StackLitData.hlsl"
#include "../../ShaderPass/ShaderPassDistortion.hlsl"
ENDHLSL
}
// StackLit shader always render in forward
Pass
{
Name "Forward" // Name is not used
Tags { "LightMode" = "ForwardOnly" }
Stencil
{
WriteMask [_StencilWriteMask]
Ref [_StencilRef]
Comp Always
Pass Replace
}
Blend [_SrcBlend] [_DstBlend]
// In case of forward we want to have depth equal for opaque mesh
ZTest [_ZTestDepthEqualForOpaque]
ZWrite [_ZWrite]
Cull [_CullModeForward]
//
// NOTE: For _CullModeForward, see BaseLitUI and the handling of TransparentBackfaceEnable:
// Basically, we need to use it to support a TransparentBackface pass before this pass
// (and it should be placed just before this one) for separate backface and frontface rendering,
// eg for "hair shader style" approximate sorting, see eg Thorsten Scheuermann writeups on this:
// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.607.1272&rep=rep1&type=pdf
// http://amd-dev.wpengine.netdna-cdn.com/wordpress/media/2012/10/Scheuermann_HairSketchSlides.pdf
// http://web.engr.oregonstate.edu/~mjb/cs519/Projects/Papers/HairRendering.pdf
//
// See Lit.shader and the order of the passes after a DistortionVectors, we have:
// TransparentDepthPrepass, TransparentBackface, Forward, TransparentDepthPostpass
HLSLPROGRAM
#pragma multi_compile _ DEBUG_DISPLAY
//NEWLITTODO
//#pragma multi_compile _ LIGHTMAP_ON
//#pragma multi_compile _ DIRLIGHTMAP_COMBINED
//#pragma multi_compile _ DYNAMICLIGHTMAP_ON
//#pragma multi_compile _ SHADOWS_SHADOWMASK
// #include "../../Lighting/Forward.hlsl" : nothing left in there.
//#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
// In case of opaque we don't want to perform the alpha test, it is done in depth prepass and we use depth equal for ztest (setup from UI)
#ifndef _SURFACE_TYPE_TRANSPARENT
#define SHADERPASS_FORWARD_BYPASS_ALPHA_TEST
#endif
#include "../../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#include "../../Debug/DebugDisplay.hlsl"
#endif
#include "../../Lighting/Lighting.hlsl"
//...this will include #include "../../Material/Material.hlsl" but also LightLoop which the forward pass directly uses.
#include "ShaderPass/StackLitSharePass.hlsl"
#include "StackLitData.hlsl"
#include "../../ShaderPass/ShaderPassForward.hlsl"
ENDHLSL
}
}
CustomEditor "Experimental.Rendering.HDPipeline.StackLitGUI"
}

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.shader.meta


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

71
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLitData.hlsl


//-------------------------------------------------------------------------------------
// Fill SurfaceData/Builtin data function
//-------------------------------------------------------------------------------------
#include "../MaterialUtilities.hlsl"
void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs posInput, out SurfaceData surfaceData, out BuiltinData builtinData)
{
ApplyDoubleSidedFlipOrMirror(input); // Apply double sided flip on the vertex normal
// NEWLITTODO:
// For now, just use the interpolated vertex normal. This has been normalized in the initial fragment interpolators unpacking.
// Eventually, we want to share all the LitData LayerTexCoord (and surface gradient frame + uv, planar, triplanar, etc.) logic, also
// spread in LitDataIndividualLayer and LitDataMeshModification.
surfaceData.normalWS = input.worldToTangent[2].xyz;
float2 baseColorMapUv = TRANSFORM_TEX(input.texCoord0, _BaseColorMap);
surfaceData.baseColor = SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, baseColorMapUv).rgb * _BaseColor.rgb;
float alpha = SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, baseColorMapUv).a * _BaseColor.a;
#ifdef _ALPHATEST_ON
//NEWLITTODO: Once we include those passes in the main StackLit.shader, add handling of CUTOFF_TRANSPARENT_DEPTH_PREPASS and _POSTPASS
// and the related properties (in the .shader) and uniforms (in the StackLitProperties file) _AlphaCutoffPrepass, _AlphaCutoffPostpass
DoAlphaTest(alpha, _AlphaCutoff);
#endif
#if defined(DEBUG_DISPLAY)
if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE)
{
surfaceData.color = GetTextureDataDebug(_DebugMipMapMode, baseColorMapUv, _BaseColorMap, _BaseColorMap_TexelSize, _BaseColorMap_MipInfo, surfaceData.color);
}
#endif
// Builtin Data
// NEWLITTODO: for all BuiltinData, might need to just refactor and use a comon function like that
// contained in LitBuiltinData.hlsl
builtinData.opacity = alpha;
builtinData.bakeDiffuseLighting = float3(0.0, 0.0, 0.0);
// Emissive Intensity is only use here, but is part of BuiltinData to enforce UI parameters as we want the users to fill one color and one intensity
builtinData.emissiveIntensity = _EmissiveIntensity;
builtinData.emissiveColor = _EmissiveColor * builtinData.emissiveIntensity * lerp(float3(1.0, 1.0, 1.0), surfaceData.baseColor.rgb, _AlbedoAffectEmissive);
#ifdef _EMISSIVE_COLOR_MAP
builtinData.emissiveColor *= SAMPLE_TEXTURE2D(_EmissiveColorMap, sampler_EmissiveColorMap, TRANSFORM_TEX(input.texCoord0, _EmissiveColorMap)).rgb;
#endif
builtinData.velocity = float2(0.0, 0.0);
//NEWLITTODO: shader feature SHADOWS_SHADOWMASK not there yet.
builtinData.shadowMask0 = 0.0;
builtinData.shadowMask1 = 0.0;
builtinData.shadowMask2 = 0.0;
builtinData.shadowMask3 = 0.0;
#if (SHADERPASS == SHADERPASS_DISTORTION) || defined(DEBUG_DISPLAY)
float3 distortion = SAMPLE_TEXTURE2D(_DistortionVectorMap, sampler_DistortionVectorMap, input.texCoord0).rgb;
distortion.rg = distortion.rg * _DistortionVectorScale.xx + _DistortionVectorBias.xx;
builtinData.distortion = distortion.rg * _DistortionScale;
builtinData.distortionBlur = clamp(distortion.b * _DistortionBlurScale, 0.0, 1.0) * (_DistortionBlurRemapMax - _DistortionBlurRemapMin) + _DistortionBlurRemapMin;
#else
builtinData.distortion = float2(0.0, 0.0);
builtinData.distortionBlur = 0.0;
#endif
builtinData.depthOffset = 0.0;
}

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLitData.hlsl.meta


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

45
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLitProperties.hlsl


// ===========================================================================
// WARNING:
// On PS4, texture/sampler declarations need to be outside of CBuffers
// Otherwise those parameters are not bound correctly at runtime.
// ===========================================================================
TEXTURE2D(_DistortionVectorMap);
SAMPLER(sampler_DistortionVectorMap);
TEXTURE2D(_EmissiveColorMap);
SAMPLER(sampler_EmissiveColorMap);
TEXTURE2D(_BaseColorMap);
SAMPLER(sampler_BaseColorMap);
CBUFFER_START(UnityPerMaterial)
float4 _BaseColor;
float4 _BaseColorMap_ST;
float4 _BaseColorMap_TexelSize;
float4 _BaseColorMap_MipInfo;
float3 _EmissiveColor;
float4 _EmissiveColorMap_ST;
float _EmissiveIntensity;
float _AlbedoAffectEmissive;
float _AlphaCutoff;
float4 _DoubleSidedConstants;
float _DistortionScale;
float _DistortionVectorScale;
float _DistortionVectorBias;
float _DistortionBlurScale;
float _DistortionBlurRemapMin;
float _DistortionBlurRemapMax;
// Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor"
// value that exist to identify if the GI emission need to be enabled.
// In our case we don't use such a mechanism but need to keep the code quiet. We declare the value and always enable it.
// TODO: Fix the code in legacy unity so we can customize the behavior for GI
float3 _EmissionColor;
CBUFFER_END

9
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLitProperties.hlsl.meta


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

560
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/StackLit/StackLit.hlsl


//-----------------------------------------------------------------------------
// SurfaceData and BSDFData
//-----------------------------------------------------------------------------
// SurfaceData is defined in StackLit.cs which generates StackLit.cs.hlsl
#include "StackLit.cs.hlsl"
//#include "../SubsurfaceScattering/SubsurfaceScattering.hlsl"
//#include "CoreRP/ShaderLibrary/VolumeRendering.hlsl"
//NEWLITTODO : wireup CBUFFERs for ambientocclusion, and other uniforms and samplers used:
//
// We need this for AO, Depth/Color pyramids, LTC lights data, FGD pre-integrated data.
//
// Also add options at the top of this file, see Lit.hlsl.
// This function is use to help with debugging and must be implemented by any lit material
// Implementer must take into account what are the current override component and
// adjust SurfaceData properties accordingdly
void ApplyDebugToSurfaceData(float3x3 worldToTangent, inout SurfaceData surfaceData)
{
#ifdef DEBUG_DISPLAY
// NOTE: THe _Debug* uniforms come from /HDRP/Debug/DebugDisplay.hlsl
// Override value if requested by user
// this can be use also in case of debug lighting mode like diffuse only
bool overrideAlbedo = _DebugLightingAlbedo.x != 0.0;
bool overrideSmoothness = _DebugLightingSmoothness.x != 0.0;
bool overrideNormal = _DebugLightingNormal.x != 0.0;
if (overrideAlbedo)
{
float3 overrideAlbedoValue = _DebugLightingAlbedo.yzw;
surfaceData.baseColor = overrideAlbedoValue;
}
if (overrideSmoothness)
{
//NEWLITTODO
//float overrideSmoothnessValue = _DebugLightingSmoothness.y;
//surfaceData.perceptualSmoothness = overrideSmoothnessValue;
}
if (overrideNormal)
{
surfaceData.normalWS = worldToTangent[2];
}
#endif
}
// This function is similar to ApplyDebugToSurfaceData but for BSDFData
//
// NOTE:
//
// This will be available and used in ShaderPassForward.hlsl since in StackLit.shader,
// just before including the core code of the pass (ShaderPassForward.hlsl) we include
// Material.hlsl (or Lighting.hlsl which includes it) which in turn includes us,
// StackLit.shader, via the #if defined(UNITY_MATERIAL_*) glue mechanism.
//
void ApplyDebugToBSDFData(inout BSDFData bsdfData)
{
#ifdef DEBUG_DISPLAY
// Override value if requested by user
// this can be use also in case of debug lighting mode like specular only
//NEWLITTODO
//bool overrideSpecularColor = _DebugLightingSpecularColor.x != 0.0;
//if (overrideSpecularColor)
//{
// float3 overrideSpecularColor = _DebugLightingSpecularColor.yzw;
// bsdfData.fresnel0 = overrideSpecularColor;
//}
#endif
}
//-----------------------------------------------------------------------------
// conversion function for forward
//-----------------------------------------------------------------------------
BSDFData ConvertSurfaceDataToBSDFData(SurfaceData surfaceData)
{
BSDFData bsdfData;
ZERO_INITIALIZE(BSDFData, bsdfData);
// NEWLITTODO: will be much more involved obviously, and use metallic, etc.
bsdfData.diffuseColor = surfaceData.baseColor;
bsdfData.normalWS = surfaceData.normalWS;
ApplyDebugToBSDFData(bsdfData);
return bsdfData;
}
//-----------------------------------------------------------------------------
// Debug method (use to display values)
//-----------------------------------------------------------------------------
void GetSurfaceDataDebug(uint paramId, SurfaceData surfaceData, inout float3 result, inout bool needLinearToSRGB)
{
GetGeneratedSurfaceDataDebug(paramId, surfaceData, result, needLinearToSRGB);
// Overide debug value output to be more readable
switch (paramId)
{
case DEBUGVIEW_LIT_SURFACEDATA_NORMAL_VIEW_SPACE:
// Convert to view space
result = TransformWorldToViewDir(surfaceData.normalWS) * 0.5 + 0.5;
break;
}
}
void GetBSDFDataDebug(uint paramId, BSDFData bsdfData, inout float3 result, inout bool needLinearToSRGB)
{
GetGeneratedBSDFDataDebug(paramId, bsdfData, result, needLinearToSRGB);
// Overide debug value output to be more readable
switch (paramId)
{
case DEBUGVIEW_LIT_BSDFDATA_NORMAL_VIEW_SPACE:
// Convert to view space
result = TransformWorldToViewDir(bsdfData.normalWS) * 0.5 + 0.5;
break;
}
}
//-----------------------------------------------------------------------------
// PreLightData
//
// Make sure we respect naming conventions to reuse ShaderPassForward as is,
// ie struct (even if opaque to the ShaderPassForward) name is PreLightData,
// GetPreLightData prototype.
//-----------------------------------------------------------------------------
// Precomputed lighting data to send to the various lighting functions
struct PreLightData
{
float NdotV; // Could be negative due to normal mapping, use ClampNdotV()
//NEWLITTODO
};
PreLightData GetPreLightData(float3 V, PositionInputs posInput, inout BSDFData bsdfData)
{
PreLightData preLightData;
ZERO_INITIALIZE(PreLightData, preLightData);
float3 N = bsdfData.normalWS;
preLightData.NdotV = dot(N, V);
//float NdotV = ClampNdotV(preLightData.NdotV);
return preLightData;
}
//-----------------------------------------------------------------------------
// bake lighting function
//-----------------------------------------------------------------------------
//
// GetBakedDiffuseLighting will be called from ShaderPassForward.hlsl.
//
// GetBakedDiffuseLighting function compute the bake lighting + emissive color to be store in emissive buffer (Deferred case)
// In forward it must be add to the final contribution.
// This function require the 3 structure surfaceData, builtinData, bsdfData because it may require both the engine side data, and data that will not be store inside the gbuffer.
float3 GetBakedDiffuseLighting(SurfaceData surfaceData, BuiltinData builtinData, BSDFData bsdfData, PreLightData preLightData)
{
//NEWLITTODO
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_LUX_METER)
{
// The lighting in SH or lightmap is assume to contain bounced light only (i.e no direct lighting), and is divide by PI (i.e Lambert is apply), so multiply by PI here to get back the illuminance
return builtinData.bakeDiffuseLighting * PI;
}
#endif
//NEWLITTODO
// Premultiply bake diffuse lighting information with DisneyDiffuse pre-integration
//return builtinData.bakeDiffuseLighting * preLightData.diffuseFGD * surfaceData.ambientOcclusion * bsdfData.diffuseColor + builtinData.emissiveColor;
return builtinData.bakeDiffuseLighting * bsdfData.diffuseColor; //...todo, just to return something for now, .bakeDiffuseLighting is bogus for now anyway.
}
//-----------------------------------------------------------------------------
// light transport functions
//-----------------------------------------------------------------------------
LightTransportData GetLightTransportData(SurfaceData surfaceData, BuiltinData builtinData, BSDFData bsdfData)
{
LightTransportData lightTransportData;
// diffuseColor for lightmapping should basically be diffuse color.
// But rough metals (black diffuse) still scatter quite a lot of light around, so
// we want to take some of that into account too.
//NEWLITTODO
//float roughness = PerceptualRoughnessToRoughness(bsdfData.perceptualRoughness);
//lightTransportData.diffuseColor = bsdfData.diffuseColor + bsdfData.fresnel0 * roughness * 0.5 * surfaceData.metallic;
lightTransportData.diffuseColor = bsdfData.diffuseColor;
lightTransportData.emissiveColor = builtinData.emissiveColor;
return lightTransportData;
}
//-----------------------------------------------------------------------------
// LightLoop related function (Only include if required)
// HAS_LIGHTLOOP is define in Lighting.hlsl
//-----------------------------------------------------------------------------
#ifdef HAS_LIGHTLOOP
#ifndef _SURFACE_TYPE_TRANSPARENT
// For /Lighting/LightEvaluation.hlsl:
#define USE_DEFERRED_DIRECTIONAL_SHADOWS // Deferred shadows are always enabled for opaque objects
#endif
#include "../../Lighting/LightEvaluation.hlsl"
#include "../../Lighting/Reflection/VolumeProjection.hlsl"
//-----------------------------------------------------------------------------
// Lighting structure for light accumulation
//-----------------------------------------------------------------------------
// These structure allow to accumulate lighting accross the Lit material
// AggregateLighting is init to zero and transfer to EvaluateBSDF, but the LightLoop can't access its content.
//
// In fact, all structures here are opaque but used by LightLoop.hlsl.
// The Accumulate* functions are also used by LightLoop to accumulate the contributions of lights.
//
struct DirectLighting
{
float3 diffuse;
float3 specular;
};
struct IndirectLighting
{
float3 specularReflected;
float3 specularTransmitted;
};
struct AggregateLighting
{
DirectLighting direct;
IndirectLighting indirect;
};
void AccumulateDirectLighting(DirectLighting src, inout AggregateLighting dst)
{
dst.direct.diffuse += src.diffuse;
dst.direct.specular += src.specular;
}
void AccumulateIndirectLighting(IndirectLighting src, inout AggregateLighting dst)
{
dst.indirect.specularReflected += src.specularReflected;
dst.indirect.specularTransmitted += src.specularTransmitted;
}
//-----------------------------------------------------------------------------
// BSDF share between directional light, punctual light and area light (reference)
//-----------------------------------------------------------------------------
// NEWLITTODO
// This function apply BSDF. Assumes that NdotL is positive.
void BSDF( float3 V, float3 L, float NdotL, float3 positionWS, PreLightData preLightData, BSDFData bsdfData,
out float3 diffuseLighting,
out float3 specularLighting)
{
float diffuseTerm = Lambert();
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
diffuseLighting = diffuseTerm;
specularLighting = float3(0.0, 0.0, 0.0);
}
//-----------------------------------------------------------------------------
// EvaluateBSDF_Directional
//-----------------------------------------------------------------------------
DirectLighting EvaluateBSDF_Directional(LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput, PreLightData preLightData,
DirectionalLightData lightData, BSDFData bsdfData,
BakeLightingData bakeLightingData)
{
DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
float3 N = bsdfData.normalWS;
float3 L = -lightData.forward; // Lights point backward in Unity
//float NdotV = ClampNdotV(preLightData.NdotV);
float NdotL = dot(N, L);
//float LdotV = dot(L, V);
// color and attenuation are outputted by EvaluateLight:
float3 color;
float attenuation;
EvaluateLight_Directional(lightLoopContext, posInput, lightData, bakeLightingData, N, L, color, attenuation);
float intensity = max(0, attenuation * NdotL); // Warning: attenuation can be greater than 1 due to the inverse square attenuation (when position is close to light)
// Note: We use NdotL here to early out, but in case of clear coat this is not correct. But we are ok with this
UNITY_BRANCH if (intensity > 0.0)
{
BSDF(V, L, NdotL, posInput.positionWS, preLightData, bsdfData, lighting.diffuse, lighting.specular);
lighting.diffuse *= intensity * lightData.diffuseScale;
lighting.specular *= intensity * lightData.specularScale;
}
// NEWLITTODO: Mixed thickness, transmission
// Save ALU by applying light and cookie colors only once.
lighting.diffuse *= color;
lighting.specular *= color;
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_LUX_METER)
{
// Only lighting, not BSDF
lighting.diffuse = color * intensity * lightData.diffuseScale;
}
#endif
return lighting;
}
//-----------------------------------------------------------------------------
// EvaluateBSDF_Punctual (supports spot, point and projector lights)
//-----------------------------------------------------------------------------
DirectLighting EvaluateBSDF_Punctual(LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightData lightData, BSDFData bsdfData, BakeLightingData bakeLightingData)
{
DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
float3 lightToSample = posInput.positionWS - lightData.positionWS;
int lightType = lightData.lightType;
float3 L;
float4 distances; // {d, d^2, 1/d, d_proj}
distances.w = dot(lightToSample, lightData.forward);
if (lightType == GPULIGHTTYPE_PROJECTOR_BOX)
{
L = -lightData.forward;
distances.xyz = 1; // No distance or angle attenuation
}
else
{
float3 unL = -lightToSample;
float distSq = dot(unL, unL);
float distRcp = rsqrt(distSq);
float dist = distSq * distRcp;
L = unL * distRcp;
distances.xyz = float3(dist, distSq, distRcp);
}
float3 N = bsdfData.normalWS;
float NdotV = ClampNdotV(preLightData.NdotV);
float NdotL = dot(N, L);
float LdotV = dot(L, V);
// NEWLITTODO: mixedThickness, transmission
float3 color;
float attenuation;
EvaluateLight_Punctual(lightLoopContext, posInput, lightData, bakeLightingData, N, L,
lightToSample, distances, color, attenuation);
float intensity = max(0, attenuation * NdotL); // Warning: attenuation can be greater than 1 due to the inverse square attenuation (when position is close to light)
// Note: We use NdotL here to early out, but in case of clear coat this is not correct. But we are ok with this
UNITY_BRANCH if (intensity > 0.0)
{
// Simulate a sphere light with this hack
// Note that it is not correct with our pre-computation of PartLambdaV (mean if we disable the optimization we will not have the
// same result) but we don't care as it is a hack anyway
//NEWLITTODO: Do we want this hack in stacklit ? Yes we have area lights, but cheap and not much maintenance to leave it here.
// For now no roughness anyways.
//bsdfData.coatRoughness = max(bsdfData.coatRoughness, lightData.minRoughness);
//bsdfData.roughnessT = max(bsdfData.roughnessT, lightData.minRoughness);
//bsdfData.roughnessB = max(bsdfData.roughnessB, lightData.minRoughness);
BSDF(V, L, NdotL, posInput.positionWS, preLightData, bsdfData, lighting.diffuse, lighting.specular);
lighting.diffuse *= intensity * lightData.diffuseScale;
lighting.specular *= intensity * lightData.specularScale;
}
//NEWLITTODO : transmission
// Save ALU by applying light and cookie colors only once.
lighting.diffuse *= color;
lighting.specular *= color;
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_LUX_METER)
{
// Only lighting, not BSDF
lighting.diffuse = color * intensity * lightData.diffuseScale;
}
#endif
return lighting;
}
// NEWLITTODO: For a refence rendering option for area light, like LIT_DISPLAY_REFERENCE_AREA option in eg EvaluateBSDF_<area light type> :
//#include "LitReference.hlsl"
//-----------------------------------------------------------------------------
// EvaluateBSDF_Line - Approximation with Linearly Transformed Cosines
//-----------------------------------------------------------------------------
DirectLighting EvaluateBSDF_Line( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightData lightData, BSDFData bsdfData, BakeLightingData bakeLightingData)
{
DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
//NEWLITTODO
return lighting;
}
//-----------------------------------------------------------------------------
// EvaluateBSDF_Area - Approximation with Linearly Transformed Cosines
//-----------------------------------------------------------------------------
// #define ELLIPSOIDAL_ATTENUATION
DirectLighting EvaluateBSDF_Rect( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightData lightData, BSDFData bsdfData, BakeLightingData bakeLightingData)
{
DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
//NEWLITTODO
return lighting;
}
DirectLighting EvaluateBSDF_Area(LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightData lightData,
BSDFData bsdfData, BakeLightingData bakeLightingData)
{
if (lightData.lightType == GPULIGHTTYPE_LINE)
{
return EvaluateBSDF_Line(lightLoopContext, V, posInput, preLightData, lightData, bsdfData, bakeLightingData);
}
else
{
return EvaluateBSDF_Rect(lightLoopContext, V, posInput, preLightData, lightData, bsdfData, bakeLightingData);
}
}
//-----------------------------------------------------------------------------
// EvaluateBSDF_SSLighting for screen space lighting
// ----------------------------------------------------------------------------
IndirectLighting EvaluateBSDF_SSLighting(LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, BSDFData bsdfData,
EnvLightData envLightData,
int GPUImageBasedLightingType,
inout float hierarchyWeight)
{
IndirectLighting lighting;
ZERO_INITIALIZE(IndirectLighting, lighting);
//NEWLITTODO
return lighting;
}
//-----------------------------------------------------------------------------
// EvaluateBSDF_Env
// ----------------------------------------------------------------------------
// _preIntegratedFGD and _CubemapLD are unique for each BRDF
IndirectLighting EvaluateBSDF_Env( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, EnvLightData lightData, BSDFData bsdfData,
int influenceShapeType, int GPUImageBasedLightingType,
inout float hierarchyWeight)
{
IndirectLighting lighting;
ZERO_INITIALIZE(IndirectLighting, lighting);
//NEWLITTODO
return lighting;
}
//-----------------------------------------------------------------------------
// PostEvaluateBSDF
// ----------------------------------------------------------------------------
void PostEvaluateBSDF( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, BSDFData bsdfData, BakeLightingData bakeLightingData, AggregateLighting lighting,
out float3 diffuseLighting, out float3 specularLighting)
{
// Apply the albedo to the direct diffuse lighting and that's about it.
// diffuse lighting has already had the albedo applied in GetBakedDiffuseLighting().
diffuseLighting = bsdfData.diffuseColor * lighting.direct.diffuse + bakeLightingData.bakeDiffuseLighting;
specularLighting = lighting.direct.specular; // should be 0 for now.
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_LUX_METER)
{
diffuseLighting = lighting.direct.diffuse + bakeLightingData.bakeDiffuseLighting;
}
else if (_DebugLightingMode == DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_OCCLUSION_FROM_SSAO)
{
// NEWLITTODO
//diffuseLighting = indirectAmbientOcclusion;
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
}
else if (_DebugLightingMode == DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_OCCLUSION_FROM_SSAO)
{
// NEWLITTODO
//diffuseLighting = specularOcclusion;
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
}
#if GTAO_MULTIBOUNCE_APPROX
else if (_DebugLightingMode == DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_GTAO_FROM_SSAO)
{
// NEWLITTODO
//diffuseLighting = GTAOMultiBounce(indirectAmbientOcclusion, bsdfData.diffuseColor);
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
}
else if (_DebugLightingMode == DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_GTAO_FROM_SSAO)
{
// NEWLITTODO
//diffuseLighting = GTAOMultiBounce(specularOcclusion, bsdfData.fresnel0);
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
}
#endif
else if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE)
{
// NEWLITTODO
//diffuseLighting = bsdfData.diffuseColor;
specularLighting = float3(0.0, 0.0, 0.0); // Disable specular lighting
}
#endif
}
#endif // #ifdef HAS_LIGHTLOOP
正在加载...
取消
保存