浏览代码

Merge branch 'master' of https://github.com/Unity-Technologies/ScriptableRenderLoop into Branch_DebugMenu2

# Conflicts:
#	Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
/RenderPassXR_Sandbox
Julien Ignace 8 年前
当前提交
205fb8de
共有 46 个文件被更改,包括 2602 次插入1731 次删除
  1. 18
      Assets/GraphicsTests/RenderPipeline/LightweightPipeline/Assets/LDPipe_Shader/LDPipe_UnlitMat.mat
  2. 3
      Assets/GraphicsTests/RenderPipeline/LightweightPipeline/Assets/LDPipe_Shader/LDPipe_UnlitMatTexture.mat
  3. 102
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs
  4. 41
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs
  5. 94
      Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
  6. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.asset
  7. 15
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs
  8. 91
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs
  9. 35
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs
  10. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader
  11. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader
  12. 8
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs
  13. 9
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/LitUI.cs
  14. 236
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs
  15. 72
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl
  16. 4
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader
  17. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitData.hlsl
  18. 5
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitDataInternal.hlsl
  19. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader
  20. 998
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.DisneyDiffuse.cs
  21. 998
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.GGX.cs
  22. 16
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CombineSubsurfaceScattering.shader
  23. 111
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringProfile.cs
  24. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.cs
  25. 10
      Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/RenderPipelineResources.cs
  26. 4
      Assets/ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawSssProfile.shader
  27. 4
      Assets/ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader
  28. 28
      Assets/ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/VaryingMesh.hlsl
  29. 38
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Utilities.cs
  30. 83
      Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightPipelineUpgraders.cs
  31. 6
      Assets/ScriptableRenderPipeline/ShaderLibrary/CommonMaterial.hlsl
  32. 12
      Assets/TestScenes/HDTest/GraphicTest/Common/Dragon/DragonStatueSpecular.mat
  33. 999
      ImageTemplates/LightweightPipeline/Scenes/Shaders/LDPipe_LitShaderMaps.unity.png
  34. 2
      ProjectSettings/GraphicsSettings.asset
  35. 23
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/RenderPipelineMaterial.cs
  36. 12
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/RenderPipelineMaterial.cs.meta
  37. 53
      Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightShaderHelper.cs
  38. 12
      Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightShaderHelper.cs.meta
  39. 9
      Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI.meta
  40. 81
      Assets/ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightUnlit.shader
  41. 9
      Assets/ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightUnlit.shader.meta
  42. 68
      Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightUnlitGUI.cs
  43. 12
      Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightUnlitGUI.cs.meta
  44. 0
      /Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightPipelineMaterialEditor.cs.meta
  45. 0
      /Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightPipelineMaterialEditor.cs

18
Assets/GraphicsTests/RenderPipeline/LightweightPipeline/Assets/LDPipe_Shader/LDPipe_UnlitMat.mat


m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: LDPipe_UnlitMat
m_Shader: {fileID: 10755, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords: _EMISSION _NORMALMAP _SPECGLOSSMAP_BASE_ALPHA
m_Shader: {fileID: 4800000, guid: 650dd9526735d5b46b79224bc6e94025, type: 3}
m_ShaderKeywords: _ALPHABLEND_ON _NORMALMAP _SPECGLOSSMAP_BASE_ALPHA
m_CustomRenderQueue: -1
stringTagMap: {}
m_CustomRenderQueue: 3000
stringTagMap:
RenderType: Transparent
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3

- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _DstBlend: 10
- _Mode: 0
- _Mode: 2
- _OcclusionStrength: 1
- _Parallax: 0.02
- _ReflectionSource: 0

- _SpecularHighlights: 1
- _SrcBlend: 1
- _SrcBlend: 5
- _ZWrite: 1
- _ZWrite: 0
- _MainColor: {r: 1, g: 0, b: 0, a: 1}
- _ReflectColor: {r: 1, g: 1, b: 1, a: 1}
- _SpecColor: {r: 1, g: 1, b: 1, a: 1}

3
Assets/GraphicsTests/RenderPipeline/LightweightPipeline/Assets/LDPipe_Shader/LDPipe_UnlitMatTexture.mat


m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: LDPipe_UnlitMatTexture
m_Shader: {fileID: 10752, guid: 0000000000000000f000000000000000, type: 0}
m_Shader: {fileID: 4800000, guid: 650dd9526735d5b46b79224bc6e94025, type: 3}
m_ShaderKeywords: _EMISSION _NORMALMAP _SPECGLOSSMAP_BASE_ALPHA
m_LightmapFlags: 4
m_EnableInstancingVariants: 0

m_Colors:
- _Color: {r: 0.9264706, g: 0.095371954, b: 0.095371954, a: 1}
- _EmissionColor: {r: 0.20663926, g: 0.24034719, b: 0.28676468, a: 1}
- _MainColor: {r: 1, g: 1, b: 1, a: 1}
- _ReflectColor: {r: 1, g: 1, b: 1, a: 1}
- _SpecColor: {r: 1, g: 1, b: 1, a: 1}

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


DebugMenuManager.instance.AddDebugItem<bool>("Rendering", "Display Opaque",() => renderingDebugSettings.displayOpaqueObjects, (value) => renderingDebugSettings.displayOpaqueObjects = (bool)value);
DebugMenuManager.instance.AddDebugItem<bool>("Rendering", "Display Transparency",() => renderingDebugSettings.displayTransparentObjects, (value) => renderingDebugSettings.displayTransparentObjects = (bool)value);
DebugMenuManager.instance.AddDebugItem<bool>("Rendering", "Enable Distortion",() => renderingDebugSettings.enableDistortion, (value) => renderingDebugSettings.enableDistortion = (bool)value);
DebugMenuManager.instance.AddDebugItem<bool>("Rendering", "Enable Subsurface Scattering",() => renderingDebugSettings.enableSSS, (value) => renderingDebugSettings.enableSSS = (bool)value);
DebugMenuManager.instance.AddDebugItem<bool>("Rendering", "Enable Subsurface Scattering",() => renderingDebugSettings.enableSSSAndTransmission, (value) => renderingDebugSettings.enableSSSAndTransmission = (bool)value);
}
public void OnValidate()

void FillWithProperties(Type type, GUIContent[] debugViewMaterialStrings, int[] debugViewMaterialValues, string strSubNameSpace, ref int index)
// className include the additional "/"
void FillWithProperties(Type type, GUIContent[] debugViewMaterialStrings, int[] debugViewMaterialValues, string className, ref int index)
{
var attributes = type.GetCustomAttributes(true);
// Get attribute to get the start number of the value for the enum

}
}
fieldName = strSubNameSpace + fieldName;
fieldName = className + fieldName;
debugViewMaterialStrings[index] = new GUIContent(fieldName);
debugViewMaterialValues[index] = attr.paramDefinesStart + (int)localIndex;

}
}
string GetSubNameSpaceName(Type type)
public class MaterialItem
return type.Namespace.Substring(type.Namespace.LastIndexOf((".")) + 1) + "/";
}
public String className;
public Type surfaceDataType;
public Type bsdfDataType;
};
var varyingNames = Enum.GetNames(typeof(Attributes.DebugViewVarying));
debugViewMaterialVaryingStrings = new GUIContent[varyingNames.Length];
debugViewMaterialVaryingValues = new int[varyingNames.Length];
var gbufferNames = Enum.GetNames(typeof(Attributes.DebugViewGbuffer));
debugViewMaterialGBufferStrings = new GUIContent[gbufferNames.Length + typeof(Lit.BSDFData).GetFields().Length];
debugViewMaterialGBufferValues = new int[gbufferNames.Length + typeof(Lit.BSDFData).GetFields().Length];
List<RenderPipelineMaterial> materialList = Utilities.GetRenderPipelineMaterialList();
var num = typeof(Builtin.BuiltinData).GetFields().Length * 2 // BuildtinData are duplicated for each material
+ typeof(Lit.SurfaceData).GetFields().Length
+ typeof(Unlit.SurfaceData).GetFields().Length
+ 1; // None
// TODO: Share this code to retrieve deferred material with HDRenderPipeline
// Find first material that have non 0 Gbuffer count and assign it as deferredMaterial
Type bsdfDataDeferredType = null;
foreach (RenderPipelineMaterial material in materialList)
{
if (material.GetMaterialGBufferCount() > 0)
{
bsdfDataDeferredType = material.GetType().GetNestedType("BSDFData");
}
}
debugViewMaterialStrings = new GUIContent[num];
debugViewMaterialValues = new int[num];
// TODO: Handle the case of no Gbuffer material
Debug.Assert(bsdfDataDeferredType != null);
num = typeof(Lit.BSDFData).GetFields().Length
+ typeof(Unlit.BSDFData).GetFields().Length
+ 1; // None
List<MaterialItem> materialItems = new List<MaterialItem>();
debugViewEngineStrings = new GUIContent[num];
debugViewEngineValues = new int[num];
int numSurfaceDataFields = 0;
int numBSDFDataFields = 0;
foreach (RenderPipelineMaterial material in materialList)
{
MaterialItem item = new MaterialItem();
item.className = material.GetType().Name + "/";
// Special case for None since it cannot be inferred from SurfaceDAta/BuiltinData
item.surfaceDataType = material.GetType().GetNestedType("SurfaceData");
numSurfaceDataFields += item.surfaceDataType.GetFields().Length;
item.bsdfDataType = material.GetType().GetNestedType("BSDFData");
numBSDFDataFields += item.bsdfDataType.GetFields().Length;
materialItems.Add(item);
}
// Material properties debug
var num = typeof(Builtin.BuiltinData).GetFields().Length * materialList.Count // BuildtinData are duplicated for each material
+ numSurfaceDataFields + 1; // +1 for None case
debugViewMaterialStrings = new GUIContent[num];
debugViewMaterialValues = new int[num];
// Special case for None since it cannot be inferred from SurfaceData/BuiltinData
FillWithProperties(typeof(Builtin.BuiltinData), debugViewMaterialStrings, debugViewMaterialValues, GetSubNameSpaceName(typeof(Lit.SurfaceData)), ref index);
FillWithProperties(typeof(Lit.SurfaceData), debugViewMaterialStrings, debugViewMaterialValues, GetSubNameSpaceName(typeof(Lit.SurfaceData)), ref index);
FillWithProperties(typeof(Builtin.BuiltinData), debugViewMaterialStrings, debugViewMaterialValues, GetSubNameSpaceName(typeof(Unlit.SurfaceData)), ref index);
FillWithProperties(typeof(Unlit.SurfaceData), debugViewMaterialStrings, debugViewMaterialValues, GetSubNameSpaceName(typeof(Unlit.SurfaceData)), ref index);
foreach (MaterialItem item in materialItems)
{
// BuiltinData are duplicated for each material
FillWithProperties(typeof(Builtin.BuiltinData), debugViewMaterialStrings, debugViewMaterialValues, item.className, ref index);
FillWithProperties(item.surfaceDataType, debugViewMaterialStrings, debugViewMaterialValues, item.className, ref index);
}
// Engine
// Engine properties debug
num = numBSDFDataFields + 1; // +1 for None case
debugViewEngineStrings = new GUIContent[num];
debugViewEngineValues = new int[num];
// 0 is a reserved number and should not be used (allow to track error)
FillWithProperties(typeof(Lit.BSDFData), debugViewEngineStrings, debugViewEngineValues, GetSubNameSpaceName(typeof(Lit.BSDFData)), ref index);
FillWithProperties(typeof(Unlit.BSDFData), debugViewEngineStrings, debugViewEngineValues, GetSubNameSpaceName(typeof(Unlit.BSDFData)), ref index);
foreach (MaterialItem item in materialItems)
{
FillWithProperties(item.bsdfDataType, debugViewEngineStrings, debugViewEngineValues, item.className, ref index);
}
// Attributes debug
var varyingNames = Enum.GetNames(typeof(Attributes.DebugViewVarying));
debugViewMaterialVaryingStrings = new GUIContent[varyingNames.Length];
debugViewMaterialVaryingValues = new int[varyingNames.Length];
// Gbuffer debug
var gbufferNames = Enum.GetNames(typeof(Attributes.DebugViewGbuffer));
debugViewMaterialGBufferStrings = new GUIContent[gbufferNames.Length + bsdfDataDeferredType.GetFields().Length];
debugViewMaterialGBufferValues = new int[gbufferNames.Length + bsdfDataDeferredType.GetFields().Length];
index = 0;
FillWithPropertiesEnum(typeof(Attributes.DebugViewGbuffer), debugViewMaterialGBufferStrings, debugViewMaterialGBufferValues, "", ref index);
FillWithProperties(typeof(Lit.BSDFData), debugViewMaterialGBufferStrings, debugViewMaterialGBufferValues, "", ref index);

public bool displayOpaqueObjects = true;
public bool displayTransparentObjects = true;
public bool enableDistortion = true;
public bool enableSSS = true;
public bool enableSSSAndTransmission = true;
}
public enum ShadowMapDebugMode

41
Assets/ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs


}
}
// TEMP: will be remove after data upgrade
[MenuItem("HDRenderPipeline/Swap standard and SSS material IDs")]
static void SwapStandardAndSssMaterialIds()
{
try
{
Object[] materials = Resources.FindObjectsOfTypeAll<Material>();
for (int i = 0, length = materials.Length; i < length; i++)
{
Material mat = materials[i] as Material;
EditorUtility.DisplayProgressBar(
"Updating materials...",
string.Format("{0} / {1}", i, length),
i / (float)(length - 1));
if (mat.shader.name == "HDRenderPipeline/Lit" || mat.shader.name == "HDRenderPipeline/LitTessellation")
{
int matID = (int)mat.GetFloat("_MaterialID");
if (matID == 0)
{
matID = 1;
mat.SetInt("_MaterialID", matID);
EditorUtility.SetDirty(mat);
}
else if (matID == 1)
{
matID = 0;
mat.SetInt("_MaterialID", matID);
EditorUtility.SetDirty(mat);
}
}
}
}
finally
{
EditorUtility.ClearProgressBar();
}
}
// Funtion used only to check performance of data with and without tessellation
[MenuItem("HDRenderPipeline/Debug/Remove tessellation materials (not reversible)")]
static void RemoveTessellationMaterials()

94
Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs


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

public bool useForwardRenderingOnly = false; // TODO: Currently there is no way to strip the extra forward shaders generated by the shaders compiler, so we can switch dynamically.
public bool useDepthPrepass = false;
// we have to fallback to forward-only rendering when scene view is using wireframe rendering mode --
// We have to fall back to forward-only rendering when scene view is using wireframe rendering mode --
// as rendering everything in wireframe + deferred do not play well together
public bool ShouldUseForwardRenderingOnly()
{

{
for (int index = 0; index < gbufferCount; index++)
{
/* RTs[index] = */
cmd.GetTemporaryRT(IDs[index], width, height, 0, FilterMode.Point, formats[index], sRGBWrites[index]);
}
}

return colorMRTs;
}
/*
public void BindBuffers(Material mat)
{
for (int index = 0; index < gbufferCount; index++)
{
mat.SetTexture(IDs[index], RTs[index]);
}
}
*/
public int gbufferCount { get; set; }
int[] IDs = new int[MaxGbuffer];
RenderTargetIdentifier[] RTIDs = new RenderTargetIdentifier[MaxGbuffer];

public class HDRenderPipeline : RenderPipeline
{
private readonly HDRenderPipelineAsset m_Asset;
readonly HDRenderPipelineAsset m_Asset;
// TODO: Find a way to automatically create/iterate through deferred material
// TODO TO CHECK: SebL I move allocation from Build() to here, but there was a comment "// Our object can be garbage collected, so need to be allocate here", it is still true ?
private readonly Lit.RenderLoop m_LitRenderLoop = new Lit.RenderLoop();
readonly RenderPipelineMaterial m_DeferredMaterial;
readonly List<RenderPipelineMaterial> m_MaterialList = new List<RenderPipelineMaterial>();
readonly GBufferManager m_gbufferManager = new GBufferManager();

private Material m_DebugViewMaterialGBuffer;
private Material m_DebugDisplayLatlong;
private Material m_DebugFullScreen;
Material m_DebugViewMaterialGBuffer;
Material m_DebugDisplayLatlong;
Material m_DebugFullScreen;
// Various buffer
readonly int m_CameraColorBuffer;

// Post-processing context and screen-space effects (recycled on every frame to avoid GC alloc)
readonly PostProcessRenderContext m_PostProcessContext;
readonly ScreenSpaceAmbientOcclusionEffect m_SsaoEffect;
// Stencil usage in HDRenderPipeline.
// Currently we use only 2 bits to identify the kind of lighting that is expected from the render pipeline
// Usage is define in LightDefinitions.cs
[Flags]
public enum StencilBits
{
Lighting = 3, // 0
All = 255 // 0xFF
}
// Detect when windows size is changing
int m_CurrentWidth;

{
m_Asset = asset;
// Scan material list and assign it
m_MaterialList = Utilities.GetRenderPipelineMaterialList();
// Find first material that have non 0 Gbuffer count and assign it as deferredMaterial
m_DeferredMaterial = null;
foreach (RenderPipelineMaterial material in m_MaterialList)
{
if (material.GetMaterialGBufferCount() > 0)
{
m_DeferredMaterial = material;
}
}
// TODO: Handle the case of no Gbuffer material
// TODO: I comment the assert here because m_DeferredMaterial for whatever reasons contain the correct class but with a "null" in the name instead of the real name and then trigger the assert
// whereas it work. Don't know what is hapening, DebugDisplay use the same code and name is correct there.
// Debug.Assert(m_DeferredMaterial != null);
m_CameraColorBuffer = Shader.PropertyToID("_CameraColorTexture");
m_CameraSubsurfaceBuffer = Shader.PropertyToID("_CameraSubsurfaceTexture");
m_CameraFilteringBuffer = Shader.PropertyToID("_CameraFilteringBuffer");

InitializeDebugMaterials();
// Init Gbuffer description
m_gbufferManager.gbufferCount = m_LitRenderLoop.GetMaterialGBufferCount();
m_gbufferManager.gbufferCount = m_DeferredMaterial.GetMaterialGBufferCount();
m_LitRenderLoop.GetMaterialGBufferDescription(out RTFormat, out RTReadWrite);
m_DeferredMaterial.GetMaterialGBufferDescription(out RTFormat, out RTReadWrite);
for (int gbufferIndex = 0; gbufferIndex < m_gbufferManager.gbufferCount; ++gbufferIndex)
{

if (ShaderConfig.s_VelocityInGbuffer == 1)
{
// If velocity is in GBuffer then it is in the last RT. Assign a different name to it.
m_gbufferManager.SetBufferDescription(m_gbufferManager.gbufferCount, "_VelocityTexture", Builtin.RenderLoop.GetVelocityBufferFormat(), Builtin.RenderLoop.GetVelocityBufferReadWrite());
m_gbufferManager.SetBufferDescription(m_gbufferManager.gbufferCount, "_VelocityTexture", Builtin.GetVelocityBufferFormat(), Builtin.GetVelocityBufferReadWrite());
m_gbufferManager.gbufferCount++;
}
m_VelocityBufferRT = new RenderTargetIdentifier(m_VelocityBuffer);

m_LitRenderLoop.Build(asset.renderPipelineResources);
m_MaterialList.ForEach(material => material.Build(asset.renderPipelineResources));
m_LightLoop.Build(asset.renderPipelineResources, asset.tileSettings, asset.textureSettings, asset.shadowInitParams, m_ShadowSettings);

public void OnSceneLoad()
{
// Recreate the textures which went NULL, and set 'isInit' to 'false'.
m_LitRenderLoop.Build(m_Asset.renderPipelineResources);
// Recreate the textures which went NULL
m_MaterialList.ForEach(material => material.Build(m_Asset.renderPipelineResources));
}
public override void Dispose()

m_LightLoop.Cleanup();
m_LitRenderLoop.Cleanup();
m_MaterialList.ForEach(material => material.Cleanup());
Utilities.Destroy(m_DebugViewMaterialGBuffer);
Utilities.Destroy(m_DebugDisplayLatlong);

}
// Broadcast SSS parameters to all shaders.
Shader.SetGlobalInt( "_EnableSSS", m_DebugDisplaySettings.renderingDebugSettings.enableSSS ? 1 : 0);
Shader.SetGlobalInt( "_EnableSSSAndTransmission", m_DebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission ? 1 : 0);
cmd.SetGlobalVectorArray("_ShapeParameters", sssParameters.shapeParameters);
cmd.SetGlobalVectorArray("_VolumeShapeParams", sssParameters.volumeShapeParams);
cmd.SetGlobalVectorArray("_VolumeAlbedos", sssParameters.volumeAlbedos);
renderContext.ExecuteCommandBuffer(cmd);

GraphicsSettings.lightsUseLinearIntensity = true;
GraphicsSettings.lightsUseColorTemperature = true;
if (!m_LitRenderLoop.isInit)
m_LitRenderLoop.RenderInit(renderContext);
m_MaterialList.ForEach(material => material.RenderInit(renderContext));
// Do anything we need to do upon a new frame.
m_LightLoop.NewFrame();

// TODO: Find a correct place to bind these material textures
// We have to bind the material specific global parameters in this mode
m_LitRenderLoop.Bind();
m_MaterialList.ForEach(material => material.Bind());
InitAndClearBuffer(camera, renderContext);

{
Utilities.SetupMaterialHDCamera(hdCamera, m_DebugViewMaterialGBuffer);
// m_gbufferManager.BindBuffers(m_DebugViewMaterialGBuffer);
// TODO: Bind depth textures
var cmd = new CommandBuffer { name = "DebugViewMaterialGBuffer" };
cmd.Blit(null, m_CameraColorBufferRT, m_DebugViewMaterialGBuffer, 0);

RenderTargetIdentifier[] colorRTs = { m_CameraColorBufferRT, m_CameraSubsurfaceBufferRT };
if (m_DebugDisplaySettings.renderingDebugSettings.enableSSS)
if (m_DebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission)
// Output split lighting for materials tagged with the SSS stencil bit.
// Output split lighting for materials asking for it (via stencil buffer)
m_LightLoop.RenderDeferredLighting(hdCamera, renderContext, m_DebugDisplaySettings, colorRTs, m_CameraDepthStencilBufferRT, new RenderTargetIdentifier(GetDepthTexture()), true);
}

void CombineSubsurfaceScattering(HDCamera hdCamera, ScriptableRenderContext context, SubsurfaceScatteringSettings sssParameters)
{
// Currently, forward-rendered objects do not output split lighting required for the SSS pass.
if (m_Asset.renderingSettings.ShouldUseForwardRenderingOnly()) return;
if (!m_DebugDisplaySettings.renderingDebugSettings.enableSSS) return;
if (!m_DebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission || m_Asset.renderingSettings.ShouldUseForwardRenderingOnly())
return;
m_FilterAndCombineSubsurfaceScattering.SetVectorArray("_SurfaceShapeParams", sssParameters.surfaceShapeParams);
m_FilterAndCombineSubsurfaceScattering.SetFloatArray("_WorldScales", sssParameters.worldScales);
m_FilterAndCombineSubsurfaceScattering.SetFloatArray("_FilterKernelsNearField", sssParameters.filterKernelsNearField);
m_FilterAndCombineSubsurfaceScattering.SetFloatArray("_FilterKernelsFarField", sssParameters.filterKernelsFarField);

int h = camera.pixelHeight;
var cmd = new CommandBuffer { name = "" };
cmd.GetTemporaryRT(m_VelocityBuffer, w, h, 0, FilterMode.Point, Builtin.RenderLoop.GetVelocityBufferFormat(), Builtin.RenderLoop.GetVelocityBufferReadWrite());
cmd.GetTemporaryRT(m_VelocityBuffer, w, h, 0, FilterMode.Point, Builtin.GetVelocityBufferFormat(), Builtin.GetVelocityBufferReadWrite());
cmd.SetRenderTarget(m_VelocityBufferRT, m_CameraDepthStencilBufferRT);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();

int h = camera.pixelHeight;
var cmd = new CommandBuffer { name = "" };
cmd.GetTemporaryRT(m_DistortionBuffer, w, h, 0, FilterMode.Point, Builtin.RenderLoop.GetDistortionBufferFormat(), Builtin.RenderLoop.GetDistortionBufferReadWrite());
cmd.GetTemporaryRT(m_DistortionBuffer, w, h, 0, FilterMode.Point, Builtin.GetDistortionBufferFormat(), Builtin.GetDistortionBufferReadWrite());
cmd.SetRenderTarget(m_DistortionBufferRT, m_CameraDepthStencilBufferRT);
cmd.ClearRenderTarget(false, true, Color.black); // TODO: can we avoid this clear for performance ?
renderContext.ExecuteCommandBuffer(cmd);

Texture skyReflection = m_SkyManager.skyReflection;
propertyBlock.SetTexture("_InputCubemap", skyReflection);
propertyBlock.SetFloat("_Mipmap", lightingDebug.skyReflectionMipmap);
debugCB.SetViewport(new Rect(x, y, overlaySize, overlaySize));
debugCB.SetViewport(new Rect(x, y, overlaySize, overlaySize));
debugCB.DrawProcedural(Matrix4x4.identity, m_DebugDisplayLatlong, 0, MeshTopology.Triangles, 3, 1, propertyBlock);
Utilities.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, camera.camera.pixelWidth);
}

2
Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.asset


specularGlobalDimmer: 1
tileDebugByCategory: 0
shadowInitParams:
shadowAtlasWidth: 2048
shadowAtlasWidth: 4096
shadowAtlasHeight: 4096
textureSettings:
spotCookieSize: 128

15
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs


public Vector3 offsetLS;
public float unused2;
};
// Usage of StencilBits.Lighting on 2 bits.
// We support both deferred and forward renderer. Here is the current usage of this 2 bits:
// 0. Everything except case below. This include any forward opaque object. No lighting in deferred lighting path.
// 1. All deferred opaque object that require split lighting (i.e output both specular and diffuse in two different render target). Typically Subsurface scattering material.
// 2. All deferred opaque object.
// 3. unused
[GenerateHLSL]
// Caution: Value below are hardcoded in some shader (because properties doesn't support include). If order or value is change, please update corresponding ".shader"
public enum StencilLightingUsage
{
NoLighting,
SplitLighting,
RegularLighting
}
}

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


Utilities.SelectKeyword(m_DeferredDirectMaterialSRT, tileKeywords, 0);
m_DeferredDirectMaterialSRT.EnableKeyword("LIGHTLOOP_TILE_PASS");
m_DeferredDirectMaterialSRT.DisableKeyword("OUTPUT_SPLIT_LIGHTING");
m_DeferredDirectMaterialSRT.SetInt("_StencilRef", (int)StencilBits.SSS);
m_DeferredDirectMaterialSRT.SetInt("_StencilCmp", 2 /* Less */); // Shade if stencil is not 0 and not SSS
m_DeferredDirectMaterialSRT.SetInt("_StencilRef", (int)StencilLightingUsage.RegularLighting);
m_DeferredDirectMaterialSRT.SetInt("_StencilCmp", (int)CompareFunction.Equal);
m_DeferredDirectMaterialSRT.SetInt("_SrcBlend", (int)BlendMode.One);
m_DeferredDirectMaterialSRT.SetInt("_DstBlend", (int)BlendMode.Zero);

m_DeferredDirectMaterialMRT.EnableKeyword("OUTPUT_SPLIT_LIGHTING");
m_DeferredDirectMaterialMRT.SetInt("_StencilRef", (int)StencilBits.SSS);
m_DeferredDirectMaterialMRT.SetInt("_StencilCmp", 3 /* Equal */);
m_DeferredDirectMaterialMRT.SetInt("_StencilRef", (int)StencilLightingUsage.SplitLighting);
m_DeferredDirectMaterialMRT.SetInt("_StencilCmp", (int)CompareFunction.Equal);
m_DeferredDirectMaterialMRT.SetInt("_SrcBlend", (int)BlendMode.One);
m_DeferredDirectMaterialMRT.SetInt("_DstBlend", (int)BlendMode.Zero);

m_DeferredIndirectMaterialSRT.DisableKeyword("OUTPUT_SPLIT_LIGHTING");
m_DeferredIndirectMaterialSRT.SetInt("_StencilRef", (int)StencilBits.SSS);
m_DeferredIndirectMaterialSRT.SetInt("_StencilCmp", 2 /* Less */); // Shade if stencil is not 0 and not SSS
m_DeferredIndirectMaterialSRT.SetInt("_StencilRef", (int)StencilLightingUsage.RegularLighting);
m_DeferredIndirectMaterialSRT.SetInt("_StencilCmp", (int)CompareFunction.Equal);
m_DeferredIndirectMaterialSRT.SetInt("_SrcBlend", (int)BlendMode.One);
m_DeferredIndirectMaterialSRT.SetInt("_DstBlend", (int)BlendMode.One); // Additive color & alpha source

m_DeferredIndirectMaterialMRT.EnableKeyword("OUTPUT_SPLIT_LIGHTING");
m_DeferredIndirectMaterialMRT.SetInt("_StencilRef", (int)StencilBits.SSS);
m_DeferredIndirectMaterialMRT.SetInt("_StencilCmp", 3 /* Equal */);
m_DeferredIndirectMaterialMRT.SetInt("_StencilRef", (int)StencilLightingUsage.SplitLighting);
m_DeferredIndirectMaterialMRT.SetInt("_StencilCmp", (int)CompareFunction.Equal);
m_DeferredIndirectMaterialMRT.SetInt("_SrcBlend", (int)BlendMode.One);
m_DeferredIndirectMaterialMRT.SetInt("_DstBlend", (int)BlendMode.One); // Additive color & alpha source

m_DeferredAllMaterialSRT.DisableKeyword("OUTPUT_SPLIT_LIGHTING");
m_DeferredAllMaterialSRT.SetInt("_StencilRef", (int)StencilBits.SSS);
m_DeferredAllMaterialSRT.SetInt("_StencilCmp", 2 /* Less */); // Shade if stencil is not 0 and not SSS
m_DeferredAllMaterialSRT.SetInt("_StencilRef", (int)StencilLightingUsage.RegularLighting);
m_DeferredAllMaterialSRT.SetInt("_StencilCmp", (int)CompareFunction.Equal);
m_DeferredAllMaterialSRT.SetInt("_SrcBlend", (int)BlendMode.One);
m_DeferredAllMaterialSRT.SetInt("_DstBlend", (int)BlendMode.Zero);

m_DeferredAllMaterialMRT.EnableKeyword("OUTPUT_SPLIT_LIGHTING");
m_DeferredAllMaterialMRT.SetInt("_StencilRef", (int)StencilBits.SSS);
m_DeferredAllMaterialMRT.SetInt("_StencilCmp", 3 /* Equal */);
m_DeferredAllMaterialMRT.SetInt("_StencilRef", (int)StencilLightingUsage.SplitLighting);
m_DeferredAllMaterialMRT.SetInt("_StencilCmp", (int)CompareFunction.Equal);
m_DeferredAllMaterialMRT.SetInt("_SrcBlend", (int)BlendMode.One);
m_DeferredAllMaterialMRT.SetInt("_DstBlend", (int)BlendMode.Zero);

m_SingleDeferredMaterialSRT.SetInt("_StencilRef", (int)StencilBits.SSS);
m_SingleDeferredMaterialSRT.SetInt("_StencilCmp", 2 /* Less */); // Shade if stencil is not 0 and not SSS
m_SingleDeferredMaterialSRT.SetInt("_StencilRef", (int)StencilLightingUsage.RegularLighting);
m_SingleDeferredMaterialSRT.SetInt("_StencilCmp", (int)CompareFunction.Equal);
m_SingleDeferredMaterialSRT.SetInt("_SrcBlend", (int)BlendMode.One);
m_SingleDeferredMaterialSRT.SetInt("_DstBlend", (int)BlendMode.Zero);

m_SingleDeferredMaterialMRT.SetInt("_StencilRef", (int)StencilBits.SSS);
m_SingleDeferredMaterialMRT.SetInt("_StencilCmp", 3 /* Equal */);
m_SingleDeferredMaterialMRT.SetInt("_StencilRef", (int)StencilLightingUsage.SplitLighting);
m_SingleDeferredMaterialMRT.SetInt("_StencilCmp", (int)CompareFunction.Equal);
m_SingleDeferredMaterialMRT.SetInt("_SrcBlend", (int)BlendMode.One);
m_SingleDeferredMaterialMRT.SetInt("_DstBlend", (int)BlendMode.Zero);

public void RenderDeferredLighting( HDCamera hdCamera, ScriptableRenderContext renderContext,
DebugDisplaySettings debugDisplaySettings,
RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthStencilBuffer, RenderTargetIdentifier depthStencilTexture,
bool outputSplitLightingForSSS)
bool outputSplitLighting)
using (new Utilities.ProfilingSample((m_TileSettings.enableTileAndCluster ? "TilePass - Deferred Lighting Pass" : "SinglePass - Deferred Lighting Pass") + (outputSplitLightingForSSS ? " MRT" : ""), renderContext))
using (new Utilities.ProfilingSample((m_TileSettings.enableTileAndCluster ? "TilePass - Deferred Lighting Pass" : "SinglePass - Deferred Lighting Pass") + (outputSplitLighting ? " MRT" : ""), renderContext))
{
var cmd = new CommandBuffer();
cmd.name = bUseClusteredForDeferred ? "Clustered pass" : "Tiled pass";

PushGlobalParams(camera, renderContext, null, 0);
// This is a debug brute force renderer to debug tile/cluster which render all the lights
if (outputSplitLightingForSSS)
if (outputSplitLighting)
// The stencil test uses a LESS comparison mode.
// If asked to disable SSS, we set the material ID of SSS materials to Standard, and shade all pixels with non-zero stencil values.
m_SingleDeferredMaterialSRT.SetInt("_StencilRef", (int)(debugDisplaySettings.renderingDebugSettings.enableSSS ? StencilBits.SSS : 0));
// If SSS is disable, do lighting for both split lighting and no split lighting
if (!debugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission)
{
m_SingleDeferredMaterialSRT.SetInt("_StencilRef", (int)StencilLightingUsage.NoLighting);
m_SingleDeferredMaterialSRT.SetInt("_StencilCmp", (int)CompareFunction.NotEqual);
}
else
{
m_SingleDeferredMaterialSRT.SetInt("_StencilRef", (int)StencilLightingUsage.RegularLighting);
m_SingleDeferredMaterialSRT.SetInt("_StencilCmp", (int)CompareFunction.Equal);
}
Utilities.DrawFullScreen(cmd, m_SingleDeferredMaterialSRT, hdCamera, colorBuffers[0], depthStencilBuffer);
}

if (m_TileSettings.enableSplitLightEvaluation)
{
if (outputSplitLightingForSSS)
if (outputSplitLighting)
{
Utilities.SelectKeyword(m_DeferredDirectMaterialMRT, "USE_CLUSTERED_LIGHTLIST", "USE_FPTL_LIGHTLIST", bUseClusteredForDeferred);
Utilities.DrawFullScreen(cmd, m_DeferredDirectMaterialMRT, hdCamera, colorBuffers, depthStencilBuffer);

}
else
{
// The stencil test uses a LESS comparison mode.
// If asked to disable SSS, we set the material ID of SSS materials to Standard, and shade all pixels with non-zero stencil values.
m_DeferredDirectMaterialSRT.SetInt("_StencilRef", (int)(debugDisplaySettings.renderingDebugSettings.enableSSS ? StencilBits.SSS : 0));
m_DeferredIndirectMaterialSRT.SetInt("_StencilRef", (int)(debugDisplaySettings.renderingDebugSettings.enableSSS ? StencilBits.SSS : 0));
// If SSS is disable, do lighting for both split lighting and no split lighting
if (!debugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission)
{
m_DeferredDirectMaterialSRT.SetInt("_StencilRef", (int)StencilLightingUsage.NoLighting);
m_DeferredDirectMaterialSRT.SetInt("_StencilCmp", (int)CompareFunction.NotEqual);
m_DeferredIndirectMaterialSRT.SetInt("_StencilRef", (int)StencilLightingUsage.NoLighting);
m_DeferredIndirectMaterialSRT.SetInt("_StencilCmp", (int)CompareFunction.NotEqual);
}
else
{
m_DeferredDirectMaterialSRT.SetInt("_StencilRef", (int)StencilLightingUsage.RegularLighting);
m_DeferredDirectMaterialSRT.SetInt("_StencilCmp", (int)CompareFunction.Equal);
m_DeferredIndirectMaterialSRT.SetInt("_StencilRef", (int)StencilLightingUsage.RegularLighting);
m_DeferredIndirectMaterialSRT.SetInt("_StencilCmp", (int)CompareFunction.Equal);
}
Utilities.SelectKeyword(m_DeferredDirectMaterialSRT, "USE_CLUSTERED_LIGHTLIST", "USE_FPTL_LIGHTLIST", bUseClusteredForDeferred);
Utilities.DrawFullScreen(cmd, m_DeferredDirectMaterialSRT, hdCamera, colorBuffers[0], depthStencilBuffer);

}
else
{
if (outputSplitLightingForSSS)
if (outputSplitLighting)
{
Utilities.SelectKeyword(m_DeferredAllMaterialMRT, "USE_CLUSTERED_LIGHTLIST", "USE_FPTL_LIGHTLIST", bUseClusteredForDeferred);
Utilities.DrawFullScreen(cmd, m_DeferredAllMaterialMRT, hdCamera, colorBuffers, depthStencilBuffer);

// The stencil test uses a LESS comparison mode.
// If asked to disable SSS, we set the material ID of SSS materials to Standard, and shade all pixels with non-zero stencil values.
m_DeferredAllMaterialSRT.SetInt("_StencilRef", (int)(debugDisplaySettings.renderingDebugSettings.enableSSS ? StencilBits.NonSSS : StencilBits.SSS));
// If SSS is disable, do lighting for both split lighting and no split lighting
if (!debugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission)
{
m_DeferredAllMaterialSRT.SetInt("_StencilRef", (int)StencilLightingUsage.NoLighting);
m_DeferredAllMaterialSRT.SetInt("_StencilCmp", (int)CompareFunction.NotEqual);
}
else
{
m_DeferredAllMaterialSRT.SetInt("_StencilRef", (int)StencilLightingUsage.RegularLighting);
m_DeferredAllMaterialSRT.SetInt("_StencilCmp", (int)CompareFunction.Equal);
}
Utilities.SelectKeyword(m_DeferredAllMaterialSRT, "USE_CLUSTERED_LIGHTLIST", "USE_FPTL_LIGHTLIST", bUseClusteredForDeferred);
Utilities.DrawFullScreen(cmd, m_DeferredAllMaterialSRT, hdCamera, colorBuffers[0], depthStencilBuffer);

35
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs


//-----------------------------------------------------------------------------
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
namespace Builtin
public class Builtin // Note: This particular class doesn't derive from RenderPipelineMaterial
{
//-----------------------------------------------------------------------------
// BuiltinData

public Vector3 emissiveColor; // HDR value
};
public class RenderLoop : Object
public static RenderTextureFormat GetVelocityBufferFormat()
public static RenderTextureFormat GetVelocityBufferFormat()
{
return RenderTextureFormat.RGHalf; // TODO: We should use 16bit normalized instead, better precision // RGInt
}
return RenderTextureFormat.RGHalf; // TODO: We should use 16bit normalized instead, better precision // RGInt
}
public static RenderTextureReadWrite GetVelocityBufferReadWrite()
{
return RenderTextureReadWrite.Linear;
}
public static RenderTextureReadWrite GetVelocityBufferReadWrite()
{
return RenderTextureReadWrite.Linear;
}
public static RenderTextureFormat GetDistortionBufferFormat()
{
// TODO: // This format need to be additive blendable and include distortionBlur, blend mode different for alpha value
return RenderTextureFormat.ARGBHalf;
}
public static RenderTextureFormat GetDistortionBufferFormat()
{
// TODO: // This format need to be additive blendable and include distortionBlur, blend mode different for alpha value
return RenderTextureFormat.ARGBHalf;
}
public static RenderTextureReadWrite GetDistortionBufferReadWrite()
{
return RenderTextureReadWrite.Linear;
}
public static RenderTextureReadWrite GetDistortionBufferReadWrite()
{
return RenderTextureReadWrite.Linear;
}
}
}

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


_HorizonFade("Horizon fade", Range(0.0, 5.0)) = 1.0
// Stencil state
[HideInInspector] _StencilRef("_StencilRef", Int) = 2 // StencilBits.NonSSS (fixed at compile time)
[HideInInspector] _StencilRef("_StencilRef", Int) = 2 // StencilLightingUsage.RegularLighting
// Blending state
[HideInInspector] _SurfaceType("__surfacetype", Float) = 0.0

2
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader


_HorizonFade("Horizon fade", Range(0.0, 5.0)) = 1.0
// Stencil state
[HideInInspector] _StencilRef("_StencilRef", Int) = 2 // StencilBits.NonSSS (fixed at compile time)
[HideInInspector] _StencilRef("_StencilRef", Int) = 2 // StencilLightingUsage.RegularLighting (fixed at compile time)
// Blending state
[HideInInspector] _SurfaceType("__surfacetype", Float) = 0.0

8
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs


depthOffsetEnable = FindProperty(kDepthOffsetEnable, props);
// MaterialID
materialID = FindProperty(kMaterialID, props, false);
materialID = FindProperty(kMaterialID, props, false); // LayeredLit is force to be standard for now, so materialID could not exist
// Per pixel displacement
enablePerPixelDisplacement = FindProperty(kEnablePerPixelDisplacement, props);

EditorGUI.indentLevel--;
}
// All Setup Keyword functions must be static. It allow to create script to automatically update the shaders with a script if ocde change
// 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 SetupBaseLitKeywords(Material material)
{
SetupBaseUnlitKeywords(material);

SetKeyword(material, "_DEPTHOFFSET_ON", depthOffsetEnable);
// Set the reference value for the stencil test.
int stencilRef = (int)StencilBits.NonSSS;
int stencilRef = (int)StencilLightingUsage.RegularLighting;
stencilRef = (int)StencilBits.SSS;
stencilRef = (int)StencilLightingUsage.SplitLighting;
}
}
material.SetInt(kStencilRef, stencilRef);

9
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/LitUI.cs


using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine.Experimental.Rendering.HDPipeline.Lit;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{

EditorGUI.indentLevel--;
}
switch ((MaterialId)materialID.floatValue)
switch ((Lit.MaterialId)materialID.floatValue)
case MaterialId.LitSSS:
case Lit.MaterialId.LitSSS:
case MaterialId.LitStandard:
case Lit.MaterialId.LitStandard:
case MaterialId.LitSpecular:
case Lit.MaterialId.LitSpecular:
m_MaterialEditor.TexturePropertySingleLine(Styles.specularColorText, specularColorMap, specularColor);
break;
default:

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


namespace UnityEngine.Experimental.Rendering.HDPipeline
{
namespace Lit
public partial class Lit : RenderPipelineMaterial
{
[GenerateHLSL(PackingRules.Exact)]
public enum MaterialId

Count = (ShaderConfig.k_PackgbufferInU16 == 1) ? 2 : 4
};
public partial class RenderLoop : Object
{
//-----------------------------------------------------------------------------
// GBuffer management
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// GBuffer management
//-----------------------------------------------------------------------------
public int GetMaterialGBufferCount() { return (int)GBufferMaterial.Count; }
public override int GetMaterialGBufferCount() { return (int)GBufferMaterial.Count; }
public void GetMaterialGBufferDescription(out RenderTextureFormat[] RTFormat, out RenderTextureReadWrite[] RTReadWrite)
{
RTFormat = new RenderTextureFormat[(int)GBufferMaterial.Count];
RTReadWrite = new RenderTextureReadWrite[(int)GBufferMaterial.Count];
public override void GetMaterialGBufferDescription(out RenderTextureFormat[] RTFormat, out RenderTextureReadWrite[] RTReadWrite)
{
RTFormat = new RenderTextureFormat[(int)GBufferMaterial.Count];
RTReadWrite = new RenderTextureReadWrite[(int)GBufferMaterial.Count];
if (ShaderConfig.s_PackgbufferInU16 == 1)
{
// TODO: Just discovered that Unity doesn't support unsigned 16 RT format.
RTFormat[0] = RenderTextureFormat.ARGBInt; RTReadWrite[0] = RenderTextureReadWrite.Linear;
RTFormat[1] = RenderTextureFormat.ARGBInt; RTReadWrite[1] = RenderTextureReadWrite.Linear;
}
else
{
RTFormat[0] = RenderTextureFormat.ARGB32; RTReadWrite[0] = RenderTextureReadWrite.sRGB;
RTFormat[1] = RenderTextureFormat.ARGB2101010; RTReadWrite[1] = RenderTextureReadWrite.Linear;
RTFormat[2] = RenderTextureFormat.ARGB32; RTReadWrite[2] = RenderTextureReadWrite.Linear;
RTFormat[3] = RenderTextureFormat.RGB111110Float; RTReadWrite[3] = RenderTextureReadWrite.Linear;
}
if (ShaderConfig.s_PackgbufferInU16 == 1)
{
// TODO: Just discovered that Unity doesn't support unsigned 16 RT format.
RTFormat[0] = RenderTextureFormat.ARGBInt; RTReadWrite[0] = RenderTextureReadWrite.Linear;
RTFormat[1] = RenderTextureFormat.ARGBInt; RTReadWrite[1] = RenderTextureReadWrite.Linear;
}
else
{
RTFormat[0] = RenderTextureFormat.ARGB32; RTReadWrite[0] = RenderTextureReadWrite.sRGB;
RTFormat[1] = RenderTextureFormat.ARGB2101010; RTReadWrite[1] = RenderTextureReadWrite.Linear;
RTFormat[2] = RenderTextureFormat.ARGB32; RTReadWrite[2] = RenderTextureReadWrite.Linear;
RTFormat[3] = RenderTextureFormat.RGB111110Float; RTReadWrite[3] = RenderTextureReadWrite.Linear;
}
//-----------------------------------------------------------------------------
// Init precomputed texture
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Init precomputed texture
//-----------------------------------------------------------------------------
public bool isInit;
bool m_isInit;
// For image based lighting
private Material m_InitPreFGD;
private RenderTexture m_PreIntegratedFGD;
// For image based lighting
Material m_InitPreFGD;
RenderTexture m_PreIntegratedFGD;
// For area lighting - We pack all texture inside a texture array to reduce the number of resource required
private Texture2DArray m_LtcData; // 0: m_LtcGGXMatrix - RGBA, 2: m_LtcDisneyDiffuseMatrix - RGBA, 3: m_LtcMultiGGXFresnelDisneyDiffuse - RGB, A unused
// For area lighting - We pack all texture inside a texture array to reduce the number of resource required
Texture2DArray m_LtcData; // 0: m_LtcGGXMatrix - RGBA, 2: m_LtcDisneyDiffuseMatrix - RGBA, 3: m_LtcMultiGGXFresnelDisneyDiffuse - RGB, A unused
const int k_LtcLUTMatrixDim = 3; // size of the matrix (3x3)
const int k_LtcLUTResolution = 64;
const int k_LtcLUTMatrixDim = 3; // size of the matrix (3x3)
const int k_LtcLUTResolution = 64;
// Load LUT with one scalar in alpha of a tex2D
void LoadLUT(Texture2DArray tex, int arrayElement, TextureFormat format, float[] LUTScalar)
{
const int count = k_LtcLUTResolution * k_LtcLUTResolution;
Color[] pixels = new Color[count];
// Load LUT with one scalar in alpha of a tex2D
void LoadLUT(Texture2DArray tex, int arrayElement, TextureFormat format, float[] LUTScalar)
for (int i = 0; i < count; i++)
const int count = k_LtcLUTResolution * k_LtcLUTResolution;
Color[] pixels = new Color[count];
pixels[i] = new Color(0, 0, 0, LUTScalar[i]);
}
for (int i = 0; i < count; i++)
{
pixels[i] = new Color(0, 0, 0, LUTScalar[i]);
}
tex.SetPixels(pixels, arrayElement);
}
tex.SetPixels(pixels, arrayElement);
}
// Load LUT with 3x3 matrix in RGBA of a tex2D (some part are zero)
void LoadLUT(Texture2DArray tex, int arrayElement, TextureFormat format, double[,] LUTTransformInv)
{
const int count = k_LtcLUTResolution * k_LtcLUTResolution;
Color[] pixels = new Color[count];
// Load LUT with 3x3 matrix in RGBA of a tex2D (some part are zero)
void LoadLUT(Texture2DArray tex, int arrayElement, TextureFormat format, double[,] LUTTransformInv)
for (int i = 0; i < count; i++)
const int count = k_LtcLUTResolution * k_LtcLUTResolution;
Color[] pixels = new Color[count];
// Both GGX and Disney Diffuse BRDFs have zero values in columns 1, 3, 5, 7.
// Column 8 contains only ones.
pixels[i] = new Color((float)LUTTransformInv[i, 0],
(float)LUTTransformInv[i, 2],
(float)LUTTransformInv[i, 4],
(float)LUTTransformInv[i, 6]);
}
for (int i = 0; i < count; i++)
{
// Both GGX and Disney Diffuse BRDFs have zero values in columns 1, 3, 5, 7.
// Column 8 contains only ones.
pixels[i] = new Color((float)LUTTransformInv[i, 0],
(float)LUTTransformInv[i, 2],
(float)LUTTransformInv[i, 4],
(float)LUTTransformInv[i, 6]);
}
tex.SetPixels(pixels, arrayElement);
}
tex.SetPixels(pixels, arrayElement);
}
// Special-case function for 'm_LtcMultiGGXFresnelDisneyDiffuse'.
void LoadLUT(Texture2DArray tex, int arrayElement, TextureFormat format, float[] LtcGGXMagnitudeData,
float[] LtcGGXFresnelData,
float[] LtcDisneyDiffuseMagnitudeData)
{
const int count = k_LtcLUTResolution * k_LtcLUTResolution;
Color[] pixels = new Color[count];
// Special-case function for 'm_LtcMultiGGXFresnelDisneyDiffuse'.
void LoadLUT(Texture2DArray tex, int arrayElement, TextureFormat format, float[] LtcGGXMagnitudeData,
float[] LtcGGXFresnelData,
float[] LtcDisneyDiffuseMagnitudeData)
for (int i = 0; i < count; i++)
const int count = k_LtcLUTResolution * k_LtcLUTResolution;
Color[] pixels = new Color[count];
// We store the result of the subtraction as a run-time optimization.
// See the footnote 2 of "LTC Fresnel Approximation" by Stephen Hill.
pixels[i] = new Color(LtcGGXMagnitudeData[i] - LtcGGXFresnelData[i],
LtcGGXFresnelData[i], LtcDisneyDiffuseMagnitudeData[i], 1);
}
for (int i = 0; i < count; i++)
{
// We store the result of the subtraction as a run-time optimization.
// See the footnote 2 of "LTC Fresnel Approximation" by Stephen Hill.
pixels[i] = new Color(LtcGGXMagnitudeData[i] - LtcGGXFresnelData[i],
LtcGGXFresnelData[i], LtcDisneyDiffuseMagnitudeData[i], 1);
}
tex.SetPixels(pixels, arrayElement);
}
tex.SetPixels(pixels, arrayElement);
}
public Lit() {}
public void Build(RenderPipelineResources renderPipelineResources)
{
m_InitPreFGD = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/PreIntegratedFGD");
public override void Build(RenderPipelineResources renderPipelineResources)
{
m_InitPreFGD = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/PreIntegratedFGD");
// For DisneyDiffuse integration values goes from (0.5 to 1.53125). GGX need 0 to 1. Use float format.
m_PreIntegratedFGD = new RenderTexture(128, 128, 0, RenderTextureFormat.RGB111110Float, RenderTextureReadWrite.Linear);
m_PreIntegratedFGD.filterMode = FilterMode.Bilinear;
m_PreIntegratedFGD.wrapMode = TextureWrapMode.Clamp;
m_PreIntegratedFGD.hideFlags = HideFlags.DontSave;
m_PreIntegratedFGD.Create();
// For DisneyDiffuse integration values goes from (0.5 to 1.53125). GGX need 0 to 1. Use float format.
m_PreIntegratedFGD = new RenderTexture(128, 128, 0, RenderTextureFormat.RGB111110Float, RenderTextureReadWrite.Linear);
m_PreIntegratedFGD.filterMode = FilterMode.Bilinear;
m_PreIntegratedFGD.wrapMode = TextureWrapMode.Clamp;
m_PreIntegratedFGD.hideFlags = HideFlags.DontSave;
m_PreIntegratedFGD.Create();
m_LtcData = new Texture2DArray(k_LtcLUTResolution, k_LtcLUTResolution, 3, TextureFormat.RGBAHalf, false /*mipmap*/, true /* linear */)
{
hideFlags = HideFlags.HideAndDontSave,
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Bilinear
};
m_LtcData = new Texture2DArray(k_LtcLUTResolution, k_LtcLUTResolution, 3, TextureFormat.RGBAHalf, false /*mipmap*/, true /* linear */)
{
hideFlags = HideFlags.HideAndDontSave,
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Bilinear
};
LoadLUT(m_LtcData, 0, TextureFormat.RGBAHalf, s_LtcGGXMatrixData);
LoadLUT(m_LtcData, 1, TextureFormat.RGBAHalf, s_LtcDisneyDiffuseMatrixData);
// TODO: switch to RGBA64 when it becomes available.
LoadLUT(m_LtcData, 2, TextureFormat.RGBAHalf, s_LtcGGXMagnitudeData, s_LtcGGXFresnelData, s_LtcDisneyDiffuseMagnitudeData);
LoadLUT(m_LtcData, 0, TextureFormat.RGBAHalf, s_LtcGGXMatrixData);
LoadLUT(m_LtcData, 1, TextureFormat.RGBAHalf, s_LtcDisneyDiffuseMatrixData);
// TODO: switch to RGBA64 when it becomes available.
LoadLUT(m_LtcData, 2, TextureFormat.RGBAHalf, s_LtcGGXMagnitudeData, s_LtcGGXFresnelData, s_LtcDisneyDiffuseMagnitudeData);
m_LtcData.Apply();
m_LtcData.Apply();
isInit = false;
}
m_isInit = false;
}
public void Cleanup()
{
Utilities.Destroy(m_InitPreFGD);
public override void Cleanup()
{
Utilities.Destroy(m_InitPreFGD);
// TODO: how to delete RenderTexture ? or do we need to do it ?
m_isInit = false;
}
// TODO: how to delete RenderTexture ? or do we need to do it ?
isInit = false;
}
public override void RenderInit(Rendering.ScriptableRenderContext renderContext)
{
if (m_isInit)
return;
public void RenderInit(Rendering.ScriptableRenderContext renderContext)
{
var cmd = new CommandBuffer();
cmd.name = "Init PreFGD";
cmd.Blit(null, new RenderTargetIdentifier(m_PreIntegratedFGD), m_InitPreFGD, 0);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
var cmd = new CommandBuffer();
cmd.name = "Init PreFGD";
cmd.Blit(null, new RenderTargetIdentifier(m_PreIntegratedFGD), m_InitPreFGD, 0);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
isInit = true;
}
m_isInit = true;
}
public void Bind()
{
Shader.SetGlobalTexture("_PreIntegratedFGD", m_PreIntegratedFGD);
Shader.SetGlobalTexture("_LtcData", m_LtcData);
}
public override void Bind()
{
Shader.SetGlobalTexture("_PreIntegratedFGD", m_PreIntegratedFGD);
Shader.SetGlobalTexture("_LtcData", m_LtcData);
}
}
}

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


#define SSS_WRAP_ANGLE (PI/12) // Used for wrap lighting
#define SSS_WRAP_LIGHT cos(PI/2 - SSS_WRAP_ANGLE)
uint _EnableSSS; // Globally toggles subsurface scattering on/off
uint _EnableSSSAndTransmission; // Globally toggles subsurface and transmission scattering on/off
float4 _ShapeParameters[SSS_N_PROFILES]; // RGB = S = 1 / D; A = filter radius
float4 _VolumeShapeParams[SSS_N_PROFILES]; // RGB = S = 1 / D; A = unused
float4 _VolumeAlbedos[SSS_N_PROFILES]; // RGB = color, A = unused
//-----------------------------------------------------------------------------

uint transmissionMode = BitFieldExtract(_TransmissionFlags, 2u, 2u * subsurfaceProfile);
bsdfData.enableTransmission = transmissionMode != SSS_TRSM_MODE_NONE;
bsdfData.enableTransmission = transmissionMode != SSS_TRSM_MODE_NONE && (_EnableSSSAndTransmission > 0);
bsdfData.transmittance = ComputeTransmittance(_ShapeParameters[subsurfaceProfile].rgb,
bsdfData.transmittance = ComputeTransmittance(_VolumeShapeParams[subsurfaceProfile].rgb,
_VolumeAlbedos[subsurfaceProfile].rgb,
bsdfData.thickness, bsdfData.subsurfaceRadius);
}

// We modify the albedo here as this code is used by all lighting (including light maps and GI).
if (performPostScatterTexturing)
{
#ifndef SSS_PASS
bsdfData.diffuseColor = float3(1.0, 1.0, 1.0);
#endif
}
else
#if defined(SHADERPASS) && (SHADERPASS == SHADERPASS_LIGHT_TRANSPORT) // In case of GI pass don't modify the diffuseColor
if (0)
#else
if (_EnableSSSAndTransmission > 0) // If we globally disable SSS effect, don't modify diffuseColor
#endif
bsdfData.diffuseColor = sqrt(bsdfData.diffuseColor);
// We modify the albedo here as this code is used by all lighting (including light maps and GI).
if (performPostScatterTexturing)
{
#ifndef SSS_PASS
bsdfData.diffuseColor = float3(1.0, 1.0, 1.0);
#endif
}
else
{
bsdfData.diffuseColor = sqrt(bsdfData.diffuseColor);
}
}
}

}
else if (surfaceData.materialId == MATERIALID_LIT_SSS)
{
// Use 16 bits to encode the thickness, and up to 8 bits to encode the profile ID.
// We need a lot of precision to minimize banding of NdotV-weighted thickness.
outGBuffer2 = float4(surfaceData.subsurfaceRadius,
PackFloatToR8G8(surfaceData.thickness),
PackByte(surfaceData.subsurfaceProfile));
outGBuffer2 = float4(surfaceData.subsurfaceRadius, surfaceData.thickness, 0, PackByte(surfaceData.subsurfaceProfile));
}
else if (surfaceData.materialId == MATERIALID_LIT_SPECULAR)
{

}
else if (supportsSSS && bsdfData.materialId == MATERIALID_LIT_SSS)
{
// Use 16 bits to encode the thickness, and up to 8 bits to encode the profile ID.
// We need a lot of precision to minimize banding of NdotV-weighted thickness.
float thickness = UnpackFloatFromR8G8(inGBuffer2.yz);
float thickness = inGBuffer2.y;
int subsurfaceProfile = UnpackByte(inGBuffer2.w);
FillMaterialIdSSSData(baseColor, subsurfaceProfile, subsurfaceRadius, thickness, bsdfData);

[branch] if (bsdfData.enableTransmission)
{
// Reverse the normal + do some wrap lighting to have a nicer transition between regular lighting and transmittance
// Ref: Steve McAuley - Energy-Conserving Wrapped Diffuse
illuminance = ComputeWrappedDiffuseLighting(NdotL, SSS_WRAP_LIGHT);
// Use the reversed normal from the front for the back of the object.
illuminance = F_Transm_Schlick(bsdfData.fresnel0, saturate(-NdotL));
// The difference between the Disney Diffuse and the Lambertian BRDF for transmission is negligible.
float3 backLight = (cookie.rgb * lightData.color) * (illuminance * lightData.diffuseScale * Lambert());
float3 backLight = (cookie.rgb * lightData.color) * (illuminance * lightData.diffuseScale);
float3 transmittedLight = backLight * bsdfData.diffuseColor * bsdfData.transmittance;
float3 transmittedLight = backLight * (bsdfData.diffuseColor * bsdfData.transmittance);
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
diffuseLighting += transmittedLight;

[branch] if (bsdfData.enableTransmission)
{
// Reverse the normal + do some wrap lighting to have a nicer transition between regular lighting and transmittance
// Ref: Steve McAuley - Energy-Conserving Wrapped Diffuse
illuminance = ComputeWrappedDiffuseLighting(NdotL, SSS_WRAP_LIGHT) * attenuation;
// Use the reversed normal from the front for the back of the object.
illuminance = F_Transm_Schlick(bsdfData.fresnel0, saturate(-NdotL)) * attenuation;
// The difference between the Disney Diffuse and the Lambertian BRDF for transmission is negligible.
float3 backLight = (cookie.rgb * lightData.color) * (illuminance * lightData.diffuseScale * Lambert());
float3 backLight = (cookie.rgb * lightData.color) * (illuminance * lightData.diffuseScale);
float3 transmittedLight = backLight * bsdfData.diffuseColor * bsdfData.transmittance;
float3 transmittedLight = backLight * (bsdfData.diffuseColor * bsdfData.transmittance);
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
diffuseLighting += transmittedLight;

[branch] if (bsdfData.enableTransmission)
{
// Reverse the normal + do some wrap lighting to have a nicer transition between regular lighting and transmittance
illuminance = ComputeWrappedDiffuseLighting(NdotL, SSS_WRAP_LIGHT) * clipFactor;
// Use the reversed normal from the front for the back of the object.
illuminance = F_Transm_Schlick(bsdfData.fresnel0, saturate(-NdotL)) * clipFactor;
// The difference between the Disney Diffuse and the Lambertian BRDF for transmission is negligible.
float3 backLight = (cookie.rgb * lightData.color) * (illuminance * lightData.diffuseScale * Lambert());
float3 backLight = (cookie.rgb * lightData.color) * (illuminance * lightData.diffuseScale);
float3 transmittedLight = backLight * bsdfData.diffuseColor * bsdfData.transmittance;
float3 transmittedLight = backLight * (bsdfData.diffuseColor * bsdfData.transmittance);
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
diffuseLighting += transmittedLight;

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


_HorizonFade("Horizon fade", Range(0.0, 5.0)) = 1.0
// Stencil state
[HideInInspector] _StencilRef("_StencilRef", Int) = 2 // StencilBits.NonSSS
[HideInInspector] _StencilRef("_StencilRef", Int) = 2 // StencilLightingUsage.RegularLighting (fixed at compile time)
// Blending state
[HideInInspector] _SurfaceType("__surfacetype", Float) = 0.0

[HideInInspector] _UVMappingMask("_UVMappingMask", Color) = (1, 0, 0, 0)
[Enum(TangentSpace, 0, ObjectSpace, 1)] _NormalMapSpace("NormalMap space", Float) = 0
[Enum(Subsurface Scattering, 0, Standard, 1, Specular Color, 2)] _MaterialID("MaterialId", Int) = 1 // MaterialId.LitStandard
[Enum(Subsurface Scattering, 0, Standard, 1, Specular Color, 2)] _MaterialID("MaterialId", Int) = 1 // MaterialId.RegularLighting
[ToggleOff] _EnablePerPixelDisplacement("Enable per pixel displacement", Float) = 0.0
_PPDMinSamples("Min sample for POM", Range(1.0, 64.0)) = 5

2
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitData.hlsl


float3 sigmaX = dPdx - dot(dPdx, vertexNormalWS) * vertexNormalWS;
float3 sigmaY = dPdy - dot(dPdy, vertexNormalWS) * vertexNormalWS;
//float flipSign = dot(sigmaY, cross(nrmVertexNormal, sigmaX) ) ? -1.0 : 1.0;
//float flipSign = dot(sigmaY, cross(vertexNormalWS, sigmaX) ) ? -1.0 : 1.0;
float flipSign = dot(dPdy, cross(vertexNormalWS, dPdx)) < 0.0 ? -1.0 : 1.0; // gives same as the commented out line above
// TODO: Optimize! The compiler will not be able to remove the tangent space that are not use because it can't know due to our UVMapping constant we use for both base and details

5
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitDataInternal.hlsl


// This part of the code is not used in case of layered shader but we keep the same macro system for simplicity
#if !defined(LAYERED_LIT_SHADER)
surfaceData.materialId = (_EnableSSS || _MaterialID != MATERIALID_LIT_SSS) ? _MaterialID : MATERIALID_LIT_STANDARD;
// TODO: In order to let the compiler optimize in case of forward rendering this need to be a variant (shader feature) and not a parameter!
surfaceData.materialId = _MaterialID;
#ifdef _TANGENTMAP
#ifdef _NORMALMAP_TANGENT_SPACE_IDX // Normal and tangent use same space

#ifdef _THICKNESSMAP
surfaceData.thickness *= SAMPLE_UVMAPPING_TEXTURE2D(_ThicknessMap, sampler_ThicknessMap, layerTexCoord.base).r;
#endif
surfaceData.thickness = 1 - surfaceData.thickness; // Reverse for artists
surfaceData.specularColor = _SpecularColor.rgb;
#ifdef _SPECULARCOLORMAP

2
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader


_HorizonFade("Horizon fade", Range(0.0, 5.0)) = 1.0
// Stencil state
[HideInInspector] _StencilRef("_StencilRef", Int) = 2 // StencilBits.NonSSS
[HideInInspector] _StencilRef("_StencilRef", Int) = 2 // StencilLightingUsage.RegularLighting (fixed at compile time)
// Blending state
[HideInInspector] _SurfaceType("__surfacetype", Float) = 0.0

998
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.DisneyDiffuse.cs
文件差异内容过多而无法显示
查看文件

998
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.GGX.cs
文件差异内容过多而无法显示
查看文件

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


// Inputs & outputs
//-------------------------------------------------------------------------------------
float _WorldScales[SSS_N_PROFILES]; // Size of the world unit in meters
float _FilterKernelsNearField[SSS_N_PROFILES][SSS_N_SAMPLES_NEAR_FIELD][2]; // 0 = radius, 1 = reciprocal of the PDF
float _FilterKernelsFarField[SSS_N_PROFILES][SSS_N_SAMPLES_FAR_FIELD][2]; // 0 = radius, 1 = reciprocal of the PDF
float4 _SurfaceShapeParams[SSS_N_PROFILES]; // RGB = S = 1 / D, A = filter radius
float _WorldScales[SSS_N_PROFILES]; // Size of the world unit in meters
float _FilterKernelsNearField[SSS_N_PROFILES][SSS_N_SAMPLES_NEAR_FIELD][2]; // 0 = radius, 1 = reciprocal of the PDF
float _FilterKernelsFarField[SSS_N_PROFILES][SSS_N_SAMPLES_FAR_FIELD][2]; // 0 = radius, 1 = reciprocal of the PDF
TEXTURE2D(_IrradianceSource); // Includes transmitted light
DECLARE_GBUFFER_TEXTURE(_GBufferTexture); // Contains the albedo and SSS parameters

float2 vec = r * float2(cos(phi), sin(phi)); \
\
float2 position = centerPosUnSS + vec * scaledPixPerMm; \
float rcpPdf = kernel[profileID][i][1]; \
float3 irradiance = LOAD_TEXTURE2D(_IrradianceSource, position).rgb; \
\
/* TODO: see if making this a [branch] improves performance. */ \

float z = LOAD_TEXTURE2D(_MainDepthTexture, position).r; \
float d = LinearEyeDepth(z, _ZBufferParams); \
float t = millimPerUnit * d - (millimPerUnit * centerDepthVS); \
float3 w = ComputeBilateralWeight(shapeParam, r, t, rcpDistScale, rcpPdf); \
float p = kernel[profileID][i][1]; \
float3 w = ComputeBilateralWeight(shapeParam, r, t, rcpDistScale, p); \
\
totalIrradiance += w * irradiance; \
totalWeight += w; \

int profileID = bsdfData.subsurfaceProfile;
float distScale = bsdfData.subsurfaceRadius;
float3 shapeParam = _ShapeParameters[profileID].rgb;
float maxDistance = _ShapeParameters[profileID].a;
float3 shapeParam = _SurfaceShapeParams[profileID].rgb;
float maxDistance = _SurfaceShapeParams[profileID].a;
// Reconstruct the view-space position.
float2 centerPosSS = posInput.positionSS;

float2 scaledPixPerMm = distScale * rcp(millimPerUnit * unitsPerPixel);
// Take the first (central) sample.
// TODO: copy its neighborhood into LDS.
float2 centerPosition = posInput.unPositionSS;
float3 centerIrradiance = LOAD_TEXTURE2D(_IrradianceSource, centerPosition).rgb;

111
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringProfile.cs


using System;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor;
#endif
namespace UnityEngine.Experimental.Rendering.HDPipeline

[HideInInspector]
public int settingsIndex; // SubsurfaceScatteringSettings.profiles[i]
[SerializeField]
Vector3 m_S; // RGB = shape parameter: S = 1 / D
Vector3 m_SurfaceShapeParam; // RGB = shape parameter: S = 1 / D
[SerializeField]
Vector3 m_VolumeShapeParam; // RGB = shape parameter: S = 1 / D
[SerializeField]
float m_ScatteringDistance; // Filter radius (in millimeters)
[SerializeField]

m_FilterKernelFarField = new Vector2[SssConstants.SSS_N_SAMPLES_FAR_FIELD];
}
m_S = new Vector3();
m_SurfaceShapeParam = new Vector3();
m_S.x = FindFitForS(surfaceAlbedo.r);
m_S.y = FindFitForS(surfaceAlbedo.g);
m_S.z = FindFitForS(surfaceAlbedo.b);
m_SurfaceShapeParam.x = FindFitForS(surfaceAlbedo.r);
m_SurfaceShapeParam.y = FindFitForS(surfaceAlbedo.g);
m_SurfaceShapeParam.z = FindFitForS(surfaceAlbedo.b);
m_VolumeShapeParam.x = FindFitForS(volumeAlbedo.r);
m_VolumeShapeParam.y = FindFitForS(volumeAlbedo.g);
m_VolumeShapeParam.z = FindFitForS(volumeAlbedo.b);
m_S.x *= 1.0f / lenVolMeanFreePath;
m_S.y *= 1.0f / lenVolMeanFreePath;
m_S.z *= 1.0f / lenVolMeanFreePath;
m_SurfaceShapeParam *= 1.0f / lenVolMeanFreePath;
m_VolumeShapeParam *= 1.0f / lenVolMeanFreePath;
float s = Mathf.Min(m_S.x, m_S.y, m_S.z);
float s = Mathf.Min(m_SurfaceShapeParam.x, m_SurfaceShapeParam.y, m_SurfaceShapeParam.z);
// Importance sample the normalized diffusion profile for the computed value of 's'.
// ------------------------------------------------------------------------------------

// ------------------------------------------------------------------------------------
// N.b.: computation of normalized weights, and multiplication by the surface albedo
// of the actual geometry is performed at runtime (in the shader).
m_FilterKernelNearField[i].x = r;

}
}
public Vector3 shapeParameter
public Vector3 surfaceShapeParameter
get { return m_S; }
get { return m_SurfaceShapeParam; }
}
public Vector3 volumeShapeParameter
{
// Set in BuildKernel().
get { return m_VolumeShapeParam; }
}
public float scatteringDistance

// Set in BuildKernel().
get { return m_FilterKernelNearField; }
}
public Vector2[] filterKernelFarField
{
// Set in BuildKernel().

[NonSerialized] public uint texturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter
[NonSerialized] public uint transmissionFlags; // 2 bit/profile; 0 = inf. thick, 1 = thin, 2 = regular
[NonSerialized] public float[] thicknessRemaps; // Remap: 0 = start, 1 = end - start
[NonSerialized] public Vector4[] shapeParameters; // RGB = S = 1 / D, A = filter radius
[NonSerialized] public Vector4[] surfaceShapeParams; // RGB = S = 1 / D, A = filter radius
[NonSerialized] public Vector4[] volumeShapeParams; // RGB = S = 1 / D, A = unused
[NonSerialized] public Vector4[] volumeAlbedos; // RGB = color, A = unused
[NonSerialized] public float[] worldScales; // Size of the world unit in meters
[NonSerialized] public float[] filterKernelsNearField; // 0 = radius, 1 = reciprocal of the PDF

texturingModeFlags = 0;
transmissionFlags = 0;
thicknessRemaps = null;
shapeParameters = null;
surfaceShapeParams = null;
volumeShapeParams = null;
filterKernelsNearField = null;
filterKernelsFarField = null;

thicknessRemaps = new float[thicknessRemapsLen];
}
const int worldScalesLen = SssConstants.SSS_N_PROFILES;
if (worldScales == null || worldScales.Length != worldScalesLen)
if (worldScales == null || worldScales.Length != SssConstants.SSS_N_PROFILES)
worldScales = new float[worldScalesLen];
worldScales = new float[SssConstants.SSS_N_PROFILES];
}
if (surfaceShapeParams == null || surfaceShapeParams.Length != SssConstants.SSS_N_PROFILES)
{
surfaceShapeParams = new Vector4[SssConstants.SSS_N_PROFILES];
const int shapeParametersLen = SssConstants.SSS_N_PROFILES;
if (shapeParameters == null || shapeParameters.Length != shapeParametersLen)
if (volumeShapeParams == null || volumeShapeParams.Length != SssConstants.SSS_N_PROFILES)
shapeParameters = new Vector4[shapeParametersLen];
volumeShapeParams = new Vector4[SssConstants.SSS_N_PROFILES];
const int volumeAlbedosLen = SssConstants.SSS_N_PROFILES;
if (volumeAlbedos == null || volumeAlbedos.Length != volumeAlbedosLen)
if (volumeAlbedos == null || volumeAlbedos.Length != SssConstants.SSS_N_PROFILES)
volumeAlbedos = new Vector4[volumeAlbedosLen];
volumeAlbedos = new Vector4[SssConstants.SSS_N_PROFILES];
}
const int filterKernelsNearFieldLen = 2 * SssConstants.SSS_N_PROFILES * SssConstants.SSS_N_SAMPLES_NEAR_FIELD;

thicknessRemaps[2 * i] = profiles[i].thicknessRemap.x;
thicknessRemaps[2 * i + 1] = profiles[i].thicknessRemap.y - profiles[i].thicknessRemap.x;
worldScales[i] = profiles[i].worldScale;
shapeParameters[i] = profiles[i].shapeParameter;
shapeParameters[i].w = profiles[i].scatteringDistance;
surfaceShapeParams[i] = profiles[i].surfaceShapeParameter;
surfaceShapeParams[i].w = profiles[i].scatteringDistance;
volumeShapeParams[i] = profiles[i].volumeShapeParameter;
volumeAlbedos[i] = profiles[i].volumeAlbedo;
for (int j = 0, n = SssConstants.SSS_N_SAMPLES_NEAR_FIELD; j < n; j++)

{
int i = SssConstants.SSS_NEUTRAL_PROFILE_ID;
shapeParameters[i] = Vector4.zero;
volumeAlbedos[i] = Vector4.zero;
worldScales[i] = 1.0f;
surfaceShapeParams[i] = Vector4.zero;
volumeShapeParams[i] = Vector4.zero;
volumeAlbedos[i] = Vector4.zero;
worldScales[i] = 1.0f;
for (int j = 0, n = SssConstants.SSS_N_SAMPLES_NEAR_FIELD; j < n; j++)
{

#if UNITY_EDITOR
public class SubsurfaceScatteringProfileFactory
{
[MenuItem("Assets/Create/Subsurface Scattering Profile", priority = 666)]
[MenuItem("Assets/Create/HDRenderPipeline/Subsurface Scattering Profile", priority = 666)]
static void MenuCreateSubsurfaceScatteringProfile()
{
Texture2D icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");

private RenderTexture m_ProfileImage, m_TransmittanceImage;
private Material m_ProfileMaterial, m_TransmittanceMaterial;
private SerializedProperty m_LenVolMeanFreePath, m_ScatteringDistance, m_SurfaceAlbedo, m_VolumeAlbedo, m_S,
private SerializedProperty m_LenVolMeanFreePath, m_ScatteringDistance, m_SurfaceAlbedo, m_VolumeAlbedo, m_SurfaceShapeParam, m_VolumeShapeParam,
m_TexturingMode, m_TransmissionMode, m_ThicknessRemap, m_WorldScale;
void OnEnable()

m_LenVolMeanFreePath = serializedObject.FindProperty("lenVolMeanFreePath");
m_ScatteringDistance = serializedObject.FindProperty("m_ScatteringDistance");
m_S = serializedObject.FindProperty("m_S");
m_SurfaceShapeParam = serializedObject.FindProperty("m_SurfaceShapeParam");
m_VolumeShapeParam = serializedObject.FindProperty("m_VolumeShapeParam");
// These shaders don't need to be reference by RenderPipelineResource as they are not use at runtime
m_ProfileMaterial = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/DrawSssProfile");
m_TransmittanceMaterial = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/DrawTransmittanceGraph");

{
EditorGUILayout.PropertyField(m_SurfaceAlbedo, styles.sssProfileSurfaceAlbedo);
m_LenVolMeanFreePath.floatValue = EditorGUILayout.Slider(styles.sssProfileLenVolMeanFreePath, m_LenVolMeanFreePath.floatValue, 0.01f, 1.0f);
GUI.enabled = false;
EditorGUILayout.PropertyField(m_ScatteringDistance, styles.sssProfileScatteringDistance);
GUI.enabled = true;

EditorGUILayout.Space();
}
float d = m_ScatteringDistance.floatValue;
Vector4 A = m_SurfaceAlbedo.colorValue;
Vector4 V = m_VolumeAlbedo.colorValue;
Vector3 S = m_S.vector3Value;
Vector2 R = m_ThicknessRemap.vector2Value;
float d = m_ScatteringDistance.floatValue;
Vector4 aS = m_SurfaceAlbedo.colorValue;
Vector4 aV = m_VolumeAlbedo.colorValue;
Vector3 sS = m_SurfaceShapeParam.vector3Value;
Vector3 sV = m_VolumeShapeParam.vector3Value;
Vector2 R = m_ThicknessRemap.vector2Value;
m_ProfileMaterial.SetVector("_SurfaceAlbedo", A);
m_ProfileMaterial.SetVector("_ShapeParameter", S);
m_ProfileMaterial.SetVector("_SurfaceAlbedo", aS);
m_ProfileMaterial.SetVector("_SurfaceShapeParam", sS);
EditorGUILayout.Space();
EditorGUILayout.LabelField(styles.sssTransmittancePreview0, styles.centeredMiniBoldLabel);
EditorGUILayout.LabelField(styles.sssTransmittancePreview1, EditorStyles.centeredGreyMiniLabel);

// Draw the transmittance graph.
m_TransmittanceMaterial.SetFloat("_ScatteringDistance", d);
m_TransmittanceMaterial.SetVector("_VolumeAlbedo", transmissionEnabled ? V : Vector4.zero);
m_TransmittanceMaterial.SetVector("_ShapeParameter", S);
m_TransmittanceMaterial.SetVector("_VolumeAlbedo", transmissionEnabled ? aV : Vector4.zero);
m_TransmittanceMaterial.SetVector("_VolumeShapeParam", sV);
m_TransmittanceMaterial.SetVector("_ThicknessRemap", R);
EditorGUI.DrawPreviewTexture(GUILayoutUtility.GetRect(16, 16), m_TransmittanceImage, m_TransmittanceMaterial, ScaleMode.ScaleToFit, 16.0f);

}
}
#endif
}
}

2
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.cs


//-----------------------------------------------------------------------------
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
namespace Unlit
public class Unlit : RenderPipelineMaterial
{
//-----------------------------------------------------------------------------
// SurfaceData

10
Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/RenderPipelineResources.cs


instance.shadeOpaqueShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/shadeopaque.compute");
// SceneSettings
instance.drawGaussianProfileShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/DrawGaussianProfile.shader");
instance.drawTransmittanceGraphShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/DrawTransmittanceGraph.shader");
// These shaders don't need to be reference by RenderPipelineResource as they are not use at runtime (only to draw in editor)
// instance.drawSssProfile = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/DrawSssProfile.shader");
// instance.drawTransmittanceGraphShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/DrawTransmittanceGraph.shader");
// Sky
instance.blitCubemap = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/Sky/BlitCubemap.shader");

public ComputeShader shadeOpaqueShader;
// SceneSettings
public Shader drawGaussianProfileShader;
public Shader drawTransmittanceGraphShader;
// These shaders don't need to be reference by RenderPipelineResource as they are not use at runtime (only to draw in editor)
// public Shader drawSssProfile;
// public Shader drawTransmittanceGraphShader;
// Sky
public Shader blitCubemap;

4
Assets/ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawSssProfile.shader


// Inputs & outputs
//-------------------------------------------------------------------------------------
float4 _SurfaceAlbedo, _ShapeParameter;
float4 _SurfaceAlbedo, _SurfaceShapeParam;
float _ScatteringDistance; // See 'SubsurfaceScatteringProfile'
//-------------------------------------------------------------------------------------

float4 Frag(Varyings input) : SV_Target
{
float r = (2 * length(input.texcoord - 0.5)) * _ScatteringDistance;
float3 S = _ShapeParameter.rgb;
float3 S = _SurfaceShapeParam.rgb;
float3 M = S * (exp(-r * S) + exp(-r * S * (1.0 / 3.0))) / (8 * PI * r);
// N.b.: we multiply by the surface albedo of the actual geometry during shading.

4
Assets/ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader


// Inputs & outputs
//-------------------------------------------------------------------------------------
float4 _VolumeAlbedo, _ShapeParameter, _ThicknessRemap;
float4 _VolumeAlbedo, _VolumeShapeParam, _ThicknessRemap;
float _ScatteringDistance; // See 'SubsurfaceScatteringProfile'
//-------------------------------------------------------------------------------------

float4 Frag(Varyings input) : SV_Target
{
float d = (_ThicknessRemap.x + input.texcoord.x * (_ThicknessRemap.y - _ThicknessRemap.x));
float3 T = ComputeTransmittance(_ShapeParameter.rgb, float3(1, 1, 1), d, 1);
float3 T = ComputeTransmittance(_VolumeShapeParam.rgb, float3(1, 1, 1), d, 1);
// Apply gamma for visualization only. Do not apply gamma to the color.
return float4(pow(T, 1.0 / 3) * _VolumeAlbedo.rgb, 1);

28
Assets/ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/VaryingMesh.hlsl


#endif
#ifdef VARYINGS_NEED_TANGENT_TO_WORLD
float4 tangentWS = float4(input.interpolators2.xyz, input.interpolators2.w > 0.0 ? 1.0 : -1.0);
// TODO: We should be able to not make distinction between the two path, but it mean material need to be aware to normalize the TBN when required, like for example for POM.
// For now do some test by keeping code consistent with previous visual.
#ifdef SURFACE_GRADIENT
float4 tangentWS = float4(input.interpolators2.xyz, input.interpolators2.w > 0.0 ? 1.0 : -1.0); // must not be normalized (mikkts requirement)
// no normalizes is mandatory for tangentWS
float3x3 worldToTangent = CreateWorldToTangent(unnormalizedNormalWS, tangentWS.xyz, tangentWS.w); // this is the mikktspace transformation (must use unnormalized attributes)
// this is the mikktspace transformation (must use unnormalized attributes)
float3x3 worldToTangent = CreateWorldToTangent(unnormalizedNormalWS, tangentWS.xyz, tangentWS.w);
output.worldToTangent[2] = worldToTangent[2] * renormFactor;
float3 normalWS = output.worldToTangent[2];
#else
// TODO: Check if we must do like for surface gradient (i.e not normalize ?) For now, for consistency with previous code we normalize
// Normalize after the interpolation
float3 normalWS = normalize(input.interpolators1);
tangentWS.xyz = normalize(tangentWS.xyz);
// bitangent on the fly option in xnormal to reduce vertex shader outputs.
float3x3 worldToTangent = CreateWorldToTangent(normalWS, tangentWS.xyz, tangentWS.w);
output.worldToTangent[0] = worldToTangent[0];
output.worldToTangent[1] = worldToTangent[1];
output.worldToTangent[2] = worldToTangent[2];
#endif
output.worldToTangent[2] = worldToTangent[2] * renormFactor; // normalizes the interpolated vertex normal
#endif // VARYINGS_NEED_TANGENT_TO_WORLD
#ifdef VARYINGS_NEED_TEXCOORD0

38
Assets/ScriptableRenderPipeline/HDRenderPipeline/Utilities.cs


using System.Linq.Expressions;
using System.Text;
using UnityEngine.Rendering;
using System.Reflection;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{

ClearDepth = 2
}
[Flags]
public enum StencilBits
public class Utilities
None = 0, // 0
SSS = 1 + Lit.MaterialId.LitSSS, // 1
NonSSS = 2 + Lit.MaterialId.LitSSS, // 2
All = 255 // 0xFF
}
public static List<RenderPipelineMaterial> GetRenderPipelineMaterialList()
{
List<RenderPipelineMaterial> materialList = new List<RenderPipelineMaterial>();
var baseType = typeof(RenderPipelineMaterial);
var assembly = baseType.Assembly;
public class Utilities
{
System.Type[] types = assembly.GetTypes();
foreach (System.Type type in types)
{
if (type.IsSubclassOf(baseType))
{
// Create an instance object of the given type
var obj = (RenderPipelineMaterial)Activator.CreateInstance(type);
materialList.Add(obj);
}
}
// Note: If there is a need for an optimization in the future of this function, user can simply fill the materialList manually by commenting the code abode and
// adding to the list material they used in their game.
// materialList.Add(new Lit());
// materialList.Add(new Unlit());
// ...
return materialList;
}
public const RendererConfiguration kRendererConfigurationBakedLighting = RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbeProxyVolume;

83
Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightPipelineUpgraders.cs


public static void UpdateMaterialKeywords(Material material)
{
UpdateMaterialBlendMode(material);
LightweightShaderHelper.SetMaterialBlendMode(material);
SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap"));
SetKeyword(material, "_CUBEMAP_REFLECTION", material.GetTexture("_Cube"));
SetKeyword(material, "_EMISSION", material.GetTexture("_EmissionMap"));
}
private static void UpdateMaterialBlendMode(Material material)
{
UpgradeBlendMode mode = (UpgradeBlendMode)material.GetFloat("_Mode");
switch (mode)
{
case UpgradeBlendMode.Opaque:
material.SetOverrideTag("RenderType", "");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
SetKeyword(material, "_ALPHATEST_ON", false);
SetKeyword(material, "_ALPHABLEND_ON", false);
material.renderQueue = -1;
break;
case UpgradeBlendMode.Cutout:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
SetKeyword(material, "_ALPHATEST_ON", true);
SetKeyword(material, "_ALPHABLEND_ON", false);
material.renderQueue = (int)RenderQueue.AlphaTest;
break;
case UpgradeBlendMode.Alpha:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
SetKeyword(material, "_ALPHATEST_ON", false);
SetKeyword(material, "_ALPHABLEND_ON", true);
material.renderQueue = (int)RenderQueue.Transparent;
break;
}
LightweightShaderHelper.SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap"));
LightweightShaderHelper.SetKeyword(material, "_CUBEMAP_REFLECTION", material.GetTexture("_Cube"));
LightweightShaderHelper.SetKeyword(material, "_EMISSION", material.GetTexture("_EmissionMap"));
}
private static void UpdateMaterialSpecularSource(Material material)

{
SetKeyword(material, "_SPECGLOSSMAP", false);
SetKeyword(material, "_SPECGLOSSMAP_BASE_ALPHA", false);
SetKeyword(material, "_SPECULAR_COLOR", false);
LightweightShaderHelper.SetKeyword(material, "_SPECGLOSSMAP", false);
LightweightShaderHelper.SetKeyword(material, "_SPECGLOSSMAP_BASE_ALPHA", false);
LightweightShaderHelper.SetKeyword(material, "_SPECULAR_COLOR", false);
}
else if (specSource == SpecularSource.SpecularTextureAndColor && material.GetTexture("_SpecGlossMap"))
{

SetKeyword(material, "_SPECGLOSSMAP", false);
SetKeyword(material, "_SPECGLOSSMAP_BASE_ALPHA", true);
LightweightShaderHelper.SetKeyword(material, "_SPECGLOSSMAP", false);
LightweightShaderHelper.SetKeyword(material, "_SPECGLOSSMAP_BASE_ALPHA", true);
SetKeyword(material, "_SPECGLOSSMAP", true);
SetKeyword(material, "_SPECGLOSSMAP_BASE_ALPHA", false);
LightweightShaderHelper.SetKeyword(material, "_SPECGLOSSMAP", true);
LightweightShaderHelper.SetKeyword(material, "_SPECGLOSSMAP_BASE_ALPHA", false);
SetKeyword(material, "_SPECULAR_COLOR", false);
LightweightShaderHelper.SetKeyword(material, "_SPECULAR_COLOR", false);
SetKeyword(material, "_SPECGLOSSMAP", false);
SetKeyword(material, "_SPECGLOSSMAP_BASE_ALPHA", false);
SetKeyword(material, "_SPECULAR_COLOR", true);
LightweightShaderHelper.SetKeyword(material, "_SPECGLOSSMAP", false);
LightweightShaderHelper.SetKeyword(material, "_SPECGLOSSMAP_BASE_ALPHA", false);
LightweightShaderHelper.SetKeyword(material, "_SPECULAR_COLOR", true);
SetKeyword(material, "_REFLECTION_CUBEMAP", false);
SetKeyword(material, "_REFLECTION_PROBE", false);
LightweightShaderHelper.SetKeyword(material, "_REFLECTION_CUBEMAP", false);
LightweightShaderHelper.SetKeyword(material, "_REFLECTION_PROBE", false);
SetKeyword(material, "_REFLECTION_CUBEMAP", true);
LightweightShaderHelper.SetKeyword(material, "_REFLECTION_CUBEMAP", true);
SetKeyword(material, "_REFLECTION_PROBE", true);
LightweightShaderHelper.SetKeyword(material, "_REFLECTION_PROBE", true);
}
private static void SetKeyword(Material material, string keyword, bool enable)
{
if (enable)
material.EnableKeyword(keyword);
else
material.DisableKeyword(keyword);
}
}

6
Assets/ScriptableRenderPipeline/ShaderLibrary/CommonMaterial.hlsl


return 0.25 * (expOneThird + 3 * expOneThird * expOneThird * expOneThird) * volumeAlbedo;
}
// Ref: Steve McAuley - Energy-Conserving Wrapped Diffuse
float ComputeWrappedDiffuseLighting(float NdotL, float w)
{
return saturate((-NdotL + w) / ((1 + w) * (1 + w)));
}
// MACRO from Legacy Untiy
// Transforms 2D UV by scale/bias property
#define TRANSFORM_TEX(tex, name) ((tex.xy) * name##_ST.xy + name##_ST.zw)

12
Assets/TestScenes/HDTest/GraphicTest/Common/Dragon/DragonStatueSpecular.mat


_TESSELLATION_OBJECT_SCALE
m_LightmapFlags: 1
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses:

m_Texture: {fileID: 2800000, guid: ad9cb02bddceb1340bc1fcb19d5f35bd, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _NormalMapOS:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}

m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _TangentMapOS:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ThicknessMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}

- _DoubleSidedEnable: 0
- _DoubleSidedMirrorEnable: 1
- _DoubleSidedMode: 0
- _DoubleSidedNormalMode: 1
- _Drag: 1
- _DstBlend: 0
- _EmissiveColorMode: 1

- _SmoothnessVar: 0.491
- _SpecularHighlights: 1
- _SrcBlend: 1
- _StencilRef: 3
- _StencilRef: 2
- _Stiffness: 1
- _SubsurfaceProfile: 0
- _SubsurfaceRadius: 1

999
ImageTemplates/LightweightPipeline/Scenes/Shaders/LDPipe_LitShaderMaps.unity.png
文件差异内容过多而无法显示
查看文件

2
ProjectSettings/GraphicsSettings.asset


m_PreloadedShaders: []
m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000,
type: 0}
m_CustomRenderPipeline: {fileID: 11400000, guid: e185fecca3c73cd47a09f1092663ef32,
m_CustomRenderPipeline: {fileID: 11400000, guid: 449281dd2b4fbee49b8397de0541ea3c,
type: 2}
m_TransparencySortMode: 0
m_TransparencySortAxis: {x: 0, y: 0, z: 1}

23
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/RenderPipelineMaterial.cs


using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class RenderPipelineMaterial : Object
{
// GBuffer management
public virtual int GetMaterialGBufferCount() { return 0; }
public virtual void GetMaterialGBufferDescription(out RenderTextureFormat[] RTFormat, out RenderTextureReadWrite[] RTReadWrite)
{
RTFormat = null;
RTReadWrite = null;
}
// Regular interface
public virtual void Build(RenderPipelineResources renderPipelineResources) {}
public virtual void Cleanup() {}
// Following function can be use to initialize GPU resource (once or each frame) and bind them
public virtual void RenderInit(Rendering.ScriptableRenderContext renderContext) {}
public virtual void Bind() {}
}
}

12
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/RenderPipelineMaterial.cs.meta


fileFormatVersion: 2
guid: 7c168d89b1622cd479edd36df0a8869e
timeCreated: 1496530306
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

53
Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightShaderHelper.cs


using UnityEngine;
using UnityEngine.Rendering;
namespace UnityEditor.Experimental.Rendering.LightweightPipeline
{
public static class LightweightShaderHelper
{
public static void SetMaterialBlendMode(Material material)
{
UpgradeBlendMode mode = (UpgradeBlendMode) material.GetFloat("_Mode");
switch (mode)
{
case UpgradeBlendMode.Opaque:
material.SetOverrideTag("RenderType", "");
material.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
SetKeyword(material, "_ALPHATEST_ON", false);
SetKeyword(material, "_ALPHABLEND_ON", false);
material.renderQueue = -1;
break;
case UpgradeBlendMode.Cutout:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
SetKeyword(material, "_ALPHATEST_ON", true);
SetKeyword(material, "_ALPHABLEND_ON", false);
material.renderQueue = (int) RenderQueue.AlphaTest;
break;
case UpgradeBlendMode.Alpha:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
SetKeyword(material, "_ALPHATEST_ON", false);
SetKeyword(material, "_ALPHABLEND_ON", true);
material.renderQueue = (int) RenderQueue.Transparent;
break;
}
}
public static void SetKeyword(Material material, string keyword, bool enable)
{
if (enable)
material.EnableKeyword(keyword);
else
material.DisableKeyword(keyword);
}
}
}

12
Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightShaderHelper.cs.meta


fileFormatVersion: 2
guid: 673aad8cdc228cf499f7974fb673fa10
timeCreated: 1496821330
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

9
Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI.meta


fileFormatVersion: 2
guid: c8b417f54d2314549995022591d5454f
folderAsset: yes
timeCreated: 1496821940
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

81
Assets/ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightUnlit.shader


Shader "ScriptableRenderPipeline/LightweightPipeline/Unlit"
{
Properties
{
_MainTex("Texture", 2D) = "white" {}
_MainColor("MainColor", Color) = (1, 1, 1, 1)
_Cutoff("AlphaCutout", Range(0.0, 1.0)) = 0.5
// BlendMode
[HideInInspector] _Mode("Mode", Float) = 0.0
[HideInInspector] _SrcBlend("Src", Float) = 1.0
[HideInInspector] _DstBlend("Dst", Float) = 0.0
[HideInInspector] _ZWrite("ZWrite", Float) = 1.0
}
SubShader
{
Tags { "RenderType" = "Opaque" "IgnoreProjectors" = "True" "RenderPipeline" = "LightweightPipe" "Lightmode" = "LightweightForward" }
LOD 100
Blend [_SrcBlend][_DstBlend]
ZWrite [_ZWrite]
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fog
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
half4 _MainColor;
half _Cutoff;
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
fixed4 texColor = tex2D(_MainTex, i.uv);
fixed alpha = texColor.a * _MainColor.a;
fixed3 color = texColor.rgb * _MainColor.rgb;
#ifdef _ALPHATEST_ON
clip(alpha - _Cutoff);
#endif
UNITY_APPLY_FOG(i.fogCoord, color);
#ifdef _ALPHABLEND_ON
return fixed4(color, alpha);
#else
return fixed4(color, 1.0);
#endif
}
ENDCG
}
}
CustomEditor "LightweightUnlitGUI"
}

9
Assets/ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightUnlit.shader.meta


fileFormatVersion: 2
guid: 650dd9526735d5b46b79224bc6e94025
timeCreated: 1496762173
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

68
Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightUnlitGUI.cs


using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor.Experimental.Rendering.LightweightPipeline;
public class LightweightUnlitGUI : ShaderGUI
{
private MaterialProperty blendModeProp = null;
private MaterialProperty mainTexProp = null;
private MaterialProperty mainColorProp = null;
private MaterialProperty alphaCutoffProp = null;
private MaterialEditor m_MaterialEditor = null;
private static class Styles
{
public static GUIContent[] mainTexLabels =
{
new GUIContent("MainTex (RGB)", "Base Color"),
new GUIContent("MainTex (RGB) Alpha (A)", "Base Color and Alpha")
};
public static readonly string[] blendNames = Enum.GetNames(typeof(UpgradeBlendMode));
public static string renderingModeLabel = "Rendering Mode";
public static string alphaCutoffLabel = "Alpha Cutoff";
}
private void FindMaterialProperties(MaterialProperty[] properties)
{
blendModeProp = FindProperty("_Mode", properties);
mainTexProp = FindProperty("_MainTex", properties);
mainColorProp = FindProperty("_MainColor", properties);
alphaCutoffProp = FindProperty("_Cutoff", properties);
}
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
{
Material material = materialEditor.target as Material;
m_MaterialEditor = materialEditor;
FindMaterialProperties(properties);
int modeValue = (int)blendModeProp.floatValue;
EditorGUI.BeginChangeCheck();
modeValue = EditorGUILayout.Popup(Styles.renderingModeLabel, modeValue, Styles.blendNames);
if (EditorGUI.EndChangeCheck())
blendModeProp.floatValue = modeValue;
GUIContent mainTexLabel = Styles.mainTexLabels[Math.Min(modeValue, 1)];
m_MaterialEditor.TexturePropertySingleLine(mainTexLabel, mainTexProp, mainColorProp);
m_MaterialEditor.TextureScaleOffsetProperty(mainTexProp);
if ((UpgradeBlendMode) modeValue == UpgradeBlendMode.Cutout)
m_MaterialEditor.RangeProperty(alphaCutoffProp, Styles.alphaCutoffLabel);
EditorGUILayout.Space();
EditorGUILayout.Space();
materialEditor.RenderQueueField();
LightweightShaderHelper.SetMaterialBlendMode(material);
EditorGUILayout.Space();
EditorGUILayout.Space();
}
}

12
Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightUnlitGUI.cs.meta


fileFormatVersion: 2
guid: 3be3f3707c329b043b5816855ee127fd
timeCreated: 1487767801
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

/Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightPipelineMaterialEditor.cs.meta → /Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightPipelineMaterialEditor.cs.meta

/Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightPipelineMaterialEditor.cs → /Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightPipelineMaterialEditor.cs

正在加载...
取消
保存