浏览代码

Merge pull request #286 from Unity-Technologies/Update-material-framework

Update material framework
/RenderPassXR_Sandbox
GitHub 7 年前
当前提交
1b926dca
共有 23 个文件被更改,包括 1441 次插入1324 次删除
  1. 102
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs
  2. 41
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs
  3. 87
      Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
  4. 15
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs
  5. 91
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs
  6. 35
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs
  7. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader
  8. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader
  9. 8
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs
  10. 9
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/LitUI.cs
  11. 236
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs
  12. 29
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl
  13. 4
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader
  14. 3
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitDataInternal.hlsl
  15. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader
  16. 998
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.DisneyDiffuse.cs
  17. 998
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.GGX.cs
  18. 16
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringProfile.cs
  19. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.cs
  20. 38
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Utilities.cs
  21. 12
      Assets/TestScenes/HDTest/GraphicTest/Common/Dragon/DragonStatueSpecular.mat
  22. 23
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/RenderPipelineMaterial.cs
  23. 12
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/RenderPipelineMaterial.cs.meta

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()

87
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;
Material m_DebugViewMaterialGBuffer;
Material m_DebugDisplayLatlong;
// 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);
Shader.SetGlobalInt( "_TexturingModeFlags", (int)sssParameters.texturingModeFlags);
Shader.SetGlobalInt( "_TransmissionFlags", (int)sssParameters.transmissionFlags);
cmd.SetGlobalFloatArray( "_ThicknessRemaps", sssParameters.thicknessRemaps);

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;
var cmd = new CommandBuffer() { name = "Subsurface Scattering" };

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);

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);
}
}
}

29
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
uint _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter
uint _TransmissionFlags; // 2 bit/profile; 0 = inf. thick, 1 = thin, 2 = regular
float _ThicknessRemaps[SSS_N_PROFILES][2]; // Remap: 0 = start, 1 = end - start

uint transmissionMode = BitFieldExtract(_TransmissionFlags, 2u, 2u * subsurfaceProfile);
bsdfData.enableTransmission = transmissionMode != SSS_TRSM_MODE_NONE;
bsdfData.enableTransmission = transmissionMode != SSS_TRSM_MODE_NONE && (_EnableSSSAndTransmission > 0);
bsdfData.useThinObjectMode = transmissionMode == SSS_TRSM_MODE_THIN;
if (bsdfData.enableTransmission)

bool performPostScatterTexturing = IsBitSet(_TexturingModeFlags, subsurfaceProfile);
// We modify the albedo here as this code is used by all lighting (including light maps and GI).
if (performPostScatterTexturing)
#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
#ifndef SSS_PASS
bsdfData.diffuseColor = float3(1.0, 1.0, 1.0);
#endif
}
else
{
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);
}
}
}

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

3
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

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/SubsurfaceScatteringProfile.cs


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

// PDF(r, s) = s * (Exp[-r * s] + Exp[-r * s / 3]) / 4
// CDF(r, s) = 1 - 1/4 * Exp[-r * s] - 3/4 * Exp[-r * s / 3]
// ------------------------------------------------------------------------------------
// 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;

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

#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");

{
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;

m_ProfileMaterial.SetVector("_SurfaceAlbedo", A);
m_ProfileMaterial.SetVector("_ShapeParameter", S);
EditorGUI.DrawPreviewTexture(GUILayoutUtility.GetRect(256, 256), m_ProfileImage, m_ProfileMaterial, ScaleMode.ScaleToFit, 1.0f);
EditorGUILayout.Space();
EditorGUILayout.LabelField(styles.sssTransmittancePreview0, styles.centeredMiniBoldLabel);
EditorGUILayout.LabelField(styles.sssTransmittancePreview1, EditorStyles.centeredGreyMiniLabel);

}
}
#endif
}
}

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


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

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;

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

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:
正在加载...
取消
保存