浏览代码

Merge branch 'master' into lowendmobile

/vr_sandbox
Felipe Lira 8 年前
当前提交
be52007a
共有 242 个文件被更改,包括 4205 次插入2682 次删除
  1. 4
      Assets/BasicRenderLoopTutorial/BasicRenderLoop.cs
  2. 4
      Assets/Editor/Tests/RenderloopTests/RenderloopTestFixture.cs
  3. 2
      Assets/ScriptableRenderLoop/HDRenderPipeline/Debug/DebugViewMaterial.cs
  4. 2
      Assets/ScriptableRenderLoop/HDRenderPipeline/Debug/DebugViewMaterial.cs.hlsl
  5. 11
      Assets/ScriptableRenderLoop/HDRenderPipeline/Debug/Resources/DebugViewMaterialGBuffer.shader
  6. 12
      Assets/ScriptableRenderLoop/HDRenderPipeline/Debug/Resources/DebugViewTiles.shader
  7. 1
      Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipeline.asset
  8. 2
      Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipeline.asset.meta
  9. 82
      Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipeline.cs
  10. 5
      Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/Forward.hlsl
  11. 5
      Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/Resources/Deferred.shader
  12. 4
      Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/TilePass/ClusteredUtils.hlsl
  13. 9
      Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/TilePass/Resources/lightlistbuild-bigtile.compute
  14. 2
      Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/TilePass/Resources/lightlistbuild-clustered.compute
  15. 91
      Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/TilePass/TilePass.cs
  16. 2
      Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/TilePass/TilePass.cs.hlsl
  17. 12
      Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/TilePass/TilePass.hlsl
  18. 2
      Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/TilePass/TilePassLoop.hlsl
  19. 7
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Builtin/BuiltinData.hlsl
  20. 251
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/LayeredLit/Editor/LayeredLitUI.cs
  21. 98
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader
  22. 138
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader
  23. 53
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs
  24. 36
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Editor/LitUI.cs
  25. 77
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Lit.cs
  26. 58
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Lit.hlsl
  27. 55
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Lit.shader
  28. 479
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/LitData.hlsl
  29. 260
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/LitDataInternal.hlsl
  30. 48
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/LitProperties.hlsl
  31. 119
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/LitTessellation.hlsl
  32. 88
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/LitTessellation.shader
  33. 4
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Resources/PreIntegratedFGD.shader
  34. 196
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/ShaderPass/LitDepthPass.hlsl
  35. 174
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/ShaderPass/LitDistortionPass.hlsl
  36. 91
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/ShaderPass/LitMetaPass.hlsl
  37. 252
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/ShaderPass/LitSharePass.hlsl
  38. 215
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/ShaderPass/LitVelocityPass.hlsl
  39. 21
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/MaterialUtilities.hlsl
  40. 140
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Unlit/Unlit.shader
  41. 22
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Unlit/UnlitData.hlsl
  42. 2
      Assets/ScriptableRenderLoop/HDRenderPipeline/PostProcess/Resources/EyeAdaptation.shader
  43. 2
      Assets/ScriptableRenderLoop/HDRenderPipeline/PostProcess/Resources/FinalPass.shader
  44. 2
      Assets/ScriptableRenderLoop/HDRenderPipeline/PostProcess/Resources/LutGen.shader
  45. 26
      Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassDebugViewMaterial.hlsl
  46. 26
      Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl
  47. 26
      Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassDistortion.hlsl
  48. 26
      Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassForward.hlsl
  49. 26
      Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassForwardUnlit.hlsl
  50. 26
      Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassGBuffer.hlsl
  51. 49
      Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl
  52. 126
      Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassVelocity.hlsl
  53. 2
      Assets/ScriptableRenderLoop/HDRenderPipeline/Shadow/Shadow.hlsl
  54. 16
      Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/HDRISky/HDRISkyRenderer.cs
  55. 113
      Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/HDRISky/Resources/SkyHDRI.shader
  56. 30
      Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkyParameters.cs
  57. 73
      Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkyRenderer.cs
  58. 35
      Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/ProceduralSky/Resources/AtmosphericScattering.hlsl
  59. 34
      Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/ProceduralSky/Resources/SkyProcedural.shader
  60. 30
      Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/Resources/GGXConvolve.shader
  61. 128
      Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/SkyManager.cs
  62. 4
      Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/SkyRenderer.cs
  63. 17
      Assets/ScriptableRenderLoop/HDRenderPipeline/Utilities.cs
  64. 2
      Assets/ScriptableRenderLoop/RenderPasses/ShadowRenderPass.cs
  65. 9
      Assets/ScriptableRenderLoop/ShaderLibrary/API/D3D11.hlsl
  66. 9
      Assets/ScriptableRenderLoop/ShaderLibrary/API/PSSL.hlsl
  67. 2
      Assets/ScriptableRenderLoop/ShaderLibrary/AreaLighting.hlsl
  68. 13
      Assets/ScriptableRenderLoop/ShaderLibrary/BSDF.hlsl
  69. 51
      Assets/ScriptableRenderLoop/ShaderLibrary/Common.hlsl
  70. 10
      Assets/ScriptableRenderLoop/ShaderLibrary/CommonLighting.hlsl
  71. 7
      Assets/ScriptableRenderLoop/ShaderLibrary/CommonMaterial.hlsl
  72. 111
      Assets/ScriptableRenderLoop/ShaderLibrary/ImageBasedLighting.hlsl
  73. 2
      Assets/ScriptableRenderLoop/ShaderLibrary/Packing.hlsl
  74. 178
      Assets/ScriptableRenderLoop/ShaderLibrary/Tessellation.hlsl
  75. 6
      Assets/ScriptableRenderLoop/fptl/FptlLighting.cs
  76. 292
      Assets/ScriptableRenderLoop/fptl/Internal-DeferredComputeShading.compute
  77. 2
      Assets/ScriptableRenderLoop/fptl/Internal-DeferredReflections.shader
  78. 2
      Assets/ScriptableRenderLoop/fptl/Internal-DeferredShading.shader
  79. 2
      Assets/ScriptableRenderLoop/fptl/LightBoundsDebug.shader
  80. 6
      Assets/ScriptableRenderLoop/fptl/StandardTest.shader
  81. 7
      Assets/ScriptableRenderLoop/fptl/lightlistbuild-bigtile.compute
  82. 603
      Assets/TestScenes/HDTest/GlobalIlluminationTest.unity
  83. 769
      Assets/TestScenes/HDTest/HDRenderLoopTest.unity
  84. 49
      Assets/TestScenes/HDTest/LayeredLitTest/Material/Layered_BlendColor.mat
  85. 1
      Assets/TestScenes/HDTest/LayeredLitTest/Material/Layered_BlendColor.mat.meta
  86. 45
      Assets/TestScenes/HDTest/Material/HDRenderLoopMaterials/CubeTransparent.mat
  87. 291
      Assets/TestScenes/HDTest/Material/HDRenderLoopMaterials/Terrain.mat
  88. 25
      Assets/TestScenes/HDTest/Material/HDRenderLoopMaterials/test details.mat
  89. 45
      Assets/TestScenes/HDTest/Material/HDRenderLoopMaterials/test-transparent.mat
  90. 6
      ProjectSettings/GraphicsSettings.asset
  91. 158
      ProjectSettings/ProjectSettings.asset
  92. 2
      ProjectSettings/ProjectVersion.txt
  93. 26
      Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/FragInputs.hlsl
  94. 64
      Assets/TestScenes/HDTest/GraphicTest/Two Sided/Material/GroundLeaf_DoubleSidedFlip.mat
  95. 25
      Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipelineSetup.asset
  96. 9
      Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipelineSetup.asset.meta
  97. 34
      Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipelineSetup.cs
  98. 12
      Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipelineSetup.cs.meta
  99. 50
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/SampleLayer.hlsl
  100. 9
      Assets/ScriptableRenderLoop/HDRenderPipeline/Material/SampleLayer.hlsl.meta

4
Assets/BasicRenderLoopTutorial/BasicRenderLoop.cs


var settings = new DrawRendererSettings(cull, camera, new ShaderPassName("BasicPass"));
settings.sorting.flags = SortFlags.CommonOpaque;
settings.inputFilter.SetQueuesOpaque();
context.DrawRenderers(ref settings);
context.DrawRenderers(settings);
// Draw skybox
context.DrawSkybox(camera);

settings.inputFilter.SetQueuesTransparent();
context.DrawRenderers(ref settings);
context.DrawRenderers(settings);
context.Submit();
}

4
Assets/Editor/Tests/RenderloopTests/RenderloopTestFixture.cs


var sceneCamera = Camera.main;
var camObject = sceneCamera.gameObject;
GraphicsSettings.renderPipeline = m_Instance;
GraphicsSettings.renderPipelineAsset = m_Instance;
s_Callback = renderCallback;
Transform t = camObject.transform;

SceneView.lastActiveSceneView.LookAtDirect(t.position + t.forward * camDist, t.rotation, size);
sceneCamera.Render();
GraphicsSettings.renderPipeline = null;
GraphicsSettings.renderPipelineAsset = null;
}
}

2
Assets/ScriptableRenderLoop/HDRenderPipeline/Debug/DebugViewMaterial.cs


public enum DebugViewGbuffer
{
Depth = DebugViewVarying.VertexColorAlpha + 1,
BakeDiffuseLighting,
BakeDiffuseLightingWithAlbedoPlusEmissive,
}
}
}

2
Assets/ScriptableRenderLoop/HDRenderPipeline/Debug/DebugViewMaterial.cs.hlsl


// UnityEngine.Experimental.Rendering.HDPipeline.Attributes.DebugViewGbuffer: static fields
//
#define DEBUGVIEWGBUFFER_DEPTH (10)
#define DEBUGVIEWGBUFFER_BAKE_DIFFUSE_LIGHTING (11)
#define DEBUGVIEWGBUFFER_BAKE_DIFFUSE_LIGHTING_WITH_ALBEDO_PLUS_EMISSIVE (11)
#endif

11
Assets/ScriptableRenderLoop/HDRenderPipeline/Debug/Resources/DebugViewMaterialGBuffer.shader


Blend SrcAlpha OneMinusSrcAlpha // We will lerp only the values that are valid
HLSLPROGRAM
#pragma target 5.0
#pragma only_renderers d3d11 ps4// TEMP: unitl we go futher in dev
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#pragma vertex Vert
#pragma fragment Frag

float linearDepth = frac(posInput.depthVS * 0.1);
result = linearDepth.xxx;
}
else if (_DebugViewMaterial == DEBUGVIEWGBUFFER_BAKE_DIFFUSE_LIGHTING)
// Caution: This value is not the same than the builtin data bakeDiffuseLighting. It also include emissive and multiply by the albedo
else if (_DebugViewMaterial == DEBUGVIEWGBUFFER_BAKE_DIFFUSE_LIGHTING_WITH_ALBEDO_PLUS_EMISSIVE)
result = bakeDiffuseLighting;
// TODO: require a remap
// TODO: we should not gamma correct, but easier to debug for now without correct high range value
result = bakeDiffuseLighting; needLinearToSRGB = true;
}
GetBSDFDataDebug(_DebugViewMaterial, bsdfData, result, needLinearToSRGB);

12
Assets/ScriptableRenderLoop/HDRenderPipeline/Debug/Resources/DebugViewTiles.shader


Blend SrcAlpha OneMinusSrcAlpha
HLSLPROGRAM
#pragma target 5.0
#pragma only_renderers d3d11 ps4// TEMP: unitl we go futher in dev
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#define LIGHTLOOP_TILE_PASS 1
#define LIGHTLOOP_TILE_ALL 1
#define LIGHTLOOP_TILE_PASS
#define LIGHTLOOP_TILE_ALL
#pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST

int n = -1;
if(tileCoord.x == 0)
{
n = count;
n = (int)count;
else if(lightListIndex >= 0 && lightListIndex < count)
else if(lightListIndex >= 0 && lightListIndex < (int)count)
{
n = FetchIndex(start, lightListIndex);
}

1
Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipeline.asset


m_Script: {fileID: 11500000, guid: d440c0deec24a2f478b3e9021cb66c29, type: 3}
m_Name: HDRenderPipeline
m_EditorClassIdentifier:
m_setup: {fileID: 11400000, guid: c90ada6c2ed7b4e4b85a303678826111, type: 2}
m_ShadowSettings:
enabled: 1
shadowAtlasWidth: 4096

2
Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipeline.asset.meta


fileFormatVersion: 2
guid: e185fecca3c73cd47a09f1092663ef32
timeCreated: 1483606455
timeCreated: 1484329328
licenseType: Pro
NativeFormatImporter:
userData:

82
Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipeline.cs


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

{
var instance = ScriptableObject.CreateInstance<HDRenderPipeline>();
UnityEditor.AssetDatabase.CreateAsset(instance, k_HDRenderPipelinePath);
instance.m_setup = UnityEditor.AssetDatabase.LoadAssetAtPath<HDRenderPipelineSetup>("Assets/HDRenderPipelineSetup.asset");
}
[UnityEditor.MenuItem("RenderPipeline/UpdateHDLoop")]
static void UpdateHDLoop()
{
var guids = AssetDatabase.FindAssets("t:HDRenderPipeline");
foreach (var guid in guids)
{
string path = AssetDatabase.GUIDToAssetPath(guid);
var loop = AssetDatabase.LoadAssetAtPath<HDRenderPipeline>(path);
loop.m_setup = AssetDatabase.LoadAssetAtPath<HDRenderPipelineSetup>("Assets/HDRenderPipelineSetup.asset");
EditorUtility.SetDirty(loop);
}
}
[UnityEditor.MenuItem("HDRenderPipeline/Add \"Additional Light Data\" (if not present)")]

}
#endif
HDRenderPipeline()
{
m_lightLoop = new TilePass.LightLoop(this);
}
[SerializeField]
private HDRenderPipelineSetup m_setup;
public HDRenderPipelineSetup renderPipelineSetup
{
get { return m_setup; }
}
protected override IRenderPipeline InternalCreatePipeline()
{
return new HDRenderPipelineInstance(this);

// Keep these settings safe to recover when leaving the render pipeline
bool previousLightsUseLinearIntensity;
bool previousLightsUseCCT;
bool previousLightsUseColorTemperature;
BaseLightLoop m_lightLoop = new TilePass.LightLoop();
BaseLightLoop m_lightLoop;
public BaseLightLoop lightLoop
{

#endif
previousLightsUseLinearIntensity = UnityEngine.Rendering.GraphicsSettings.lightsUseLinearIntensity;
previousLightsUseCCT = UnityEngine.Rendering.GraphicsSettings.lightsUseCCT;
previousLightsUseColorTemperature = UnityEngine.Rendering.GraphicsSettings.lightsUseColorTemperature;
UnityEngine.Rendering.GraphicsSettings.lightsUseCCT = true;
UnityEngine.Rendering.GraphicsSettings.lightsUseColorTemperature = true;
m_CameraColorBuffer = Shader.PropertyToID("_CameraColorTexture");
m_CameraDepthBuffer = Shader.PropertyToID("_CameraDepthTexture");

UnityEditor.SupportedRenderingFeatures.active = UnityEditor.SupportedRenderingFeatures.Default;
#endif
UnityEngine.Rendering.GraphicsSettings.lightsUseLinearIntensity = previousLightsUseLinearIntensity;
UnityEngine.Rendering.GraphicsSettings.lightsUseCCT = previousLightsUseCCT;
UnityEngine.Rendering.GraphicsSettings.lightsUseColorTemperature = previousLightsUseColorTemperature;
}
void InitAndClearBuffer(Camera camera, ScriptableRenderContext renderContext)

// Clear GBuffers
using (new Utilities.ProfilingSample("Clear GBuffer", renderContext))
if (!debugParameters.ShouldUseForwardRenderingOnly())
Utilities.SetRenderTarget(renderContext, m_gbufferManager.GetGBuffers(), m_CameraDepthBufferRT, ClearFlag.ClearColor, Color.black);
using (new Utilities.ProfilingSample("Clear GBuffer", renderContext))
{
Utilities.SetRenderTarget(renderContext, m_gbufferManager.GetGBuffers(), m_CameraDepthBufferRT, ClearFlag.ClearColor, Color.black);
}
// END TEMP
}
}

sorting = { flags = SortFlags.CommonOpaque }
};
settings.inputFilter.SetQueuesOpaque();
renderContext.DrawRenderers(ref settings);
renderContext.DrawRenderers(settings);
}
void RenderTransparentRenderList(CullResults cull, Camera camera, ScriptableRenderContext renderContext, string passName, RendererConfiguration rendererConfiguration = 0)

sorting = { flags = SortFlags.CommonTransparent }
};
settings.inputFilter.SetQueuesTransparent();
renderContext.DrawRenderers(ref settings);
renderContext.DrawRenderers(settings);
}
void RenderDepthPrepass(CullResults cull, Camera camera, ScriptableRenderContext renderContext)

Shader.SetGlobalInt("_DebugViewMaterial", (int)debugParameters.debugViewMaterial);
RenderOpaqueRenderList(cull, hdCamera.camera, renderContext, "DebugViewMaterial");
RenderOpaqueRenderList(cull, hdCamera.camera, renderContext, "DebugViewMaterial", Utilities.kRendererConfigurationBakedLighting);
}
// Render GBuffer opaque

// Render forward transparent
{
RenderTransparentRenderList(cull, hdCamera.camera, renderContext, "DebugViewMaterial");
RenderTransparentRenderList(cull, hdCamera.camera, renderContext, "DebugViewMaterial", Utilities.kRendererConfigurationBakedLighting);
}
// Last blit

return ;
}
// Bind material data
m_LitRenderLoop.Bind();
m_lightLoop.RenderDeferredLighting(hdCamera, renderContext, m_CameraColorBuffer);
}

using (new Utilities.ProfilingSample("Forward Pass", renderContext))
{
// Bind material data
m_LitRenderLoop.Bind();
Utilities.SetRenderTarget(renderContext, m_CameraColorBufferRT, m_CameraDepthBufferRT);
m_lightLoop.RenderForward(camera, renderContext, renderOpaque);

RenderOpaqueRenderList(cullResults, camera, renderContext, "Forward");
RenderOpaqueRenderList(cullResults, camera, renderContext, "Forward", Utilities.kRendererConfigurationBakedLighting);
}
else
{

{
using (new Utilities.ProfilingSample("Forward Only Pass", renderContext))
{
// Bind material data
m_LitRenderLoop.Bind();
RenderOpaqueRenderList(cullResults, camera, renderContext, "ForwardOnlyOpaque");
RenderOpaqueRenderList(cullResults, camera, renderContext, "ForwardOnlyOpaque", Utilities.kRendererConfigurationBakedLighting);
}
}

{
// If opaque velocity have been render during GBuffer no need to render it here
if ((ShaderConfig.s_VelocityInGbuffer == 0) || debugParameters.ShouldUseForwardRenderingOnly())
if ((ShaderConfig.s_VelocityInGbuffer == 1) || debugParameters.ShouldUseForwardRenderingOnly())
return ;
int w = camera.pixelWidth;

// TODO: This is the wrong way to handle resize/allocation. We can have several different camera here, mean that the loop on camera will allocate and deallocate
// the below buffer which is bad. Best is to have a set of buffer for each camera that is persistent and reallocate resource if need
// For now consider we have only one camera that go to this code, the main one.
m_SkyManager.Resize(); // TODO: Also a bad naming, here we just want to realloc texture if skyparameters change (usefull for lookdev)
m_SkyManager.Resize(camera.nearClipPlane, camera.farClipPlane); // TODO: Also a bad naming, here we just want to realloc texture if skyparameters change (usefull for lookdev)
if (camera.pixelWidth != m_currentWidth || camera.pixelHeight != m_currentHeight || m_lightLoop.NeedResize())
{

InitAndClearBuffer(camera, renderContext);
// 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();
RenderDepthPrepass(cullResults, camera, renderContext);
// Forward opaque with deferred/cluster tile require that we fill the depth buffer

using (new Utilities.ProfilingSample("Build Light list", renderContext))
{
m_lightLoop.PrepareLightsForGPU(m_ShadowSettings, cullResults, camera, ref shadows);
m_lightLoop.BuildGPULightLists(camera, renderContext, m_CameraDepthBufferRT); // TODO: Use async compute here to run light culling during shadow
PushGlobalParams(hdCamera, renderContext);
m_lightLoop.BuildGPULightLists(camera, renderContext, m_CameraDepthBufferRT); // TODO: Use async compute here to run light culling during shadow
PushGlobalParams(hdCamera, renderContext);
// Caution: We require sun light here as some sky use the sun light to render, mean UpdateSkyEnvironment
// must be call after BuildGPULightLists.

5
Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/Forward.hlsl


// Must match name in GetKeyword() method of forward lighting architecture .cs file
// #pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS -> can't use a pragma from include... (for now)
// #pragma multi_compile SHADOWFILTERING_FIXED_SIZE_PCF -> can't use a pragma from include... (for now)
// No USE_FPTL_LIGHTLIST as we are in forward and this use the cluster path (but cluster path can use the tile light list for opaque)
#define USE_CLUSTERED_LIGHTLIST
#define LIGHTLOOP_TILE_ALL

5
Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/Resources/Deferred.shader


Blend[_SrcBlend][_DstBlend]
HLSLPROGRAM
#pragma target 5.0
#pragma only_renderers d3d11 ps4// TEMP: unitl we go futher in dev
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#pragma vertex Vert
#pragma fragment Frag

//#pragma multi_compile SHADOWFILTERING_FIXED_SIZE_PCF
// TODO: Workflow problem here, I would like to only generate variant for the LIGHTLOOP_TILE_PASS case, not the LIGHTLOOP_SINGLE_PASS case. This must be on lightloop side and include here.... (Can we codition
#pragma multi_compile LIGHTLOOP_TILE_DIRECT LIGHTLOOP_TILE_INDIRECT LIGHTLOOP_TILE_ALL

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


float GetScaleFromBase(float base)
{
const float C = (float)(1 << g_iLog2NumClusters);
const float geomSeries = (1.0 - pow(abs(base), C)) / (1 - base); // geometric series: sum_k=0^{C-1} base^k
const float geomSeries = (1.0 - PositivePow(base, C)) / (1 - base); // geometric series: sum_k=0^{C-1} base^k
return geomSeries / (g_fFarPlane - g_fNearPlane);
}

if (logBasePerTile)
userscale = GetScaleFromBase(suggestedBase);
float dist = (pow(suggestedBase, (float)k) - 1.0) / (userscale * (suggestedBase - 1.0f));
float dist = (PositivePow(suggestedBase, (float)k) - 1.0) / (userscale * (suggestedBase - 1.0f));
res = dist + g_fNearPlane;
#if USE_LEFTHAND_CAMERASPACE

9
Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/TilePass/Resources/lightlistbuild-bigtile.compute


lightOffs = 0;
GroupMemoryBarrierWithGroupSync();
int i;
for(i=t; i<iNrCoarseLights; i+=NR_THREADS) if(lightsListLDS[i]<g_iNrVisibLights) InterlockedAdd(lightOffs, 1);
for(i=t; i<iNrCoarseLights; i+=NR_THREADS) if((int)lightsListLDS[i]<g_iNrVisibLights) InterlockedAdd(lightOffs, 1);
GroupMemoryBarrierWithGroupSync();
iNrCoarseLights = lightOffs;

int i=iSwizzle + (2*(iSection&0x2)); // offset by 4 at section 2
vP0 = GetTileVertex(uint2(viTilLL.x, viTilUR.y), uint2(viTilUR.x, viTilLL.y), i, fTileFarPlane);
vE0 = iSection==0 ? vP0 : (((iSwizzle&0x2)==0 ? 1.0f : (-1.0f))*((iSwizzle&0x1)==(iSwizzle>>1) ? float3(1,0,0) : float3(0,1,0)));
vE0 = iSection == 0 ? vP0 : (((iSwizzle & 0x2) == 0 ? 1.0f : (-1.0f)) * ((int)(iSwizzle & 0x1) == (iSwizzle >> 1) ? float3(1, 0, 0) : float3(0, 1, 0)));
}
void CullByExactEdgeTests(uint threadID, int iNrCoarseLights, uint2 viTilLL, uint2 viTilUR)

for(int l=0; l<iNrCoarseLights; l++)
{
const uint idxCoarse = lightsListLDS[l];
[branch]if (idxCoarse<(uint)g_iNrVisibLights && _LightVolumeData[idxCoarse].lightVolume != LIGHTVOLUMETYPE_SPHERE) // don't bother doing edge tests for sphere lights since these have camera aligned bboxes.
bool canEnter = idxCoarse<(uint)g_iNrVisibLights;
if(canEnter) canEnter = _LightVolumeData[idxCoarse].lightVolume != LIGHTVOLUMETYPE_SPHERE; // don't bother doing edge tests for sphere lights since these have camera aligned bboxes.
[branch]if(canEnter)
{
SFiniteLightBound lgtDat = g_data[idxCoarse];

2
Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/TilePass/Resources/lightlistbuild-clustered.compute


groupshared uint lightOffs;
#ifdef ENABLE_DEPTH_TEXTURE_BACKPLANE
groupshared int ldsZMax;
groupshared uint ldsZMax;
#endif
#ifdef EXACT_EDGE_TESTS

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


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

public static float VIEWPORT_SCALE_Z = 1.0f;
// enable unity's original left-hand shader camera space (right-hand internally in unity).
public static int USE_LEFTHAND_CAMERASPACE = 0;
public static int USE_LEFTHAND_CAMERASPACE = 1;
// flags
public static int IS_CIRCULAR_SPOT_SHAPE = 1;

int m_areaLightCount = 0;
int m_lightCount = 0;
static ComputeShader buildScreenAABBShader = null;
static ComputeShader buildPerTileLightListShader = null; // FPTL
static ComputeShader buildPerBigTileLightListShader = null;
static ComputeShader buildPerVoxelLightListShader = null; // clustered
static ComputeShader shadeOpaqueShader = null;
private ComputeShader buildScreenAABBShader { get { return m_Parent.renderPipelineSetup.buildScreenAABBShader; } }
private ComputeShader buildPerTileLightListShader { get { return m_Parent.renderPipelineSetup.buildPerTileLightListShader; } }
private ComputeShader buildPerBigTileLightListShader { get { return m_Parent.renderPipelineSetup.buildPerBigTileLightListShader; } }
private ComputeShader buildPerVoxelLightListShader { get { return m_Parent.renderPipelineSetup.buildPerVoxelLightListShader; } }
private ComputeShader shadeOpaqueShader { get { return m_Parent.renderPipelineSetup.shadeOpaqueShader; } }
static int s_GenAABBKernel;
static int s_GenListPerTileKernel;

static int s_GenListPerBigTileKernel;
public bool enableDrawLightBoundsDebug = false;
public bool disableTileAndCluster = true; // For debug / test
public bool disableTileAndCluster = false; // For debug / test
public bool disableDeferredShadingInCompute = true;
public bool enableSplitLightEvaluation = true;
public bool enableComputeLightEvaluation = false;

public bool enableClustered = false;
public bool disableFptlWhenClustered = true; // still useful on opaques. Should be false by default to force tile on opaque.
public bool enableBigTilePrepass = false;
public bool enableClustered = true;
public bool disableFptlWhenClustered = false; // still useful on opaques. Should be false by default to force tile on opaque.
public bool enableBigTilePrepass = true;
const bool k_UseDepthBuffer = true; // only has an impact when EnableClustered is true (requires a depth-prepass)
const bool k_UseAsyncCompute = true; // should not use on mobile

static ComputeBuffer s_GlobalLightListAtomic = null;
// clustered light list specific buffers and data end
private static GameObject s_DefaultAdditionalLightDataGameObject;
private static AdditionalLightData s_DefaultAdditionalLightData;
bool usingFptl
{
get

}
}
private static AdditionalLightData DefaultAdditionalLightData
{
get
{
if (s_DefaultAdditionalLightDataGameObject == null)
{
s_DefaultAdditionalLightDataGameObject = new GameObject("Default Light Data");
s_DefaultAdditionalLightDataGameObject.hideFlags = HideFlags.HideAndDontSave;
s_DefaultAdditionalLightData = s_DefaultAdditionalLightDataGameObject.AddComponent<AdditionalLightData>();
}
return s_DefaultAdditionalLightData;
}
}
Material m_DeferredDirectMaterial = null;
Material m_DeferredIndirectMaterial = null;
Material m_DeferredAllMaterial = null;

const int k_TileSize = 16;
private readonly HDRenderPipeline m_Parent;
int GetNumTileX(Camera camera)
{

return (camera.pixelHeight + (k_TileSize - 1)) / k_TileSize;
}
public LightLoop(HDRenderPipeline hdRenderPipeline)
{
m_Parent = hdRenderPipeline;
}
public override void Build(TextureSettings textureSettings)
{
m_lightList = new LightList();

m_CubeCookieTexArray.AllocTextureArray(4, textureSettings.pointCookieSize, TextureFormat.RGBA32, true);
m_CubeReflTexArray = new TextureCacheCubemap();
m_CubeReflTexArray.AllocTextureArray(32, textureSettings.reflectionCubemapSize, TextureFormat.BC6H, true);
buildScreenAABBShader = Resources.Load<ComputeShader>("scrbound");
buildPerTileLightListShader = Resources.Load<ComputeShader>("lightlistbuild");
buildPerBigTileLightListShader = Resources.Load<ComputeShader>("lightlistbuild-bigtile");
buildPerVoxelLightListShader = Resources.Load<ComputeShader>("lightlistbuild-clustered");
shadeOpaqueShader = Resources.Load<ComputeShader>("shadeopaque");
s_GenAABBKernel = buildScreenAABBShader.FindKernel("ScreenBoundsAABB");
s_GenListPerTileKernel = buildPerTileLightListShader.FindKernel(enableBigTilePrepass ? "TileLightListGen_SrcBigTile" : "TileLightListGen");

Utilities.Destroy(m_DebugViewTilesMaterial);
Utilities.Destroy(m_SingleDeferredMaterial);
GameObject.DestroyImmediate(s_DefaultAdditionalLightDataGameObject);
s_DefaultAdditionalLightDataGameObject = null;
s_DefaultAdditionalLightData = null;
}
public override void NewFrame()

int punctualLightcount = 0;
int areaLightCount = 0;
var sortKeys = new uint[Math.Min(cullResults.visibleLights.Length, k_MaxLightsOnScreen)];
int lightCount = Math.Min(cullResults.visibleLights.Length, k_MaxLightsOnScreen);
var sortKeys = new uint[lightCount];
for (int lightIndex = 0, numLights = cullResults.visibleLights.Length; lightIndex < numLights; ++lightIndex)
for (int lightIndex = 0, numLights = cullResults.visibleLights.Length; (lightIndex < numLights) && (sortCount < lightCount); ++lightIndex)
{
var light = cullResults.visibleLights[lightIndex];

if (additionalData == null)
{
Debug.LogWarning("Light entity detected without additional data, will not be taken into account " + light.light.name);
continue;
// PreRenderLight is used to display preview
if (light.light.name != "PreRenderLight")
{
Debug.LogWarningFormat("Light entity {0} has no additional data, will be rendered using default values.", light.light.name);
}
additionalData = DefaultAdditionalLightData;
}
LightCategory lightCategory = LightCategory.Count;

int lightIndex = (int)(sortKey & 0xFFFF);
var light = cullResults.visibleLights[lightIndex];
var additionalData = light.light.GetComponent<AdditionalLightData>();
var additionalData = light.light.GetComponent<AdditionalLightData>() ?? DefaultAdditionalLightData;
// Directional rendering side, it is separated as it is always visible so no volume to handle here
if (gpuLightType == GPULightType.Directional)

// Redo everything but this time with envLights
int envLightCount = 0;
sortKeys = new uint[Math.Min(cullResults.visibleReflectionProbes.Length, k_MaxEnvLightsOnScreen)];
int probeCount = Math.Min(cullResults.visibleReflectionProbes.Length, k_MaxEnvLightsOnScreen);
sortKeys = new uint[probeCount];
for (int probeIndex = 0, numProbes = cullResults.visibleReflectionProbes.Length; probeIndex < numProbes; probeIndex++)
for (int probeIndex = 0, numProbes = cullResults.visibleReflectionProbes.Length; (probeIndex < numProbes) && (sortCount < probeCount); probeIndex++)
if (envLightCount >= k_MaxEnvLightsOnScreen)
// probe.texture can be null when we are adding a reflection probe in the editor
if (probe.texture == null || envLightCount >= k_MaxEnvLightsOnScreen)
continue;
// TODO: Support LightVolumeType.Sphere, currently in UI there is no way to specify a sphere influence volume

for (int n = 0; n < numVectors; n++)
{
for (int i = 0; i < 4; i++)
{
{
data[4 * n + i] = values[n][i];
}
}

#if UNITY_EDITOR
private Vector2 m_mousePosition = Vector2.zero;
private void OnSceneGUI(UnityEditor.SceneView sceneview)
{
m_mousePosition = Event.current.mousePosition;

SetGlobalBuffer("g_vLightListGlobal", bUseClusteredForDeferred ? s_PerVoxelLightLists : s_LightList); // opaques list (unless MSAA possibly)
SetGlobalPropertyRedirect(shadeOpaqueShader, usingFptl ? s_shadeOpaqueFptlKernel : s_shadeOpaqueClusteredKernel, cmd);
SetGlobalBuffer("g_vLightListGlobal", bUseClusteredForDeferred ? s_PerVoxelLightLists : s_LightList); // opaques list (unless MSAA possibly)
// In case of bUseClusteredForDeferred disable toggle option since we're using m_perVoxelLightLists as opposed to lightList
if (bUseClusteredForDeferred)

if (disableTileAndCluster)
{
// This is a debug brute force renderer to debug tile/cluster which render all the lights
Utilities.SetupMaterialHDCamera(hdCamera, m_SingleDeferredMaterial);
m_SingleDeferredMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
m_SingleDeferredMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);

public override void RenderForward(Camera camera, ScriptableRenderContext renderContext, bool renderOpaque)
{
// Note: if we use render opaque with deferred tiling we need to render a opque depth pass for these opaque objects
// Note: if we use render opaque with deferred tiling we need to render a opaque depth pass for these opaque objects
bool useFptl = renderOpaque && usingFptl;
var cmd = new CommandBuffer();

else
{
cmd.name = useFptl ? "Forward Tiled pass" : "Forward Clustered pass";
// say that we want to use tile of single loop
cmd.SetGlobalFloat("g_isOpaquesOnlyEnabled", useFptl ? 1 : 0); // leaving this as a dynamic toggle for now for forward opaques to keep shader variants down.
cmd.SetGlobalFloat("_UseTileLightList", useFptl ? 1 : 0); // leaving this as a dynamic toggle for now for forward opaques to keep shader variants down.
cmd.SetGlobalBuffer("g_vLightListGlobal", useFptl ? s_LightList : s_PerVoxelLightLists);
}

2
Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/TilePass/TilePass.cs.hlsl


#define MAX_NR_LIGHTS_PER_CAMERA (1024)
#define MAX_NR_BIGTILE_LIGHTS_PLUSONE (512)
#define VIEWPORT_SCALE_Z (1)
#define USE_LEFTHAND_CAMERASPACE (0)
#define USE_LEFTHAND_CAMERASPACE (1)
#define IS_CIRCULAR_SPOT_SHAPE (1)
#define HAS_COOKIE_TEXTURE (2)
#define IS_BOX_PROJECTED (4)

12
Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/TilePass/TilePass.hlsl


SAMPLER2D_SHADOW(samplerg_tShadowBuffer);
// Use texture array for IES
TEXTURE2D_ARRAY(_IESArray);
SAMPLER2D(sampler_IESArray);
//TEXTURE2D_ARRAY(_IESArray);
//SAMPLER2D(sampler_IESArray);
// Used by directional and spot lights
TEXTURE2D_ARRAY(_CookieTextures);

// ----------------------------------------------------------------------------
// sphericalTexCoord is theta and phi spherical coordinate
float4 SampleIES(LightLoopContext lightLoopContext, int index, float2 sphericalTexCoord, float lod)
{
return SAMPLE_TEXTURE2D_ARRAY_LOD(_IESArray, sampler_IESArray, sphericalTexCoord, index, 0);
}
//float4 SampleIES(LightLoopContext lightLoopContext, int index, float2 sphericalTexCoord, float lod)
//{
// return SAMPLE_TEXTURE2D_ARRAY_LOD(_IESArray, sampler_IESArray, sphericalTexCoord, index, 0);
//}
//-----------------------------------------------------------------------------
// Reflection proble / Sky sampling function

2
Assets/ScriptableRenderLoop/HDRenderPipeline/Lighting/TilePass/TilePassLoop.hlsl


return FetchIndexTile(tileOffset, lightIndex);
}
#else
#elif defined(USE_CLUSTERED_LIGHTLIST)
#include "ClusteredUtils.hlsl"

7
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Builtin/BuiltinData.hlsl


// Note: These parameters can be store in GBuffer if the writer wants
//-----------------------------------------------------------------------------
#include "BuiltinData.cs.hlsl"
//TODO: return this original relative path include after fixing a bug in Unity side
//#include "BuiltinData.cs.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Builtin/BuiltinData.cs.hlsl"
//-----------------------------------------------------------------------------
// common Encode/Decode functions

break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_BAKE_DIFFUSE_LIGHTING:
// TODO: require a remap
result = builtinData.bakeDiffuseLighting;
// TODO: we should not gamma correct, but easier to debug for now without correct high range value
result = builtinData.bakeDiffuseLighting; needLinearToSRGB = true;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_COLOR:
// emissiveColor is premultiply by emissive intensity

251
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/LayeredLit/Editor/LayeredLitUI.cs


Triplanar,
}
public enum VertexColorMode
{
None,
Multiply,
Add
}
new GUIContent("Base Layer"),
new GUIContent("Main layer"),
public readonly GUIStyle[] layerLabelColors =
{

public readonly GUIContent syncButtonText = new GUIContent("Re-Synchronize Layers", "Re-synchronize all layers's properties with the referenced Material");
public readonly GUIContent layersText = new GUIContent("Layers");
public readonly GUIContent emissiveText = new GUIContent("Emissive");
public readonly GUIContent layerMapMaskText = new GUIContent("Layer Mask", "Layer mask (multiplied by vertex color if enabled)");
public readonly GUIContent layerMapVertexColorText = new GUIContent("Use Vertex Color", "If no layer mask is set, vertex color values between 0 and 1.0 are used as final mask.\nIf a layer mask is set, vertex color values are remapped between -1 and 1 and added to the mask (neutral at 0.5 vertex color).");
public readonly GUIContent vertexColorHeightMultiplierText = new GUIContent("Vertex Height Scale", "Scale applied to the vertex color height.");
public readonly GUIContent layerMapMaskText = new GUIContent("Layer Mask", "Layer mask");
public readonly GUIContent vertexColorModeText = new GUIContent("Vertex Color Mode", "Mode multiply: vertex color is multiply with the mask. Mode additive: vertex color values are remapped between -1 and 1 and added to the mask (neutral at 0.5 vertex color).");
public readonly GUIContent layerTilingText = new GUIContent("Tiling", "Tiling factor applied to UVSet");
public readonly GUIContent mainLayerInfluenceText = new GUIContent("Main layer influence", "Main layer influence.");
public readonly GUIContent densityOpacityInfluenceText = new GUIContent("Density / Opacity", "Density / Opacity");
public readonly GUIContent heightOffsetText = new GUIContent("Height Offset", "Height offset from the previous layer.");
public readonly GUIContent inheritBaseLayerText = new GUIContent("Inherit Base Layer Normal", "Inherit the normal from the base layer.");
public readonly GUIContent useDensityModeModeText = new GUIContent("Use Density Mode", "Enable density mode");
public readonly GUIContent useMainLayerInfluenceModeText = new GUIContent("Main Layer Influence", "Switch between regular layers mode and base/layers mode");
public readonly GUIContent blendSizeText = new GUIContent("Blend Size", "Thickness over which the layer will be blended with the previous one.");
public readonly GUIContent heightControlText = new GUIContent("Height control");
public readonly GUIContent heightCenterOffsetText = new GUIContent("Height Center Offset", "Offset applied to the center of the height of the layer.");
public readonly GUIContent blendUsingHeight = new GUIContent("Blend Using Height", "Blend Layers using height.");
public readonly GUIContent inheritBaseColorThresholdText = new GUIContent("Threshold", "Inherit the base color from the base layer.");
public readonly GUIContent minimumOpacityText = new GUIContent("Minimum Opacity", "Minimum Opacity.");
public readonly GUIContent opacityAsDensityText = new GUIContent("Use Opacity as Density", "Use Opacity as Density.");
public readonly GUIContent inheritBaseNormalText = new GUIContent("Normal influence", "Inherit the normal from the base layer.");
public readonly GUIContent inheritBaseHeightText = new GUIContent("Heightmap influence", "Inherit the height from the base layer.");
public readonly GUIContent inheritBaseColorText = new GUIContent("BaseColor influence", "Inherit the base color from the base layer.");
layerLabelColors[0].normal.textColor = Color.white;
layerLabelColors[1].normal.textColor = Color.red;
layerLabelColors[2].normal.textColor = Color.green;
layerLabelColors[3].normal.textColor = Color.blue;

MaterialProperty layerMaskMap = null;
const string kLayerMaskMap = "_LayerMaskMap";
MaterialProperty layerMaskVertexColor = null;
const string kLayerMaskVertexColor = "_LayerMaskVertexColor";
MaterialProperty vertexColorMode = null;
const string kVertexColorMode = "_VertexColorMode";
MaterialProperty layerCount = null;
const string kLayerCount = "_LayerCount";
MaterialProperty[] layerTexWorldScale = new MaterialProperty[kMaxLayerCount];

MaterialProperty[] layerUVDetail = new MaterialProperty[kMaxLayerCount];
MaterialProperty[] layerUVDetailsMappingMask = new MaterialProperty[kMaxLayerCount];
const string kLayerTiling = "_LayerTiling";
MaterialProperty[] layerTiling = new MaterialProperty[kMaxLayerCount];
const string kkUseMainLayerInfluence = "_UseMainLayerInfluence";
MaterialProperty useMainLayerInfluence = null;
const string kHeightOffset = "_HeightOffset";
MaterialProperty[] heightOffset = new MaterialProperty[kMaxLayerCount-1];
const string kInheritBaseLayer = "_InheritBaseLayer";
MaterialProperty[] inheritBaseLayer = new MaterialProperty[kMaxLayerCount - 1];
const string kUseDensityMode = "_UseDensityMode";
MaterialProperty useDensityMode = null;
const string kOpacityAsDensity = "_OpacityAsDensity";
MaterialProperty[] opacityAsDensity = new MaterialProperty[kMaxLayerCount];
const string kMinimumOpacity = "_MinimumOpacity";
MaterialProperty[] minimumOpacity = new MaterialProperty[kMaxLayerCount];
MaterialProperty[] heightFactor = new MaterialProperty[kMaxLayerCount-1];
const string kBlendSize = "_BlendSize";
MaterialProperty[] blendSize = new MaterialProperty[kMaxLayerCount-1];
const string kVertexColorHeightFactor = "_VertexColorHeightFactor";
MaterialProperty vertexColorHeightFactor = null;
MaterialProperty[] heightFactor = new MaterialProperty[kMaxLayerCount];
const string kHeightCenterOffset = "_HeightCenterOffset";
MaterialProperty[] heightCenterOffset = new MaterialProperty[kMaxLayerCount];
const string kBlendUsingHeight = "_BlendUsingHeight";
MaterialProperty[] blendUsingHeight = new MaterialProperty[kMaxLayerCount - 1];
// influence
const string kInheritBaseNormal = "_InheritBaseNormal";
MaterialProperty[] inheritBaseNormal = new MaterialProperty[kMaxLayerCount - 1];
const string kInheritBaseHeight = "_InheritBaseHeight";
MaterialProperty[] inheritBaseHeight = new MaterialProperty[kMaxLayerCount - 1];
const string kInheritBaseColor = "_InheritBaseColor";
MaterialProperty[] inheritBaseColor = new MaterialProperty[kMaxLayerCount - 1];
const string kInheritBaseColorThreshold = "_InheritBaseColorThreshold";
MaterialProperty[] inheritBaseColorThreshold = new MaterialProperty[kMaxLayerCount - 1];
MaterialProperty layerEmissiveColor = null;
MaterialProperty layerEmissiveColorMap = null;

FindMaterialOptionProperties(props);
layerMaskMap = FindProperty(kLayerMaskMap, props);
layerMaskVertexColor = FindProperty(kLayerMaskVertexColor, props);
vertexColorHeightFactor = FindProperty(kVertexColorHeightFactor, props);
vertexColorMode = FindProperty(kVertexColorMode, props);
useMainLayerInfluence = FindProperty(kkUseMainLayerInfluence, props);
useDensityMode = FindProperty(kUseDensityMode, props);
for (int i = 0; i < kMaxLayerCount; ++i)
{
layerTexWorldScale[i] = FindProperty(string.Format("{0}{1}", kTexWorldScale, i), props);

layerUVDetail[i] = FindProperty(string.Format("{0}{1}", kUVDetail, i), props);
layerUVDetailsMappingMask[i] = FindProperty(string.Format("{0}{1}", kUVDetailsMappingMask, i), props);
layerTiling[i] = FindProperty(string.Format("{0}{1}", kLayerTiling, i), props);
minimumOpacity[i] = FindProperty(string.Format("{0}{1}", kMinimumOpacity, i), props);
opacityAsDensity[i] = FindProperty(string.Format("{0}{1}", kOpacityAsDensity, i), props);
heightFactor[i] = FindProperty(string.Format("{0}{1}", kHeightFactor, i), props);
heightCenterOffset[i] = FindProperty(string.Format("{0}{1}", kHeightCenterOffset, i), props);
inheritBaseLayer[i - 1] = FindProperty(string.Format("{0}{1}", kInheritBaseLayer, i), props);
heightOffset[i-1] = FindProperty(string.Format("{0}{1}", kHeightOffset, i), props);
heightFactor[i-1] = FindProperty(string.Format("{0}{1}", kHeightFactor, i), props);
blendSize[i-1] = FindProperty(string.Format("{0}{1}", kBlendSize, i), props);
blendUsingHeight[i - 1] = FindProperty(string.Format("{0}{1}", kBlendUsingHeight, i), props);
inheritBaseNormal[i - 1] = FindProperty(string.Format("{0}{1}", kInheritBaseNormal, i), props);
inheritBaseHeight[i - 1] = FindProperty(string.Format("{0}{1}", kInheritBaseHeight, i), props);
inheritBaseColor[i - 1] = FindProperty(string.Format("{0}{1}", kInheritBaseColor, i), props);
inheritBaseColorThreshold[i - 1] = FindProperty(string.Format("{0}{1}", kInheritBaseColorThreshold, i), props);
}
}

Material material = m_MaterialEditor.target as Material;
bool mainLayerInfluenceEnable = useMainLayerInfluence.floatValue > 0.0f;
EditorGUILayout.LabelField(styles.layerLabels[layerIndex], styles.layerLabelColors[layerIndex]);
EditorGUI.indentLevel++;

SynchronizeLayerProperties(material, m_MaterialLayers, layerIndex);
result = true;
}
if (((LayerUVBaseMapping)layerUVBase[layerIndex].floatValue == LayerUVBaseMapping.Planar) ||
((LayerUVBaseMapping)layerUVBase[layerIndex].floatValue == LayerUVBaseMapping.Triplanar))
{

}
else
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(layerTiling[layerIndex], styles.layerTilingText);
EditorGUI.indentLevel--;
EditorGUI.BeginChangeCheck();
m_MaterialEditor.ShaderProperty(layerUVDetail[layerIndex], styles.UVDetailText);
if (EditorGUI.EndChangeCheck())

}
}
if(layerIndex > 0)
bool useDensityModeEnable = useDensityMode.floatValue != 0.0f;
if (useDensityModeEnable)
{
EditorGUILayout.LabelField(styles.densityOpacityInfluenceText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(opacityAsDensity[layerIndex], styles.opacityAsDensityText);
m_MaterialEditor.ShaderProperty(minimumOpacity[layerIndex], styles.minimumOpacityText);
EditorGUI.indentLevel--;
}
EditorGUILayout.LabelField(styles.heightControlText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(heightFactor[layerIndex], styles.heightFactorText);
m_MaterialEditor.ShaderProperty(heightCenterOffset[layerIndex], styles.heightCenterOffsetText);
EditorGUI.indentLevel--;
// influence
if (layerIndex > 0)
if (!useHeightBasedBlend.hasMixedValue && useHeightBasedBlend.floatValue != 0.0f)
int paramIndex = layerIndex - 1;
bool heightBasedBlendEnable = useHeightBasedBlend.floatValue != 0.0f;
if (heightBasedBlendEnable)
int heightParamIndex = layerIndex - 1;
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(blendUsingHeight[paramIndex], styles.blendUsingHeight);
EditorGUI.indentLevel--;
}
m_MaterialEditor.ShaderProperty(inheritBaseLayer[heightParamIndex], styles.inheritBaseLayerText);
m_MaterialEditor.ShaderProperty(heightOffset[heightParamIndex], styles.heightOffsetText);
m_MaterialEditor.ShaderProperty(heightFactor[heightParamIndex], styles.heightFactorText);
m_MaterialEditor.ShaderProperty(blendSize[heightParamIndex], styles.blendSizeText);
if (mainLayerInfluenceEnable)
{
EditorGUILayout.LabelField(styles.mainLayerInfluenceText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(inheritBaseColor[paramIndex], styles.inheritBaseColorText);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(inheritBaseColorThreshold[paramIndex], styles.inheritBaseColorThresholdText);
EditorGUI.indentLevel--;
m_MaterialEditor.ShaderProperty(inheritBaseNormal[paramIndex], styles.inheritBaseNormalText);
// Main height influence is only available if the shader use the heightmap for displacement (per vertex or per level)
// We always display it as it can be tricky to know when per pixel displacement is enabled or not
m_MaterialEditor.ShaderProperty(inheritBaseHeight[paramIndex], styles.inheritBaseHeightText);
EditorGUI.indentLevel--;
}
}

m_MaterialEditor.TexturePropertySingleLine(styles.layerMapMaskText, layerMaskMap);
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = useHeightBasedBlend.hasMixedValue;
bool enabled = EditorGUILayout.Toggle(styles.useHeightBasedBlendText, useHeightBasedBlend.floatValue > 0.0f);
EditorGUI.showMixedValue = useMainLayerInfluence.hasMixedValue;
bool mainLayerModeInfluenceEnable = EditorGUILayout.Toggle(styles.useMainLayerInfluenceModeText, useMainLayerInfluence.floatValue > 0.0f);
useHeightBasedBlend.floatValue = enabled ? 1.0f : 0.0f;
useMainLayerInfluence.floatValue = mainLayerModeInfluenceEnable ? 1.0f : 0.0f;
if (enabled)
m_MaterialEditor.ShaderProperty(vertexColorMode, styles.vertexColorModeText);
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = useDensityMode.hasMixedValue;
bool useDensityModeEnable = EditorGUILayout.Toggle(styles.useDensityModeModeText, useDensityMode.floatValue > 0.0f);
if (EditorGUI.EndChangeCheck())
m_MaterialEditor.ShaderProperty(vertexColorHeightFactor, styles.vertexColorHeightMultiplierText);
useDensityMode.floatValue = useDensityModeEnable ? 1.0f : 0.0f;
else
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = useHeightBasedBlend.hasMixedValue;
bool enabled = EditorGUILayout.Toggle(styles.useHeightBasedBlendText, useHeightBasedBlend.floatValue > 0.0f);
if (EditorGUI.EndChangeCheck())
m_MaterialEditor.ShaderProperty(layerMaskVertexColor, styles.layerMapVertexColorText);
useHeightBasedBlend.floatValue = enabled ? 1.0f : 0.0f;
EditorGUILayout.Space();

}
SetKeyword(material, "_EMISSIVE_COLOR_MAP", material.GetTexture(kEmissiveColorMap));
bool useHeightBasedBlend = material.GetFloat(kUseHeightBasedBlend) != 0.0f;
if(useHeightBasedBlend)
SetKeyword(material, "_MAIN_LAYER_INFLUENCE_MODE", material.GetFloat(kkUseMainLayerInfluence) != 0.0f);
VertexColorMode VCMode = (VertexColorMode)vertexColorMode.floatValue;
if (VCMode == VertexColorMode.Multiply)
SetKeyword(material, "_LAYER_MASK_VERTEX_COLOR_MUL", true);
}
else if (VCMode == VertexColorMode.Add)
{
SetKeyword(material, "_HEIGHT_BASED_BLEND", true);
SetKeyword(material, "_LAYER_MASK_VERTEX_COLOR_ADD", true);
if (material.GetTexture(kLayerMaskMap) != null)
{
SetKeyword(material, "_LAYER_MASK_VERTEX_COLOR_ADD", material.GetFloat(kLayerMaskVertexColor) != 0.0f);
SetKeyword(material, "_LAYER_MASK_VERTEX_COLOR_MUL", false);
}
else
{
SetKeyword(material, "_LAYER_MASK_VERTEX_COLOR_MUL", material.GetFloat(kLayerMaskVertexColor) != 0.0f);
SetKeyword(material, "_LAYER_MASK_VERTEX_COLOR_ADD", false);
}
SetKeyword(material, "_HEIGHT_BASED_BLEND", false);
SetKeyword(material, "_LAYER_MASK_VERTEX_COLOR_MUL", false);
SetKeyword(material, "_LAYER_MASK_VERTEX_COLOR_ADD", false);
bool useHeightBasedBlend = material.GetFloat(kUseHeightBasedBlend) != 0.0f;
SetKeyword(material, "_HEIGHT_BASED_BLEND", useHeightBasedBlend);
bool useDensityModeEnable = material.GetFloat(kUseDensityMode) != 0.0f;
SetKeyword(material, "_DENSITY_MODE", useDensityModeEnable);
bool UV2orUV3needed = false;
bool needUV3 = false;
bool needUV2 = false;
if (
((UVDetailMapping)material.GetFloat(uvDetail) == UVDetailMapping.UV2) ||
((LayerUVBaseMapping)material.GetFloat(uvBase) == LayerUVBaseMapping.UV2) ||
((UVDetailMapping)material.GetFloat(uvDetail) == UVDetailMapping.UV3) ||
((LayerUVBaseMapping)material.GetFloat(uvBase) == LayerUVBaseMapping.UV3)
)
if ( ((UVDetailMapping)material.GetFloat(uvDetail) == UVDetailMapping.UV2) ||
((LayerUVBaseMapping)material.GetFloat(uvBase) == LayerUVBaseMapping.UV2) )
UV2orUV3needed = true;
break;
needUV2 = true;
}
if ( ((UVDetailMapping)material.GetFloat(uvDetail) == UVDetailMapping.UV3) ||
((LayerUVBaseMapping)material.GetFloat(uvBase) == LayerUVBaseMapping.UV3) )
{
needUV3 = true;
break; // If we find it UV3 let's early out
SetKeyword(material, "_REQUIRE_UV2_OR_UV3", UV2orUV3needed);
if (needUV3)
{
material.DisableKeyword("_REQUIRE_UV2");
material.EnableKeyword("_REQUIRE_UV3");
}
else if (needUV2)
{
material.EnableKeyword("_REQUIRE_UV2");
material.DisableKeyword("_REQUIRE_UV3");
}
else
{
material.DisableKeyword("_REQUIRE_UV2");
material.DisableKeyword("_REQUIRE_UV3");
}
}
void SetupLayersKeywords(Material material)

98
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader


_DetailAOScale2("_DetailAOScale2", Range(-2.0, 2.0)) = 1
_DetailAOScale3("_DetailAOScale3", Range(-2.0, 2.0)) = 1
// Specific to planar mapping
_TexWorldScale0("TexWorldScale0", Float) = 1.0
_TexWorldScale1("TexWorldScale1", Float) = 1.0
_TexWorldScale2("TexWorldScale2", Float) = 1.0
_TexWorldScale3("TexWorldScale3", Float) = 1.0
[ToggleOff] _LayerMaskVertexColor("Use Vertex Color Mask", Float) = 0.0
// Layer blending options V2
[ToggleOff] _UseDensityMode("Use Density mode", Float) = 0.0
[ToggleOff] _UseMainLayerInfluence("UseMainLayerInfluence", Float) = 0.0
_HeightOffset1("_HeightOffset1", Range(-0.3, 0.3)) = 0.0
_HeightOffset2("_HeightOffset2", Range(-0.3, 0.3)) = 0.0
_HeightOffset3("_HeightOffset3", Range(-0.3, 0.3)) = 0.0
_HeightFactor0("_HeightFactor0", Float) = 1
_HeightFactor1("_HeightFactor1", Float) = 1
_HeightFactor2("_HeightFactor2", Float) = 1
_HeightFactor3("_HeightFactor3", Float) = 1
_HeightCenterOffset0("_HeightCenterOffset0", Float) = 0.0
_HeightCenterOffset1("_HeightCenterOffset1", Float) = 0.0
_HeightCenterOffset2("_HeightCenterOffset2", Float) = 0.0
_HeightCenterOffset3("_HeightCenterOffset3", Float) = 0.0
_BlendUsingHeight1("_BlendUsingHeight1", Float) = 0.0
_BlendUsingHeight2("_BlendUsingHeight2", Float) = 0.0
_BlendUsingHeight3("_BlendUsingHeight3", Float) = 0.0
_HeightFactor1("_HeightFactor1", Range(0, 5)) = 1
_HeightFactor2("_HeightFactor2", Range(0, 5)) = 1
_HeightFactor3("_HeightFactor3", Range(0, 5)) = 1
_InheritBaseNormal1("_InheritBaseNormal1", Range(0, 1.0)) = 0.0
_InheritBaseNormal2("_InheritBaseNormal2", Range(0, 1.0)) = 0.0
_InheritBaseNormal3("_InheritBaseNormal3", Range(0, 1.0)) = 0.0
_BlendSize1("_BlendSize1", Range(0, 0.30)) = 0.0
_BlendSize2("_BlendSize2", Range(0, 0.30)) = 0.0
_BlendSize3("_BlendSize3", Range(0, 0.30)) = 0.0
_InheritBaseHeight1("_InheritBaseHeight1", Range(0, 1.0)) = 0.0
_InheritBaseHeight2("_InheritBaseHeight2", Range(0, 1.0)) = 0.0
_InheritBaseHeight3("_InheritBaseHeight3", Range(0, 1.0)) = 0.0
_InheritBaseLayer1("_InheritBaseLayer1", Range(0, 1.0)) = 0.0
_InheritBaseLayer2("_InheritBaseLayer2", Range(0, 1.0)) = 0.0
_InheritBaseLayer3("_InheritBaseLayer3", Range(0, 1.0)) = 0.0
_InheritBaseColor1("_InheritBaseColor1", Range(0, 1.0)) = 0.0
_InheritBaseColor2("_InheritBaseColor2", Range(0, 1.0)) = 0.0
_InheritBaseColor3("_InheritBaseColor3", Range(0, 1.0)) = 0.0
_VertexColorHeightFactor("_VertexColorHeightFactor", Float) = 0.3
_InheritBaseColorThreshold1("_InheritBaseColorThreshold1", Range(0, 1.0)) = 1.0
_InheritBaseColorThreshold2("_InheritBaseColorThreshold2", Range(0, 1.0)) = 1.0
_InheritBaseColorThreshold3("_InheritBaseColorThreshold3", Range(0, 1.0)) = 1.0
_MinimumOpacity0("_MinimumOpacity0", Range(0, 1.0)) = 1.0
_MinimumOpacity1("_MinimumOpacity1", Range(0, 1.0)) = 1.0
_MinimumOpacity2("_MinimumOpacity2", Range(0, 1.0)) = 1.0
_MinimumOpacity3("_MinimumOpacity3", Range(0, 1.0)) = 1.0
_OpacityAsDensity0("_OpacityAsDensity0", Range(0, 1.0)) = 0.0
_OpacityAsDensity1("_OpacityAsDensity1", Range(0, 1.0)) = 0.0
_OpacityAsDensity2("_OpacityAsDensity2", Range(0, 1.0)) = 0.0
_OpacityAsDensity3("_OpacityAsDensity3", Range(0, 1.0)) = 0.0
_LayerTiling0("LayerTiling0", Float) = 1
_LayerTiling1("LayerTiling1", Float) = 1
_LayerTiling2("LayerTiling2", Float) = 1
_LayerTiling3("LayerTiling3", Float) = 1
_DistortionVectorMap("DistortionVectorMap", 2D) = "black" {}

[Enum(Mask Alpha, 0, BaseColor Alpha, 1)] _SmoothnessTextureChannel("Smoothness texture channel", Float) = 1
[Enum(TangentSpace, 0, ObjectSpace, 1)] _NormalMapSpace("NormalMap space", Float) = 0
[ToggleOff] _EnablePerPixelDisplacement("Enable per pixel displacement", Float) = 0.0
_PPDMinSamples("Min sample for POM", Range(1.0, 64.0)) = 5
_PPDMaxSamples("Max sample for POM", Range(1.0, 64.0)) = 15
// WARNING
// All the following properties that concern the UV mapping are the same as in the Lit shader.
// This means that they will get overridden when synchronizing the various layers.
// To avoid this, make sure that all properties here are in the exclusion list in LayeredLitUI.SynchronizeLayerProperties
[Enum(None, 0, Multiply, 1, Add, 2)] _VertexColorMode("Vertex color mode", Float) = 0
// WARNING
// All the following properties that concern the UV mapping are the same as in the Lit shader.
// This means that they will get overridden when synchronizing the various layers.
// To avoid this, make sure that all properties here are in the exclusion list in LayeredLitUI.SynchronizeLayerProperties
_TexWorldScale0("Tiling", Float) = 1.0
_TexWorldScale1("Tiling", Float) = 1.0
_TexWorldScale2("Tiling", Float) = 1.0

HLSLINCLUDE
#pragma target 5.0
#pragma only_renderers d3d11 ps4// TEMP: unitl we go futher in dev
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#pragma shader_feature _ _DOUBLESIDED_LIGHTING_FLIP _DOUBLESIDED_LIGHTING_MIRROR
#pragma shader_feature _ _DOUBLESIDED _DOUBLESIDED_LIGHTING_FLIP _DOUBLESIDED_LIGHTING_MIRROR
#pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature _LAYER_MAPPING_TRIPLANAR_0

#pragma shader_feature _DETAIL_MAP_WITH_NORMAL
#pragma shader_feature _NORMALMAP_TANGENT_SPACE
#pragma shader_feature _PER_PIXEL_DISPLACEMENT
#pragma shader_feature _REQUIRE_UV2_OR_UV3
#pragma shader_feature _ _REQUIRE_UV2 _REQUIRE_UV3
#pragma shader_feature _EMISSIVE_COLOR
#pragma shader_feature _NORMALMAP

#pragma shader_feature _HEIGHTMAP
#pragma shader_feature _DETAIL_MAP
#pragma shader_feature _ _LAYER_MASK_VERTEX_COLOR_MUL _LAYER_MASK_VERTEX_COLOR_ADD
#pragma shader_feature _MAIN_LAYER_INFLUENCE_MODE
#pragma shader_feature _DENSITY_MODE
#pragma shader_feature _HEIGHT_BASED_BLEND
#pragma shader_feature _ _LAYEREDLIT_3_LAYERS _LAYEREDLIT_4_LAYERS

#include "common.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderConfig.cs.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderVariables.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Attributes.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/FragInputs.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPass.cs.hlsl"
//-------------------------------------------------------------------------------------

#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "../Lit/LitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL

#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "../Lit/LitData.hlsl"
#include "../../ShaderPass/ShaderPassDebugViewMaterial.hlsl"
ENDHLSL

#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitMetaPass.hlsl"
#include "../Lit/LitData.hlsl"
#include "../../ShaderPass/ShaderPassLightTransport.hlsl"
ENDHLSL

#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitVelocityPass.hlsl"
#include "../Lit/LitData.hlsl"
#include "../../ShaderPass/ShaderPassVelocity.hlsl"
ENDHLSL

#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitDepthPass.hlsl"
#include "../Lit/LitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL

#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitDepthPass.hlsl"
#include "../Lit/LitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL

#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitDistortionPass.hlsl"
#include "../Lit/LitData.hlsl"
#include "../../ShaderPass/ShaderPassDistortion.hlsl"
ENDHLSL

HLSLPROGRAM
#define SHADERPASS SHADERPASS_FORWARD
#include "../../Lighting/Forward.hlsl"
// #include "../../Lighting/Forward.hlsl"
//#pragma multi_compile SHADOWFILTERING_FIXED_SIZE_PCF
#include "../../ShaderPass/ShaderPassForward.hlsl"
ENDHLSL

138
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader


_DetailAOScale2("_DetailAOScale2", Range(-2.0, 2.0)) = 1
_DetailAOScale3("_DetailAOScale3", Range(-2.0, 2.0)) = 1
// Specific to planar mapping
_TexWorldScale0("TexWorldScale0", Float) = 1.0
_TexWorldScale1("TexWorldScale1", Float) = 1.0
_TexWorldScale2("TexWorldScale2", Float) = 1.0
_TexWorldScale3("TexWorldScale3", Float) = 1.0
[ToggleOff] _LayerMaskVertexColor("Use Vertex Color Mask", Float) = 0.0
// Layer blending options V2
[ToggleOff] _UseDensityMode("Use Density mode", Float) = 0.0
[ToggleOff] _UseMainLayerInfluence("UseMainLayerInfluence", Float) = 0.0
_HeightOffset1("_HeightOffset1", Range(-0.3, 0.3)) = 0.0
_HeightOffset2("_HeightOffset2", Range(-0.3, 0.3)) = 0.0
_HeightOffset3("_HeightOffset3", Range(-0.3, 0.3)) = 0.0
_HeightFactor0("_HeightFactor0", Float) = 1
_HeightFactor1("_HeightFactor1", Float) = 1
_HeightFactor2("_HeightFactor2", Float) = 1
_HeightFactor3("_HeightFactor3", Float) = 1
_HeightCenterOffset0("_HeightCenterOffset0", Float) = 0.0
_HeightCenterOffset1("_HeightCenterOffset1", Float) = 0.0
_HeightCenterOffset2("_HeightCenterOffset2", Float) = 0.0
_HeightCenterOffset3("_HeightCenterOffset3", Float) = 0.0
_BlendUsingHeight1("_BlendUsingHeight1", Float) = 0.0
_BlendUsingHeight2("_BlendUsingHeight2", Float) = 0.0
_BlendUsingHeight3("_BlendUsingHeight3", Float) = 0.0
_InheritBaseNormal1("_InheritBaseNormal1", Range(0, 1.0)) = 0.0
_InheritBaseNormal2("_InheritBaseNormal2", Range(0, 1.0)) = 0.0
_InheritBaseNormal3("_InheritBaseNormal3", Range(0, 1.0)) = 0.0
_InheritBaseHeight1("_InheritBaseHeight1", Range(0, 1.0)) = 0.0
_InheritBaseHeight2("_InheritBaseHeight2", Range(0, 1.0)) = 0.0
_InheritBaseHeight3("_InheritBaseHeight3", Range(0, 1.0)) = 0.0
_InheritBaseColor1("_InheritBaseColor1", Range(0, 1.0)) = 0.0
_InheritBaseColor2("_InheritBaseColor2", Range(0, 1.0)) = 0.0
_InheritBaseColor3("_InheritBaseColor3", Range(0, 1.0)) = 0.0
_HeightFactor1("_HeightFactor1", Range(0, 5)) = 1
_HeightFactor2("_HeightFactor2", Range(0, 5)) = 1
_HeightFactor3("_HeightFactor3", Range(0, 5)) = 1
_InheritBaseColorThreshold1("_InheritBaseColorThreshold1", Range(0, 1.0)) = 1.0
_InheritBaseColorThreshold2("_InheritBaseColorThreshold2", Range(0, 1.0)) = 1.0
_InheritBaseColorThreshold3("_InheritBaseColorThreshold3", Range(0, 1.0)) = 1.0
_BlendSize1("_BlendSize1", Range(0, 0.05)) = 0.0
_BlendSize2("_BlendSize2", Range(0, 0.05)) = 0.0
_BlendSize3("_BlendSize3", Range(0, 0.05)) = 0.0
_MinimumOpacity0("_MinimumOpacity0", Range(0, 1.0)) = 1.0
_MinimumOpacity1("_MinimumOpacity1", Range(0, 1.0)) = 1.0
_MinimumOpacity2("_MinimumOpacity2", Range(0, 1.0)) = 1.0
_MinimumOpacity3("_MinimumOpacity3", Range(0, 1.0)) = 1.0
_InheritBaseLayer1("_InheritBaseLayer1", Range(0, 1.0)) = 0.0
_InheritBaseLayer2("_InheritBaseLayer2", Range(0, 1.0)) = 0.0
_InheritBaseLayer3("_InheritBaseLayer3", Range(0, 1.0)) = 0.0
_OpacityAsDensity0("_OpacityAsDensity0", Range(0, 1.0)) = 0.0
_OpacityAsDensity1("_OpacityAsDensity1", Range(0, 1.0)) = 0.0
_OpacityAsDensity2("_OpacityAsDensity2", Range(0, 1.0)) = 0.0
_OpacityAsDensity3("_OpacityAsDensity3", Range(0, 1.0)) = 0.0
_VertexColorHeightFactor("_VertexColorHeightFactor", Float) = 0.3
_LayerTiling0("LayerTiling0", Float) = 1
_LayerTiling1("LayerTiling1", Float) = 1
_LayerTiling2("LayerTiling2", Float) = 1
_LayerTiling3("LayerTiling3", Float) = 1
_DistortionVectorMap("DistortionVectorMap", 2D) = "black" {}

[Enum(Mask Alpha, 0, BaseColor Alpha, 1)] _SmoothnessTextureChannel("Smoothness texture channel", Float) = 1
[Enum(TangentSpace, 0, ObjectSpace, 1)] _NormalMapSpace("NormalMap space", Float) = 0
[ToggleOff] _EnablePerPixelDisplacement("Enable per pixel displacement", Float) = 0.0
_PPDMinSamples("Min sample for POM", Range(1.0, 64.0)) = 5
_PPDMaxSamples("Max sample for POM", Range(1.0, 64.0)) = 15
// WARNING
// All the following properties that concern the UV mapping are the same as in the Lit shader.
// This means that they will get overridden when synchronizing the various layers.
// To avoid this, make sure that all properties here are in the exclusion list in LayeredLitUI.SynchronizeLayerProperties
[Enum(None, 0, Multiply, 1, Add, 2)] _VertexColorMode("Vertex color mode", Float) = 0
// WARNING
// All the following properties that concern the UV mapping are the same as in the Lit shader.
// This means that they will get overridden when synchronizing the various layers.
// To avoid this, make sure that all properties here are in the exclusion list in LayeredLitUI.SynchronizeLayerProperties
_TexWorldScale0("Tiling", Float) = 1.0
_TexWorldScale1("Tiling", Float) = 1.0
_TexWorldScale2("Tiling", Float) = 1.0

// Tesselation specific
[Enum(Phong, 0, Displacement, 1, DisplacementPhong, 2)] _TessellationMode("Tessellation mode", Float) = 1
_TessellationFactorFixed("Tessellation Factor", Float) = 4.0 // if != -1.0 force fixed factor
_TessellationFactorMaxDistance("Tessellation max distance factor", Float) = 12.0
_TessellationFactorTriangleSize("Tessellation triangle size", Float) = 20.0
_TessellationFactor("Tessellation Factor", Range(0.0, 15.0)) = 4.0
_TessellationFactorMinDistance("Tessellation start fading distance", Float) = 20.0
_TessellationFactorMaxDistance("Tessellation end fading distance", Float) = 50.0
_TessellationFactorTriangleSize("Tessellation triangle size", Float) = 100.0
_TessellationBackFaceCullEpsilon("Tessellation back face epsilon", Range(-1.0, 1.0)) = 0.25
_TessellationBackFaceCullEpsilon("Tessellation back face epsilon", Range(-1.0, 0.0)) = -0.25
[ToggleOff] _TessellationObjectScale("Tessellation object scale", Float) = 0.0
// TODO: Handle culling mode for backface culling
}

#pragma target 5.0
#pragma only_renderers d3d11 ps4// TEMP: unitl we go futher in dev
#pragma only_renderers d3d11 ps4 // TEMP: unitl we go futher in dev
#pragma shader_feature _ _DOUBLESIDED_LIGHTING_FLIP _DOUBLESIDED_LIGHTING_MIRROR
// Default is _TESSELATION_PHONG
#pragma shader_feature _ _TESSELATION_DISPLACEMENT _TESSELATION_DISPLACEMENT_PHONG
#pragma shader_feature _ _DOUBLESIDED _DOUBLESIDED_LIGHTING_FLIP _DOUBLESIDED_LIGHTING_MIRROR
// Default is _TESSELLATION_PHONG
#pragma shader_feature _ _TESSELLATION_DISPLACEMENT _TESSELLATION_DISPLACEMENT_PHONG
#pragma shader_feature _TESSELLATION_OBJECT_SCALE
#pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature _LAYER_MAPPING_TRIPLANAR_0

#pragma shader_feature _DETAIL_MAP_WITH_NORMAL
#pragma shader_feature _NORMALMAP_TANGENT_SPACE
#pragma shader_feature _PER_PIXEL_DISPLACEMENT
#pragma shader_feature _REQUIRE_UV2_OR_UV3
#pragma shader_feature _ _REQUIRE_UV2 _REQUIRE_UV3
#pragma shader_feature _EMISSIVE_COLOR
#pragma shader_feature _NORMALMAP

#pragma shader_feature _HEIGHTMAP
#pragma shader_feature _DETAIL_MAP
#pragma shader_feature _ _LAYER_MASK_VERTEX_COLOR_MUL _LAYER_MASK_VERTEX_COLOR_ADD
#pragma shader_feature _MAIN_LAYER_INFLUENCE_MODE
#pragma shader_feature _DENSITY_MODE
#pragma shader_feature _ _LAYEREDLIT_3_LAYERS _LAYEREDLIT_4_LAYERS
#pragma shader_feature _ _LAYEREDLIT_3_LAYERS _LAYEREDLIT_4_LAYERS
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED

// Define
//-------------------------------------------------------------------------------------
#define UNITY_MATERIAL_LIT // Need to be define before including Material.hlsl
#define TESSELATION_ON
#define UNITY_MATERIAL_LIT // Need to be define before including Material.hlsl
#define TESSELLATION_ON
//-------------------------------------------------------------------------------------
// Include

#include "tesselation.hlsl"
#include "tessellation.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Attributes.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/FragInputs.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPass.cs.hlsl"
//-------------------------------------------------------------------------------------

#include "Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/LitProperties.hlsl"
// All our shaders use same name for entry point
#pragma vertex Vert
#pragma fragment Frag
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTesselation
#pragma hull Hull
#pragma domain Domain

#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "../Lit/LitData.hlsl"
#include "../Tesselation/TesselationShare.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTesselation
#pragma hull Hull
#pragma domain Domain

#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "../Lit/LitData.hlsl"
#include "../Tesselation/TesselationShare.hlsl"
#include "../../ShaderPass/ShaderPassDebugViewMaterial.hlsl"
ENDHLSL

// DYNAMICLIGHTMAP_ON is used when we have an "enlighten lightmap" ie a lightmap updated at runtime by enlighten.This lightmap contain indirect lighting from realtime lights and realtime emissive material.Offline baked lighting(from baked material / light,
// both direct and indirect lighting) will hand up in the "regular" lightmap->LIGHTMAP_ON.
#pragma vertex Vert
// No tessellation for Meta pass
#undef TESSELLATION_ON
#include "../../ShaderPass/ShaderPassLightTransport.hlsl"
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTesselation
#pragma hull Hull
#pragma domain Domain

#include "../Lit/LitData.hlsl"
#include "../Tesselation/TesselationShare.hlsl"
#include "../../ShaderPass/ShaderPassVelocity.hlsl"
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTesselation
#pragma hull Hull
#pragma domain Domain

#include "../Lit/LitData.hlsl"
#include "../Tesselation/TesselationShare.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTesselation
#pragma hull Hull
#pragma domain Domain

#include "../Lit/LitData.hlsl"
#include "../Tesselation/TesselationShare.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTesselation
#pragma hull Hull
#pragma domain Domain

#include "../Lit/LitData.hlsl"
#include "../Tesselation/TesselationShare.hlsl"
#include "../../ShaderPass/ShaderPassDistortion.hlsl"
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTesselation
#include "../../Lighting/Forward.hlsl"
// #include "../../Lighting/Forward.hlsl"
//#pragma multi_compile SHADOWFILTERING_FIXED_SIZE_PCF
#include "../Tesselation/TesselationShare.hlsl"
#include "../../ShaderPass/ShaderPassForward.hlsl"
ENDHLSL

CustomEditor "Experimental.Rendering.HDPipeline.LayeredLitGUI"
CustomEditor "Experimental.Rendering.HDPipeline.LayeredLitGUI"
}

53
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs


public static string surfaceTypeText = "Surface Type";
public static string blendModeText = "Blend Mode";
public static string detailText = "Inputs Detail";
public static string textureControlText = "Input textures control";
public static string lightingText = "Inputs Lighting";
public static GUIContent alphaCutoffEnableText = new GUIContent("Alpha Cutoff Enable", "Threshold for alpha cutoff");

public static GUIContent UVBaseDetailMappingText = new GUIContent("UV set for Base and Detail", "");
public static GUIContent normalMapSpaceText = new GUIContent("Normal/Tangent Map space", "");
public static GUIContent enablePerPixelDisplacementText = new GUIContent("Enable Per Pixel Displacement", "");
public static GUIContent ppdMinSamplesText = new GUIContent("Minimum samples", "Minimun samples to use with per pixel displacement mapping");
public static GUIContent ppdMaxSamplesText = new GUIContent("Maximum samples", "Maximum samples to use with per pxiel displacement mapping");
public static GUIContent detailMapModeText = new GUIContent("Detail Map with Normal", "Detail Map with AO / Height");
public static GUIContent UVDetailMappingText = new GUIContent("UV set for Detail", "");
public static GUIContent emissiveColorModeText = new GUIContent("Emissive Color Usage", "Use emissive color or emissive mask");

public static GUIContent tangentMapText = new GUIContent("Tangent Map", "Tangent Map (BC5) - DXT5 for test");
public static GUIContent anisotropyText = new GUIContent("Anisotropy", "Anisotropy scale factor");
public static GUIContent anisotropyMapText = new GUIContent("Anisotropy Map (G)", "Anisotropy");
public static GUIContent anisotropyMapText = new GUIContent("Anisotropy Map (B)", "Anisotropy");
public static GUIContent detailMaskText = new GUIContent("Detail Mask (B)", "Mask for detailMap");
public static GUIContent detailMaskText = new GUIContent("Detail Mask (G)", "Mask for detailMap");
public static GUIContent detailAlbedoScaleText = new GUIContent("Detail AlbedoScale", "Detail Albedo Scale factor");
public static GUIContent detailNormalScaleText = new GUIContent("Detail NormalScale", "Normal Scale factor");
public static GUIContent detailSmoothnessScaleText = new GUIContent("Detail SmoothnessScale", "Smoothness Scale factor");

public static readonly string[] tessellationModeNames = Enum.GetNames(typeof(TessellationMode));
public static GUIContent tessellationText = new GUIContent("Tessellation options", "Tessellation options");
public static GUIContent tessellationFactorFixedText = new GUIContent("Fixed tessellation factor", "If non negative, this value is a fixed tessellation factor use for tessellation");
public static GUIContent tessellationFactorMaxDistanceText = new GUIContent("Max Distance", "Maximun distance to the camera where triangle are tesselated");
public static GUIContent tessellationFactorTriangleSizeText = new GUIContent("Triangle size", "Desired screen space sized of triangle. Smaller value mean smaller triangle.");
public static GUIContent tessellationFactorText = new GUIContent("Tessellation factor", "This value is the tessellation factor use for tessellation, higher mean more tessellated");
public static GUIContent tessellationFactorMinDistanceText = new GUIContent("Start fade distance", "Distance (in unity unit) at which the tessellation start to fade out. Must be inferior at Max distance");
public static GUIContent tessellationFactorMaxDistanceText = new GUIContent("End fade distance", "Maximum distance (in unity unit) to the camera where triangle are tessellated");
public static GUIContent tessellationFactorTriangleSizeText = new GUIContent("Triangle size", "Desired screen space sized of triangle (in pixel). Smaller value mean smaller triangle.");
public static GUIContent tessellationBackFaceCullEpsilonText = new GUIContent("Triangle culling Epsilon", "If non zero, backface culling is enabled for tessellation, smaller number mean more aggressive culling and better performance");
public static GUIContent tessellationObjectScaleText = new GUIContent("Enable object scale", "Scale displacement taking into account the object scale");
public static GUIContent tessellationBackFaceCullEpsilonText = new GUIContent("Triangle culling Epsilon", "If -1.0 back face culling is enabled for tessellation, higher number mean more aggressive culling and better performance");
public static GUIContent tessellationObjectScaleText = new GUIContent("Enable object scale", "Tesselation displacement will take into account the object scale - Only work with uniform positive scale");
}
public enum SurfaceType

GUILayout.Label(Styles.tessellationText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
TessellationModePopup();
m_MaterialEditor.ShaderProperty(tessellationFactorFixed, Styles.tessellationFactorFixedText);
m_MaterialEditor.ShaderProperty(tessellationFactor, Styles.tessellationFactorText);
m_MaterialEditor.ShaderProperty(tessellationFactorMinDistance, Styles.tessellationFactorMinDistanceText);
// clamp min distance to be below max distance
tessellationFactorMinDistance.floatValue = Math.Min(tessellationFactorMaxDistance.floatValue, tessellationFactorMinDistance.floatValue);
m_MaterialEditor.ShaderProperty(tessellationFactorTriangleSize, Styles.tessellationFactorTriangleSizeText);
if ((TessellationMode)tessellationMode.floatValue == TessellationMode.Phong ||
(TessellationMode)tessellationMode.floatValue == TessellationMode.DisplacementPhong)

m_MaterialEditor.ShaderProperty(tessellationBackFaceCullEpsilon, Styles.tessellationBackFaceCullEpsilonText);
if ((DoubleSidedMode)doubleSidedMode.floatValue == DoubleSidedMode.None)
{
m_MaterialEditor.ShaderProperty(tessellationBackFaceCullEpsilon, Styles.tessellationBackFaceCullEpsilonText);
}
m_MaterialEditor.ShaderProperty(tessellationObjectScale, Styles.tessellationObjectScaleText);
EditorGUI.indentLevel--;
}

// tessellation specific, silent if not found
tessellationMode = FindProperty(kTessellationMode, props, false);
tessellationFactorFixed = FindProperty(kTessellationFactorFixed, props, false);
tessellationFactor = FindProperty(kTessellationFactor, props, false);
tessellationFactorMinDistance = FindProperty(kTessellationFactorMinDistance, props, false);
tessellationFactorMaxDistance = FindProperty(kTessellationFactorMaxDistance, props, false);
tessellationFactorTriangleSize = FindProperty(kTessellationFactorTriangleSize, props, false);
tessellationShapeFactor = FindProperty(kTessellationShapeFactor, props, false);

if (doubleSidedMode == DoubleSidedMode.DoubleSidedLightingFlip)
{
material.DisableKeyword("_DOUBLESIDED");
material.DisableKeyword("_DOUBLESIDED");
else if (doubleSidedMode == DoubleSidedMode.DoubleSided)
{
material.EnableKeyword("_DOUBLESIDED");
material.DisableKeyword("_DOUBLESIDED_LIGHTING_FLIP");
material.DisableKeyword("_DOUBLESIDED_LIGHTING_MIRROR");
}
material.DisableKeyword("_DOUBLESIDED");
material.DisableKeyword("_DOUBLESIDED_LIGHTING_FLIP");
material.DisableKeyword("_DOUBLESIDED_LIGHTING_MIRROR");
}

material.DisableKeyword("_TESSELLATION_DISPLACEMENT");
material.EnableKeyword("_TESSELLATION_DISPLACEMENT_PHONG");
}
bool tessellationObjectScaleEnable = material.GetFloat(kTessellationObjectScale) == 1.0;
SetKeyword(material, "_TESSELLATION_OBJECT_SCALE", tessellationObjectScaleEnable);
}
}

const string kDepthOffsetEnable = "_DepthOffsetEnable";
// tessellation params
MaterialProperty tessellationMode = null;
protected MaterialProperty tessellationMode = null;
MaterialProperty tessellationFactorFixed = null;
const string kTessellationFactorFixed = "_TessellationFactorFixed";
MaterialProperty tessellationFactor = null;
const string kTessellationFactor = "_TessellationFactor";
MaterialProperty tessellationFactorMinDistance = null;
const string kTessellationFactorMinDistance = "_TessellationFactorMinDistance";
MaterialProperty tessellationFactorMaxDistance = null;
const string kTessellationFactorMaxDistance = "_TessellationFactorMaxDistance";
MaterialProperty tessellationFactorTriangleSize = null;

36
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Editor/LitUI.cs


protected const string kNormalMapSpace = "_NormalMapSpace";
protected MaterialProperty enablePerPixelDisplacement = null;
protected const string kEnablePerPixelDisplacement = "_EnablePerPixelDisplacement";
protected MaterialProperty ppdMinSamples = null;
protected const string kPpdMinSamples = "_PPDMinSamples";
protected MaterialProperty ppdMaxSamples = null;
protected const string kPpdMaxSamples = "_PPDMaxSamples";
protected MaterialProperty detailMapMode = null;
protected const string kDetailMapMode = "_DetailMapMode";
protected MaterialProperty UVDetail = null;

smoothnessMapChannel = FindProperty(kSmoothnessTextureChannel, props);
normalMapSpace = FindProperty(kNormalMapSpace, props);
enablePerPixelDisplacement = FindProperty(kEnablePerPixelDisplacement, props);
ppdMinSamples = FindProperty(kPpdMinSamples, props);
ppdMaxSamples = FindProperty(kPpdMaxSamples, props);
detailMapMode = FindProperty(kDetailMapMode, props);
emissiveColorMode = FindProperty(kEmissiveColorMode, props);
}

m_MaterialEditor.ShaderProperty(normalMapSpace, Styles.normalMapSpaceText.text);
m_MaterialEditor.ShaderProperty(emissiveColorMode, Styles.emissiveColorModeText.text);
m_MaterialEditor.ShaderProperty(enablePerPixelDisplacement, Styles.enablePerPixelDisplacementText.text);
m_MaterialEditor.ShaderProperty(ppdMinSamples, Styles.ppdMinSamplesText.text);
m_MaterialEditor.ShaderProperty(ppdMaxSamples, Styles.ppdMaxSamplesText.text);
ppdMinSamples.floatValue = Mathf.Min(ppdMinSamples.floatValue, ppdMaxSamples.floatValue);
EditorGUI.indentLevel--;
}

{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(heightAmplitude, Styles.heightMapAmplitudeText);
heightAmplitude.floatValue = Math.Max(0.0f, heightAmplitude.floatValue); // Must be positive
m_MaterialEditor.ShaderProperty(heightCenter, Styles.heightMapCenterText);
EditorGUI.showMixedValue = false;
EditorGUI.indentLevel--;

m_MaterialEditor.TexturePropertySingleLine(Styles.anisotropyMapText, anisotropyMap);
EditorGUILayout.Space();
GUILayout.Label(Styles.textureControlText, EditorStyles.label);
m_MaterialEditor.TextureScaleOffsetProperty(baseColorMap);
EditorGUILayout.Space();

SetKeyword(material, "_ANISOTROPYMAP", material.GetTexture(kAnisotropyMap));
SetKeyword(material, "_DETAIL_MAP", material.GetTexture(kDetailMap));
SetKeyword(material, "_REQUIRE_UV2_OR_UV3", (
((UVDetailMapping)material.GetFloat(kUVDetail) == UVDetailMapping.UV2 || (UVDetailMapping)material.GetFloat(kUVDetail) == UVDetailMapping.UV3)
&& (UVBaseMapping)material.GetFloat(kUVBase) == UVBaseMapping.UV0)
);
}
bool needUV2 = (UVDetailMapping)material.GetFloat(kUVDetail) == UVDetailMapping.UV2 && (UVBaseMapping)material.GetFloat(kUVBase) == UVBaseMapping.UV0;
bool needUV3 = (UVDetailMapping)material.GetFloat(kUVDetail) == UVDetailMapping.UV3 && (UVBaseMapping)material.GetFloat(kUVBase) == UVBaseMapping.UV0;
if (needUV3)
{
material.DisableKeyword("_REQUIRE_UV2");
material.EnableKeyword("_REQUIRE_UV3");
}
else if (needUV2)
{
material.EnableKeyword("_REQUIRE_UV2");
material.DisableKeyword("_REQUIRE_UV3");
}
else
{
material.DisableKeyword("_REQUIRE_UV2");
material.DisableKeyword("_REQUIRE_UV3");
}
}
}
} // namespace UnityEditor

77
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Lit.cs


// Init precomputed texture
//-----------------------------------------------------------------------------
public bool isInit;
public bool isInit;
private Material m_InitPreFGD;
private Material m_InitPreFGD;
// For area lighting
private Texture2D m_LtcGGXMatrix; // RGBA
private Texture2D m_LtcDisneyDiffuseMatrix; // RGBA
private Texture2D m_LtcMultiGGXFresnelDisneyDiffuse; // RGB, A unused
// 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
Material CreateEngineMaterial(string shaderPath)
{
Material mat = new Material(Shader.Find(shaderPath) as Shader);
mat.hideFlags = HideFlags.HideAndDontSave;
return mat;
}
Texture2D CreateLUT(int width, int height, TextureFormat format, Color[] pixels)
{
Texture2D tex = new Texture2D(width, height, format, false /*mipmap*/, true /*linear*/);
tex.hideFlags = HideFlags.HideAndDontSave;
tex.wrapMode = TextureWrapMode.Clamp;
tex.SetPixels(pixels);
tex.Apply();
return tex;
}
Texture2D LoadLUT(TextureFormat format, float[] LUTScalar)
void LoadLUT(Texture2DArray tex, int arrayElement, TextureFormat format, float[] LUTScalar)
// amplitude
return CreateLUT(k_LtcLUTResolution, k_LtcLUTResolution, format, pixels);
tex.SetPixels(pixels, arrayElement);
Texture2D LoadLUT(TextureFormat format, double[,] LUTTransformInv)
void LoadLUT(Texture2DArray tex, int arrayElement, TextureFormat format, double[,] LUTTransformInv)
// transformInv
for (int i = 0; i < count; i++)
{
// Both GGX and Disney Diffuse BRDFs have zero values in columns 1, 3, 5, 7.

(float)LUTTransformInv[i, 6]);
}
return CreateLUT(k_LtcLUTResolution, k_LtcLUTResolution, format, pixels);
tex.SetPixels(pixels, arrayElement);
Texture2D LoadLUT(TextureFormat format, float[] LtcGGXMagnitudeData,
float[] LtcGGXFresnelData,
float[] LtcDisneyDiffuseMagnitudeData)
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];

LtcGGXFresnelData[i], LtcDisneyDiffuseMagnitudeData[i], 1);
}
return CreateLUT(k_LtcLUTResolution, k_LtcLUTResolution, format, pixels);
}
tex.SetPixels(pixels, arrayElement);
}
m_InitPreFGD = CreateEngineMaterial("Hidden/HDRenderPipeline/PreIntegratedFGD");
m_InitPreFGD = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/PreIntegratedFGD");
m_PreIntegratedFGD = new RenderTexture(128, 128, 0, RenderTextureFormat.ARGBHalf);
m_PreIntegratedFGD = new RenderTexture(128, 128, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
m_PreIntegratedFGD.filterMode = FilterMode.Bilinear;
m_PreIntegratedFGD.wrapMode = TextureWrapMode.Clamp;
m_PreIntegratedFGD.Create();
m_LtcGGXMatrix = LoadLUT(TextureFormat.RGBAHalf, s_LtcGGXMatrixData);
m_LtcDisneyDiffuseMatrix = LoadLUT(TextureFormat.RGBAHalf, s_LtcDisneyDiffuseMatrixData);
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);
m_LtcMultiGGXFresnelDisneyDiffuse = LoadLUT(TextureFormat.RGBAHalf, s_LtcGGXMagnitudeData,
s_LtcGGXFresnelData,
s_LtcDisneyDiffuseMagnitudeData);
LoadLUT(m_LtcData, 2, TextureFormat.RGBAHalf, s_LtcGGXMagnitudeData, s_LtcGGXFresnelData, s_LtcDisneyDiffuseMagnitudeData);
m_LtcData.Apply();
isInit = false;
}

public void Bind()
{
Shader.SetGlobalTexture("_PreIntegratedFGD", m_PreIntegratedFGD);
Shader.SetGlobalTexture("_LtcGGXMatrix", m_LtcGGXMatrix);
Shader.SetGlobalTexture("_LtcDisneyDiffuseMatrix", m_LtcDisneyDiffuseMatrix);
Shader.SetGlobalTexture("_LtcMultiGGXFresnelDisneyDiffuse", m_LtcMultiGGXFresnelDisneyDiffuse);
Shader.SetGlobalTexture("_PreIntegratedFGD", m_PreIntegratedFGD);
Shader.SetGlobalTexture("_LtcData", m_LtcData);
}
}
}

58
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Lit.hlsl


//-----------------------------------------------------------------------------
// SurfaceData is define in Lit.cs which generate Lit.cs.hlsl
#include "Lit.cs.hlsl"
//TODO: return this original relative path include after fixing a bug in Unity side
//#include "Lit.cs.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Lit.cs.hlsl"
// In case we pack data uint16 buffer we need to change the output render target format to uint16
// TODO: Is there a way to automate these output type based on the format declare in lit.cs ?

// TODO: Check if anisotropy with a dynamic if on anisotropy > 0 is performant. Because it may mean we always calculate both isotropy and anisotropy case.
// Maybe we should always calculate anisotropy in case of standard ? Don't think the compile can optimize correctly.
// TODO: I haven't configure this sampler in the code, we should be able to do it (but Unity don't allow it for now...)
// By default Unity provide MIG_MAG_LINEAR_POINT sampler, so it fit with our need.
// TODO: to avoid the message Fragment program 'Frag' : sampler 'sampler_PreIntegratedFGD' has no matching texture and will be undefined.
// We need to test this define LIGHTLOOP_TILE_DIRECT, this is a bad workaround but no alternative until we can setup sampler correctly...
#if defined(LIT_DISPLAY_REFERENCE_IBL) || defined(LIGHTLOOP_TILE_DIRECT)
// When reference mode is enabled, then we need to chose another sampler not related to cubemap code...
SAMPLER2D(sampler_LtcGGXMatrix);
#define SRL_BilinearSampler sampler_LtcGGXMatrix // Used for all textures
#else
SAMPLER2D(sampler_PreIntegratedFGD);
#define SRL_BilinearSampler sampler_PreIntegratedFGD // Used for all textures
#endif
// TODO: we can share the sampler here and name it SRL_BilinearSampler. However Unity currently doesn't support to set sampler in C#
// + to avoid the message Fragment program 'Frag' : sampler 'sampler_PreIntegratedFGD' has no matching texture and will be undefined.
TEXTURE2D(_LtcGGXMatrix); // RGBA
TEXTURE2D(_LtcDisneyDiffuseMatrix); // RGBA
TEXTURE2D(_LtcMultiGGXFresnelDisneyDiffuse); // RGB, A unused
SAMPLER2D(sampler_PreIntegratedFGD);
TEXTURE2D_ARRAY(_LtcData); // We pack the 3 Ltc data inside a texture array
SAMPLER2D(sampler_LtcData);
#define LTC_GGX_MATRIX_INDEX 0 // RGBA
#define LTC_DISNEY_DIFFUSE_MATRIX_INDEX 1 // RGBA
#define LTC_MULTI_GGX_FRESNEL_DISNEY_DIFFUSE_INDEX 2 // RGB, A unused
//-----------------------------------------------------------------------------
// Helper functions/variable specific to this material

// _PreIntegratedFGD.y = Gv * Fc
// Pre integrate DisneyDiffuse FGD:
// _PreIntegratedFGD.z = DisneyDiffuse
float3 preFGD = SAMPLE_TEXTURE2D_LOD(_PreIntegratedFGD, SRL_BilinearSampler, float2(NdotV, perceptualRoughness), 0).xyz;
float3 preFGD = SAMPLE_TEXTURE2D_LOD(_PreIntegratedFGD, sampler_PreIntegratedFGD, float2(NdotV, perceptualRoughness), 0).xyz;
// f0 * Gv * (1 - Fc) + Gv * Fc
specularFGD = fresnel0 * preFGD.x + preFGD.y;

}
else if (surfaceData.materialId == MATERIALID_LIT_SSS)
{
outGBuffer2 = float4(surfaceData.subSurfaceRadius, surfaceData.thickness, 0.0, surfaceData.subSurfaceProfile / 8.0f); // Number of profile not define yet
outGBuffer2 = float4(surfaceData.subSurfaceRadius, surfaceData.thickness, 0.0, surfaceData.subSurfaceProfile / 8.0); // Number of profile not define yet
}
else if (surfaceData.materialId == MATERIALID_LIT_CLEAR_COAT)
{

bsdfData.fresnel0 = 0.028; // TODO take from subSurfaceProfile
bsdfData.subSurfaceRadius = inGBuffer2.r;
bsdfData.thickness = inGBuffer2.g;
bsdfData.subSurfaceProfile = inGBuffer2.a * 8.0f;
bsdfData.subSurfaceProfile = inGBuffer2.a * 8.0;
}
else if (bsdfData.materialId == MATERIALID_LIT_CLEAR_COAT)
{

float3 iblR = reflect(-V, iblNormalWS);
preLightData.iblDirWS = GetSpecularDominantDir(bsdfData.normalWS, iblR, bsdfData.roughness, preLightData.NdotV);
preLightData.iblMipLevel = perceptualRoughnessToMipmapLevel(bsdfData.perceptualRoughness);
preLightData.iblMipLevel = PerceptualRoughnessToMipmapLevel(bsdfData.perceptualRoughness);
// Area light specific
// UVs for sampling the LUTs

// Note we load the matrix transpose (avoid to have to transpose it in shader)
preLightData.ltcXformGGX = 0.0;
preLightData.ltcXformGGX._m22 = 1.0;
preLightData.ltcXformGGX._m00_m02_m11_m20 = SAMPLE_TEXTURE2D_LOD(_LtcGGXMatrix, SRL_BilinearSampler, uv, 0);
preLightData.ltcXformGGX._m00_m02_m11_m20 = SAMPLE_TEXTURE2D_ARRAY_LOD(_LtcData, sampler_LtcData, uv, LTC_GGX_MATRIX_INDEX, 0);
preLightData.ltcXformDisneyDiffuse._m00_m02_m11_m20 = SAMPLE_TEXTURE2D_LOD(_LtcDisneyDiffuseMatrix, SRL_BilinearSampler, uv, 0);
preLightData.ltcXformDisneyDiffuse._m00_m02_m11_m20 = SAMPLE_TEXTURE2D_ARRAY_LOD(_LtcData, sampler_LtcData, uv, LTC_DISNEY_DIFFUSE_MATRIX_INDEX, 0);
float3 ltcMagnitude = SAMPLE_TEXTURE2D_LOD(_LtcMultiGGXFresnelDisneyDiffuse, SRL_BilinearSampler, uv, 0).r;
float3 ltcMagnitude = SAMPLE_TEXTURE2D_ARRAY_LOD(_LtcData, sampler_LtcData, uv, LTC_MULTI_GGX_FRESNEL_DISNEY_DIFFUSE_INDEX, 0).rgb;
preLightData.ltcGGXFresnelMagnitudeDiff = ltcMagnitude.r;
preLightData.ltcGGXFresnelMagnitude = ltcMagnitude.g;
preLightData.ltcDisneyDiffuseMagnitude = ltcMagnitude.b;

specularLighting = float3(0.0, 0.0, 0.0);
float3 cookieColor = float3(1.0, 1.0, 1.0);
[branch] if (lightData.shadowIndex >= 0 && illuminance > 0.0f)
[branch] if (lightData.shadowIndex >= 0 && illuminance > 0.0)
{
float shadowAttenuation = GetDirectionalShadowAttenuation(lightLoopContext, positionWS, lightData.shadowIndex, L, posInput.unPositionSS);

illuminance *= cookie.a;
}
[branch] if (illuminance > 0.0f)
[branch] if (illuminance > 0.0)
{
BSDF(V, L, positionWS, preLightData, bsdfData, diffuseLighting, specularLighting);
diffuseLighting *= (cookieColor * lightData.color) * (illuminance * lightData.diffuseScale);

// TODO: measure impact of having all these dynamic branch here and the gain (or not) of testing illuminace > 0
[branch] if (lightData.IESIndex >= 0 && illuminance > 0.0)
{
float3x3 lightToWorld = float3x3(lightData.right, lightData.up, lightData.forward);
float2 sphericalCoord = GetIESTextureCoordinate(lightToWorld, L);
illuminance *= SampleIES(lightLoopContext, lightData.IESIndex, sphericalCoord, 0).r;
}
//[branch] if (lightData.IESIndex >= 0 && illuminance > 0.0)
//{
// float3x3 lightToWorld = float3x3(lightData.right, lightData.up, lightData.forward);
// float2 sphericalCoord = GetIESTextureCoordinate(lightToWorld, L);
// illuminance *= SampleIES(lightLoopContext, lightData.IESIndex, sphericalCoord, 0).r;
//}
[branch] if (lightData.shadowIndex >= 0 && illuminance > 0.0)
{

55
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Lit.shader


// Blending state
[HideInInspector] _SurfaceType("__surfacetype", Float) = 0.0
[HideInInspector] _BlendMode ("__blendmode", Float) = 0.0
[HideInInspector] _SrcBlend ("__src", Float) = 1.0
[HideInInspector] _DstBlend ("__dst", Float) = 0.0
[HideInInspector] _ZWrite ("__zw", Float) = 1.0
[HideInInspector] _BlendMode("__blendmode", Float) = 0.0
[HideInInspector] _SrcBlend("__src", Float) = 1.0
[HideInInspector] _DstBlend("__dst", Float) = 0.0
[HideInInspector] _ZWrite("__zw", Float) = 1.0
// Material Id
[HideInInspector] _MaterialId("_MaterialId", FLoat) = 0

[Enum(UV0, 0, Planar, 1, TriPlanar, 2)] _UVBase("UV Set for base", Float) = 0
_TexWorldScale("Scale to apply on world coordinate", Float) = 1.0
[HideInInspector] _UVMappingMask("_UVMappingMask", Color) = (1,0,0,0)
[HideInInspector] _UVMappingMask("_UVMappingMask", Color) = (1, 0, 0, 0)
_PPDMinSamples("Min sample for POM", Range(1.0, 64.0)) = 5
_PPDMaxSamples("Max sample for POM", Range(1.0, 64.0)) = 15
[HideInInspector] _UVDetailsMappingMask("_UVDetailsMappingMask", Color) = (1,0,0,0)
[Enum(Use Emissive Color, 0, Use Emissive Mask, 1)] _EmissiveColorMode("Emissive color mode", Float) = 1
[HideInInspector] _UVDetailsMappingMask("_UVDetailsMappingMask", Color) = (1, 0, 0, 0)
[Enum(Use Emissive Color, 0, Use Emissive Mask, 1)] _EmissiveColorMode("Emissive color mode", Float) = 1
#pragma target 5.0
#pragma only_renderers d3d11 ps4// TEMP: unitl we go futher in dev
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go futher in dev
//-------------------------------------------------------------------------------------
// Variant

#pragma shader_feature _DISTORTION_ON
#pragma shader_feature _DEPTHOFFSET_ON
#pragma shader_feature _ _DOUBLESIDED_LIGHTING_FLIP _DOUBLESIDED_LIGHTING_MIRROR
#pragma shader_feature _ _DOUBLESIDED _DOUBLESIDED_LIGHTING_FLIP _DOUBLESIDED_LIGHTING_MIRROR
#pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature _MAPPING_TRIPLANAR

#pragma shader_feature _REQUIRE_UV2_OR_UV3
#pragma shader_feature _ _REQUIRE_UV2 _REQUIRE_UV3
#pragma shader_feature _EMISSIVE_COLOR
#pragma shader_feature _NORMALMAP

#include "common.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderConfig.cs.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderVariables.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Attributes.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/FragInputs.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPass.cs.hlsl"
//-------------------------------------------------------------------------------------

HLSLPROGRAM
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../Material/Material.hlsl"
#include "../../Material/Material.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL

HLSLPROGRAM
#define SHADERPASS SHADERPASS_DEBUG_VIEW_MATERIAL
#include "../../Material/Material.hlsl"
#include "../../Material/Material.hlsl"
#include "../../ShaderPass/ShaderPassDebugViewMaterial.hlsl"
ENDHLSL

#include "../../Material/Material.hlsl"
#include "ShaderPass/LitMetaPass.hlsl"
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassLightTransport.hlsl"
ENDHLSL

HLSLPROGRAM
#define SHADERPASS SHADERPASS_DEPTH_ONLY
#include "../../Material/Material.hlsl"
#include "../../Material/Material.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL

HLSLPROGRAM
#define SHADERPASS SHADERPASS_DEPTH_ONLY
#include "../../Material/Material.hlsl"
#include "../../Material/Material.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL

HLSLPROGRAM
#define SHADERPASS SHADERPASS_VELOCITY
#include "../../Material/Material.hlsl"
#include "../../Material/Material.hlsl"
#include "../../ShaderPass/ShaderPassVelocity.hlsl"
ENDHLSL

HLSLPROGRAM
#define SHADERPASS SHADERPASS_DISTORTION
#include "../../Material/Material.hlsl"
#include "../../Material/Material.hlsl"
#include "../../ShaderPass/ShaderPassDistortion.hlsl"
ENDHLSL

Cull [_CullMode]
HLSLPROGRAM
#include "../../Lighting/Forward.hlsl"
// #include "../../Lighting/Forward.hlsl"
//#pragma multi_compile SHADOWFILTERING_FIXED_SIZE_PCF
#include "../../Lighting/Lighting.hlsl"
#include "../../Lighting/Lighting.hlsl"
#include "../../ShaderPass/ShaderPassForward.hlsl"
ENDHLSL

479
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/LitData.hlsl


// Fill SurfaceData/Builtin data function
//-------------------------------------------------------------------------------------
#include "../MaterialUtilities.hlsl"
#include "../SampleLayer.hlsl"
void GetBuiltinData(FragInputs input, SurfaceData surfaceData, float alpha, float depthOffset, out BuiltinData builtinData)
{

builtinData.emissiveColor = float3(0.0, 0.0, 0.0);
#endif
builtinData.velocity = CalculateVelocity(input.positionCS, input.previousPositionCS);
builtinData.velocity = float2(0.0, 0.0);
#ifdef _DISTORTION_ON
float3 distortion = SAMPLE_TEXTURE2D(_DistortionVectorMap, sampler_DistortionVectorMap, input.texCoord0).rgb;

builtinData.depthOffset = depthOffset;
}
// Gather all kind of mapping in one struct, allow to improve code readability
struct LayerUV
{
float2 uv;
// triplanar
bool isTriplanar;
float2 uvYZ;
float2 uvZX;
float2 uvXY;
};
struct LayerTexCoord
{
#ifndef LAYERED_LIT_SHADER

float3 weights;
};
float4 SampleLayer(TEXTURE2D_ARGS(layerTex, layerSampler), LayerUV layerUV, float3 weights)
{
if (layerUV.isTriplanar)
{
float4 val = float4(0.0, 0.0, 0.0, 0.0);
if (weights.x > 0.0)
val += weights.x * SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uvYZ);
if (weights.y > 0.0)
val += weights.y * SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uvZX);
if (weights.z > 0.0)
val += weights.z * SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uvXY);
return val;
}
else
{
return SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uv);
}
}
// TODO: Handle BC5 format, currently this code is for DXT5nm
// THis function below must call UnpackNormalmapRGorAG
float3 SampleNormalLayer(TEXTURE2D_ARGS(layerTex, layerSampler), LayerUV layerUV, float3 weights, float scale)
{
if (layerUV.isTriplanar)
{
float3 val = float3(0.0, 0.0, 0.0);
if (weights.x > 0.0)
val += weights.x * UnpackNormalAG(SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uvYZ), scale);
if (weights.y > 0.0)
val += weights.y * UnpackNormalAG(SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uvZX), scale);
if (weights.z > 0.0)
val += weights.z * UnpackNormalAG(SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uvXY), scale);
return normalize(val);
}
else
{
return UnpackNormalAG(SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uv), scale);
}
}
// This version is for normalmap with AG encoding only (use with details map)
float3 SampleNormalLayerAG(TEXTURE2D_ARGS(layerTex, layerSampler), LayerUV layerUV, float3 weights, float scale)
{
if (layerUV.isTriplanar)
{
float3 val = float3(0.0, 0.0, 0.0);
if (weights.x > 0.0)
val += weights.x * UnpackNormalAG(SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uvYZ), scale);
if (weights.y > 0.0)
val += weights.y * UnpackNormalAG(SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uvZX), scale);
if (weights.z > 0.0)
val += weights.z * UnpackNormalAG(SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uvXY), scale);
return normalize(val);
}
else
{
return UnpackNormalAG(SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uv), scale);
}
}
// This version is for normalmap with RGB encoding only, i.e non encoding. It is necessary to use this abstraction to handle correctly triplanar
// plus consistent with the normal scale parameter
float3 SampleNormalLayerRGB(TEXTURE2D_ARGS(layerTex, layerSampler), LayerUV layerUV, float3 weights, float scale)
{
if (layerUV.isTriplanar)
{
float3 val = float3(0.0, 0.0, 0.0);
if (weights.x > 0.0)
val += weights.x * UnpackNormalRGB(SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uvYZ), scale);
if (weights.y > 0.0)
val += weights.y * UnpackNormalRGB(SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uvZX), scale);
if (weights.z > 0.0)
val += weights.z * UnpackNormalRGB(SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uvXY), scale);
return normalize(val);
}
else
{
return UnpackNormalRGB(SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV.uv), scale);
}
}
// Macro to improve readibility of surface data
#define SAMPLE_LAYER_TEXTURE2D(textureName, samplerName, coord) SampleLayer(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights)
#define SAMPLE_LAYER_NORMALMAP(textureName, samplerName, coord, scale) SampleNormalLayer(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, scale)
#define SAMPLE_LAYER_NORMALMAP_AG(textureName, samplerName, coord, scale) SampleNormalLayerAG(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, scale)
#define SAMPLE_LAYER_NORMALMAP_RGB(textureName, samplerName, coord, scale) SampleNormalLayerRGB(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, scale)
// Transforms 2D UV by scale/bias property
#define TRANSFORM_TEX(tex,name) ((tex.xy) * name##_ST.xy + name##_ST.zw)
// include LitDataInternal to define GetSurfaceData
#ifdef TESSELLATION_ON
#include "LitTessellation.hlsl"
#endif
void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs posInput, out SurfaceData surfaceData, out BuiltinData builtinData)
void GetLayerTexCoord(float2 texCoord0, float2 texCoord1, float2 texCoord2, float2 texCoord3,
float3 positionWS, float3 normalWS, out LayerTexCoord layerTexCoord)
LayerTexCoord layerTexCoord;
layerTexCoord.weights = ComputeTriplanarWeights(input.tangentToWorld[2].xyz);
layerTexCoord.weights = ComputeTriplanarWeights(normalWS);
#endif
// Be sure that the compiler is aware that we don't touch UV1 to UV3 for base layer in case of non layer shader

#ifdef _MAPPING_TRIPLANAR
isTriplanar = true;
#endif
ComputeLayerTexCoord(input, isTriplanar, layerTexCoord);
// Transform view vector in tangent space
ComputeLayerTexCoord( texCoord0, texCoord1, texCoord2, texCoord3,
positionWS, normalWS, isTriplanar, layerTexCoord);
}
void ApplyPerPixelDisplacement(FragInputs input, float3 V, inout LayerTexCoord layerTexCoord)
{
#if defined(_HEIGHTMAP) && defined(_PER_PIXEL_DISPLACEMENT)
// ref: https://www.gamedev.net/resources/_/technical/graphics-programming-and-theory/a-closer-look-at-parallax-occlusion-mapping-r3262
ApplyDisplacement(input, viewDirTS, layerTexCoord);
// Change the number of samples per ray depending on the viewing angle for the surface.
// Oblique angles require smaller step sizes to achieve more accurate precision for computing displacement.
int numSteps = (int)lerp(_PPDMaxSamples, _PPDMinSamples, viewDirTS.z);
ParallaxOcclusionMappingLayer(layerTexCoord, numSteps, viewDirTS);
// TODO: We are supposed to modify lightmaps coordinate (fetch in GetBuiltin), but this isn't the same uv mapping, so can't apply the offset here...
// Let's assume it will be "fine" as indirect diffuse is often low frequency
#endif
}
// Calculate displacement for per vertex displacement mapping
float ComputePerVertexDisplacement(LayerTexCoord layerTexCoord, float4 vertexColor, float lod)
{
return SampleHeightmapLod(layerTexCoord, lod);
}
void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs posInput, out SurfaceData surfaceData, out BuiltinData builtinData)
{
LayerTexCoord layerTexCoord;
GetLayerTexCoord(input.texCoord0, input.texCoord1, input.texCoord2, input.texCoord3,
input.positionWS, input.tangentToWorld[2].xyz, layerTexCoord);
ApplyPerPixelDisplacement(input, V, layerTexCoord);
ApplyDepthOffsetAttribute(depthOffset, input);
#endif
// We perform the conversion to world of the normalTS outside of the GetSurfaceData

surfaceData.normalWS = TransformTangentToWorld(normalTS, input.tangentToWorld);
surfaceData.tangentWS = input.tangentToWorld[0].xyz;
// NdotV should not be negative for visible pixels, but it can happen due to the
// perspective projection and the normal mapping + decals. In that case, the normal
// should be modified to become valid (i.e facing the camera) to avoid weird artifacts.
// Note: certain applications (e.g. SpeedTree) make use of double-sided lighting.
// This will potentially reduce the length of the normal at edges of geometry.
bool twoSided = false;
GetShiftedNdotV(surfaceData.normalWS, V, twoSided);
// Orthonormalize the basis vectors using the Gram-Schmidt process.
// We assume that the length of the surface normal is sufficiently close to 1.
surfaceData.tangentWS = normalize(surfaceData.tangentWS - dot(surfaceData.tangentWS, surfaceData.normalWS));
GetNormalAndTangentWS(input, V, normalTS, surfaceData.normalWS, surfaceData.tangentWS);
// Caution: surfaceData must be fully initialize before calling GetBuiltinData
GetBuiltinData(input, surfaceData, alpha, depthOffset, builtinData);

#define ADD_ZERO_IDX(Name) Name##0
// Generate function for all layer
// include LitDataInternal multiple time to define the variation of GetSurfaceData for each layer
#ifdef TESSELLATION_ON
#include "LitTessellation.hlsl" // Include only one time for layer 0
#endif
#undef LAYER_INDEX
#undef ADD_IDX

#undef LAYER_INDEX
#undef ADD_IDX
void ComputeMaskWeights(float3 inputMasks, out float outWeights[_MAX_LAYER])
void ComputeMaskWeights(float4 inputMasks, out float outWeights[_MAX_LAYER])
masks[0] = 1.0f; // Layer 0 is always full
#if defined(_DENSITY_MODE)
masks[0] = inputMasks.a;
#else
masks[0] = 1.0;
#endif
float left = 1.0f;
// Algorithm is like this:
// Top layer have priority on others layers
// If a top layer doesn't use the full weight, the remaining can be use by the following layer.
float weightsSum = 0.0;
for (int i = _LAYER_COUNT - 1; i > 0; --i)
for (int i = _LAYER_COUNT - 1; i >= 0; --i)
outWeights[i] = masks[i] * left;
left -= outWeights[i];
outWeights[i] = min(masks[i], (1.0 - weightsSum));
weightsSum = saturate(weightsSum + masks[i]);
outWeights[0] = left;
float3 BlendLayeredFloat3(float3 x0, float3 x1, float3 x2, float3 x3, float weight[4])
float3 BlendLayeredVector3(float3 x0, float3 x1, float3 x2, float3 x3, float weight[4])
{
float3 result = float3(0.0, 0.0, 0.0);

return result;
}
float ApplyHeightBasedBlend(inout float inputFactor, float previousLayerHeight, float layerHeight, float heightOffset, float heightFactor, float edgeBlendStrength, float vertexColor)
{
float finalLayerHeight = heightFactor * layerHeight + heightOffset + _VertexColorHeightFactor * (vertexColor * 2.0 - 1.0);
edgeBlendStrength = max(0.00001, edgeBlendStrength);
if (previousLayerHeight >= finalLayerHeight)
{
inputFactor = 0.0;
}
else if (finalLayerHeight > previousLayerHeight && finalLayerHeight < previousLayerHeight + edgeBlendStrength)
{
inputFactor = inputFactor * pow((finalLayerHeight - previousLayerHeight) / edgeBlendStrength, 0.5);
}
return max(finalLayerHeight, previousLayerHeight);
}
#define SURFACEDATA_BLEND_COLOR(surfaceData, name, mask) BlendLayeredFloat3(surfaceData##0.##name, surfaceData##1.##name, surfaceData##2.##name, surfaceData##3.##name, mask);
#define SURFACEDATA_BLEND_VECTOR3(surfaceData, name, mask) BlendLayeredVector3(surfaceData##0.##name, surfaceData##1.##name, surfaceData##2.##name, surfaceData##3.##name, mask);
void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs posInput, out SurfaceData surfaceData, out BuiltinData builtinData)
void GetLayerTexCoord(float2 texCoord0, float2 texCoord1, float2 texCoord2, float2 texCoord3,
float3 positionWS, float3 normalWS, out LayerTexCoord layerTexCoord)
LayerTexCoord layerTexCoord;
layerTexCoord.weights = ComputeTriplanarWeights(input.tangentToWorld[2].xyz);
layerTexCoord.weights = ComputeTriplanarWeights(normalWS);
#endif
bool isTriplanar = false;

ComputeLayerTexCoord0(input, isTriplanar, layerTexCoord);
ComputeLayerTexCoord0( texCoord0, texCoord1, texCoord2, texCoord3,
positionWS, normalWS, isTriplanar, layerTexCoord, _LayerTiling0);
ComputeLayerTexCoord1(input, isTriplanar, layerTexCoord);
ComputeLayerTexCoord1( texCoord0, texCoord1, texCoord2, texCoord3,
positionWS, normalWS, isTriplanar, layerTexCoord, _LayerTiling1);
ComputeLayerTexCoord2(input, isTriplanar, layerTexCoord);
ComputeLayerTexCoord2( texCoord0, texCoord1, texCoord2, texCoord3,
positionWS, normalWS, isTriplanar, layerTexCoord, _LayerTiling2);
ComputeLayerTexCoord3(input, isTriplanar, layerTexCoord);
ComputeLayerTexCoord3( texCoord0, texCoord1, texCoord2, texCoord3,
positionWS, normalWS, isTriplanar, layerTexCoord, _LayerTiling3);
}
// Transform view vector in tangent space
void ApplyPerPixelDisplacement(FragInputs input, float3 V, inout LayerTexCoord layerTexCoord)
{
#if defined(_HEIGHTMAP) && defined(_PER_PIXEL_DISPLACEMENT)
float height0 = ApplyDisplacement0(input, viewDirTS, layerTexCoord);
float height1 = ApplyDisplacement1(input, viewDirTS, layerTexCoord);
float height2 = ApplyDisplacement2(input, viewDirTS, layerTexCoord);
float height3 = ApplyDisplacement3(input, viewDirTS, layerTexCoord);
float depthOffset = 0.0;
int numSteps = (int)lerp(_PPDMaxSamples, _PPDMinSamples, viewDirTS.z);
ParallaxOcclusionMappingLayer0(layerTexCoord, numSteps, viewDirTS);
ParallaxOcclusionMappingLayer1(layerTexCoord, numSteps, viewDirTS);
ParallaxOcclusionMappingLayer2(layerTexCoord, numSteps, viewDirTS);
ParallaxOcclusionMappingLayer3(layerTexCoord, numSteps, viewDirTS);
#endif
}
float3 ComputeMainNormalInfluence(FragInputs input, float3 normalTS0, float3 normalTS1, float3 normalTS2, float3 normalTS3, LayerTexCoord layerTexCoord, float weights[_MAX_LAYER])
{
// Get our regular normal from regular layering
float3 normalTS = BlendLayeredVector3(normalTS0, normalTS1, normalTS2, normalTS3, weights);
// THen get Main Layer Normal influence factor. Main layer is 0 because it can't be influence. In this case the final lerp return normalTS.
float influenceFactor = BlendLayeredScalar(0.0, _InheritBaseNormal1, _InheritBaseNormal2, _InheritBaseNormal3, weights);
// We will add smoothly the contribution of the normal map by using lower mips with help of bias sampling. InfluenceFactor must be [0..numMips] // Caution it cause banding...
// Note: that we don't take details map into account here.
float maxMipBias = log2(max(_NormalMap0_TexelSize.z, _NormalMap0_TexelSize.w)); // don't do + 1 as it is for bias, not lod
float3 mainNormalTS = GetNormalTS0(input, layerTexCoord, float3(0.0, 0.0, 1.0), 0.0, true, maxMipBias * (1.0 - influenceFactor));
// Add on our regular normal a bit of Main Layer normal base on influence factor. Note that this affect only the "visible" normal.
return lerp(normalTS, BlendNormalRNM(normalTS, mainNormalTS), influenceFactor);
}
float3 ComputeMainBaseColorInfluence(float3 baseColor0, float3 baseColor1, float3 baseColor2, float3 baseColor3, float compoMask, LayerTexCoord layerTexCoord, float weights[_MAX_LAYER])
{
float3 baseColor = BlendLayeredVector3(baseColor0, baseColor1, baseColor2, baseColor3, weights);
float influenceFactor = BlendLayeredScalar(0.0, _InheritBaseColor1, _InheritBaseColor2, _InheritBaseColor3, weights);
float influenceThreshold = BlendLayeredScalar(1.0, _InheritBaseColorThreshold1, _InheritBaseColorThreshold2, _InheritBaseColorThreshold3, weights);
influenceFactor = influenceFactor * (1.0 - saturate(compoMask / influenceThreshold));
// We want to calculate the mean color of the texture. For this we will sample a low mipmap
float textureBias = 15.0; // Use maximum bias
float3 baseMeanColor0 = SAMPLE_LAYER_TEXTURE2D_BIAS(_BaseColorMap0, sampler_BaseColorMap0, layerTexCoord.base0, textureBias).rgb *_BaseColor0.rgb;
float3 baseMeanColor1 = SAMPLE_LAYER_TEXTURE2D_BIAS(_BaseColorMap1, sampler_BaseColorMap0, layerTexCoord.base1, textureBias).rgb *_BaseColor1.rgb;
float3 baseMeanColor2 = SAMPLE_LAYER_TEXTURE2D_BIAS(_BaseColorMap2, sampler_BaseColorMap0, layerTexCoord.base2, textureBias).rgb *_BaseColor2.rgb;
float3 baseMeanColor3 = SAMPLE_LAYER_TEXTURE2D_BIAS(_BaseColorMap3, sampler_BaseColorMap0, layerTexCoord.base3, textureBias).rgb *_BaseColor3.rgb;
float3 meanColor = BlendLayeredVector3(baseMeanColor0, baseMeanColor1, baseMeanColor2, baseMeanColor3, weights);
// If we inherit from base layer, we will add a bit of it
// We add variance of current visible level and the base color 0 or mean (to retrieve initial color) depends on influence
// (baseColor - meanColor) + lerp(meanColor, baseColor0, inheritBaseColor) simplify to
return saturate(influenceFactor * (baseColor0 - meanColor) + baseColor);
}
// Caution: Blend mask are Layer 1 R - Layer 2 G - Layer 3 B - Main Layer A
float4 GetBlendMask(LayerTexCoord layerTexCoord, float4 vertexColor, bool useLodSampling = false, float lod = 0)
{
// Caution:
// Blend mask are Main Layer A - Layer 1 R - Layer 2 G - Layer 3 B
// Value for Mani layer is not use for blending itself but for alternate weighting like density.
// Settings this specific Main layer blend mask in alpha allow to be transparent in case we don't use it and 1 is provide by default.
float4 blendMasks = useLodSampling ? SAMPLE_LAYER_TEXTURE2D_LOD(_LayerMaskMap, sampler_LayerMaskMap, layerTexCoord.base0, lod) : SAMPLE_LAYER_TEXTURE2D(_LayerMaskMap, sampler_LayerMaskMap, layerTexCoord.base0);
#if defined(_LAYER_MASK_VERTEX_COLOR_MUL)
blendMasks *= vertexColor;
#elif defined(_LAYER_MASK_VERTEX_COLOR_ADD)
blendMasks = saturate(blendMasks + vertexColor * 2.0 - 1.0);
#endif
return blendMasks;
}
// Calculate displacement for per vertex displacement mapping
float ComputePerVertexDisplacement(LayerTexCoord layerTexCoord, float4 vertexColor, float lod)
{
float4 blendMasks = GetBlendMask(layerTexCoord, vertexColor, true, lod);
float weights[_MAX_LAYER];
ComputeMaskWeights(blendMasks, weights);
float height0 = SampleHeightmapLod0(layerTexCoord, lod, _HeightCenterOffset0, _HeightFactor0);
float height1 = SampleHeightmapLod1(layerTexCoord, lod, _HeightCenterOffset1, _HeightFactor1);
float height2 = SampleHeightmapLod2(layerTexCoord, lod, _HeightCenterOffset2, _HeightFactor2);
float height3 = SampleHeightmapLod3(layerTexCoord, lod, _HeightCenterOffset3, _HeightFactor3);
float heightResult = BlendLayeredScalar(height0, height1, height2, height3, weights);
#if defined(_MAIN_LAYER_INFLUENCE_MODE)
// Think that inheritbasedheight will be 0 if height0 is fully visible in weights. So there is no double contribution of height0
float inheritBaseHeight = BlendLayeredScalar(0.0, _InheritBaseHeight1, _InheritBaseHeight2, _InheritBaseHeight3, weights);
return heightResult + height0 * inheritBaseHeight;
#endif
return heightResult;
}
float3 ApplyHeightBasedBlend(float3 inputMask, float3 inputHeight, float3 blendUsingHeight)
{
return saturate(lerp(inputMask * inputHeight * blendUsingHeight * 100, 1, inputMask * inputMask)); // 100 arbitrary scale to limit blendUsingHeight values.
}
// Calculate weights to apply to each layer
// Caution: This function must not be use for per vertex of per pixel displacement, there is a dedicated function for them.
// this function handle triplanar
void ComputeLayerWeights(FragInputs input, LayerTexCoord layerTexCoord, float4 inputAlphaMask, out float outWeights[_MAX_LAYER])
{
float4 blendMasks = GetBlendMask(layerTexCoord, input.color);
#if defined(_DENSITY_MODE)
// Note: blendMasks.argb because a is main layer
float4 minOpaParam = float4(_MinimumOpacity0, _MinimumOpacity1, _MinimumOpacity2, _MinimumOpacity3);
float4 remapedOpacity = lerp(minOpaParam, float4(1.0, 1.0, 1.0, 1.0), inputAlphaMask); // Remap opacity mask from [0..1] to [minOpa..1]
float4 opacityAsDensity = saturate((inputAlphaMask - (float4(1.0, 1.0, 1.0, 1.0) - blendMasks.argb)) * 20.0);
float4 useOpacityAsDensityParam = float4(_OpacityAsDensity0, _OpacityAsDensity1, _OpacityAsDensity2, _OpacityAsDensity3);
blendMasks.argb = lerp(blendMasks.argb * remapedOpacity, opacityAsDensity, useOpacityAsDensityParam);
#endif
#if defined(_HEIGHT_BASED_BLEND)
float height0 = SampleHeightmap0(layerTexCoord, _HeightCenterOffset0, _HeightFactor0);
float height1 = SampleHeightmap1(layerTexCoord, _HeightCenterOffset1, _HeightFactor1);
float height2 = SampleHeightmap2(layerTexCoord, _HeightCenterOffset2, _HeightFactor2);
float height3 = SampleHeightmap3(layerTexCoord, _HeightCenterOffset3, _HeightFactor3);
float4 heights = float4(height0, height1, height2, height3);
// HACK, use height0 to avoid compiler error for unused sampler
// To remove once we have POM
heights.y += (heights.x * 0.0001);
// don't apply on main layer
blendMasks.rgb = ApplyHeightBasedBlend(blendMasks.rgb, heights.yzw, float3(_BlendUsingHeight1, _BlendUsingHeight2, _BlendUsingHeight3));
#endif
ComputeMaskWeights(blendMasks, outWeights);
}
void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs posInput, out SurfaceData surfaceData, out BuiltinData builtinData)
{
LayerTexCoord layerTexCoord;
GetLayerTexCoord(input.texCoord0, input.texCoord1, input.texCoord2, input.texCoord3,
input.positionWS, input.tangentToWorld[2].xyz, layerTexCoord);
ApplyPerPixelDisplacement(input, V, layerTexCoord);
float depthOffset = 0.0;
ApplyDepthOffsetAttribute(depthOffset, input);
SurfaceData surfaceData0;
SurfaceData surfaceData1;
SurfaceData surfaceData2;
SurfaceData surfaceData3;
float3 normalTS0;
float3 normalTS1;
float3 normalTS2;
float3 normalTS3;
SurfaceData surfaceData0, surfaceData1, surfaceData2, surfaceData3;
float3 normalTS0, normalTS1, normalTS2, normalTS3;
// Mask Values : Layer 1, 2, 3 are r, g, b
float3 maskValues = SAMPLE_TEXTURE2D(_LayerMaskMap, sampler_LayerMaskMap, input.texCoord0).rgb;
// Mutually exclusive with _HEIGHT_BASED_BLEND
#if defined(_LAYER_MASK_VERTEX_COLOR_MUL) // Used when no layer mask is set
maskValues *= input.vertexColor.rgb;
#elif defined(_LAYER_MASK_VERTEX_COLOR_ADD) // When layer mask is set, color is additive to enable user to override it.
maskValues = saturate(maskValues + input.vertexColor.rgb * 2.0 - 1.0);
// For layering we kill pixel based on maximun alpha
#ifdef _ALPHATEST_ON
#if _LAYER_COUNT == 2
clip(max(alpha0, alpha1) - _AlphaCutoff);
#endif
#if _LAYER_COUNT == 3
clip(max3(alpha0, alpha1, alpha2) - _AlphaCutoff);
#endif
#if _LAYER_COUNT == 4
clip(max(alpha3, max3(alpha0, alpha1, alpha2)) - _AlphaCutoff);
#if defined(_HEIGHT_BASED_BLEND)
float baseLayerHeight = height0;
baseLayerHeight = ApplyHeightBasedBlend(maskValues.r, baseLayerHeight, height1, _HeightOffset1, _HeightFactor1, _BlendSize1, input.vertexColor.r);
baseLayerHeight = ApplyHeightBasedBlend(maskValues.g, baseLayerHeight, height2, _HeightOffset2 + _HeightOffset1, _HeightFactor2, _BlendSize2, input.vertexColor.g);
ApplyHeightBasedBlend(maskValues.b, baseLayerHeight, height3, _HeightOffset3 + _HeightOffset2 + _HeightOffset1, _HeightFactor3, _BlendSize3, input.vertexColor.b);
ComputeMaskWeights(maskValues, weights);
ComputeLayerWeights(input, layerTexCoord, float4(alpha0, alpha1, alpha2, alpha3), weights);
// For layered shader, alpha of base color is used as either an opacity mask, a composition mask for inheritance parameters or a density mask.
float alpha = PROP_BLEND_SCALAR(alpha, weights);
surfaceData.baseColor = SURFACEDATA_BLEND_COLOR(surfaceData, baseColor, weights);
#if defined(_MAIN_LAYER_INFLUENCE_MODE)
surfaceData.baseColor = ComputeMainBaseColorInfluence(surfaceData0.baseColor, surfaceData1.baseColor, surfaceData2.baseColor, surfaceData3.baseColor, alpha, layerTexCoord, weights);
float3 normalTS = ComputeMainNormalInfluence(input, normalTS0, normalTS1, normalTS2, normalTS3, layerTexCoord, weights);
#else
surfaceData.baseColor = SURFACEDATA_BLEND_VECTOR3(surfaceData, baseColor, weights);
float3 normalTS = BlendLayeredVector3(normalTS0, normalTS1, normalTS2, normalTS3, weights);
#endif
float3 normalTS;
#if defined(_HEIGHT_BASED_BLEND)
float _InheritBaseLayer0 = 1.0f; // Default value for lerp when all weights but base layer are zero.
// Compute the combined inheritance factor of layers 1,2 and 3
float inheritFactor = PROP_BLEND_SCALAR(_InheritBaseLayer, weights);
float3 vertexNormalTS = float3(0.0, 0.0, 1.0);
// The idea here is to lerp toward vertex normal. This way when we don't want to inherit, we will combine layer 1/2/3 normal with a vertex normal which is neutral.
float3 baseLayerNormalTS = normalize(lerp(vertexNormalTS, normalTS0, inheritFactor));
// Blend layer 1/2/3 normals before combining to the base layer. Again we need to have a neutral value for base layer (vertex normal) in case all weights are zero.
float3 layersNormalTS = BlendLayeredFloat3(vertexNormalTS, normalTS1, normalTS2, normalTS3, weights);
normalTS = BlendNormalRNM(baseLayerNormalTS, layersNormalTS);
#else
normalTS = BlendLayeredFloat3(normalTS0, normalTS1, normalTS2, normalTS3, weights);
#endif
surfaceData.normalWS = TransformTangentToWorld(normalTS, input.tangentToWorld);
surfaceData.tangentWS = input.tangentToWorld[0].xyz;
// NdotV should not be negative for visible pixels, but it can happen due to the
// perspective projection and the normal mapping + decals. In that case, the normal
// should be modified to become valid (i.e facing the camera) to avoid weird artifacts.
// Note: certain applications (e.g. SpeedTree) make use of double-sided lighting.
// This will potentially reduce the length of the normal at edges of geometry.
bool twoSided = false;
GetShiftedNdotV(surfaceData.normalWS, V, twoSided);
// Orthonormalize the basis vectors using the Gram-Schmidt process.
// We assume that the length of the surface normal is sufficiently close to 1.
surfaceData.tangentWS = normalize(surfaceData.tangentWS - dot(surfaceData.tangentWS, surfaceData.normalWS));
surfaceData.tangentWS = normalize(input.tangentToWorld[0].xyz);
surfaceData.materialId = 0;
surfaceData.anisotropy = 0;
surfaceData.specular = 0.04;

surfaceData.coatPerceptualSmoothness = 1.0;
surfaceData.specularColor = float3(0.0, 0.0, 0.0);
float alpha = PROP_BLEND_SCALAR(alpha, weights);
GetNormalAndTangentWS(input, V, normalTS, surfaceData.normalWS, surfaceData.tangentWS);
#ifdef TESSELLATION_ON
#include "LitTessellation.hlsl" // Must be after GetLayerTexCoord() declaration
#endif

260
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/LitDataInternal.hlsl


void ADD_IDX(ComputeLayerTexCoord)(FragInputs input, bool isTriplanar, inout LayerTexCoord layerTexCoord)
void ADD_IDX(ComputeLayerTexCoord)( float2 texCoord0, float2 texCoord1, float2 texCoord2, float2 texCoord3,
float3 positionWS, float3 normalWS, bool isTriplanar, inout LayerTexCoord layerTexCoord, float additionalTiling = 1.0)
float2 uvBase = ADD_IDX(_UVMappingMask).x * input.texCoord0 +
ADD_IDX(_UVMappingMask).y * input.texCoord1 +
ADD_IDX(_UVMappingMask).z * input.texCoord2 +
ADD_IDX(_UVMappingMask).w * input.texCoord3;
float2 uvBase = ADD_IDX(_UVMappingMask).x * texCoord0 +
ADD_IDX(_UVMappingMask).y * texCoord1 +
ADD_IDX(_UVMappingMask).z * texCoord2 +
ADD_IDX(_UVMappingMask).w * texCoord3;
uvBase *= additionalTiling.xx;
float2 uvDetails = ADD_IDX(_UVDetailsMappingMask).x * input.texCoord0 +
ADD_IDX(_UVDetailsMappingMask).y * input.texCoord1 +
ADD_IDX(_UVDetailsMappingMask).z * input.texCoord2 +
ADD_IDX(_UVDetailsMappingMask).w * input.texCoord3;
float2 uvDetails = ADD_IDX(_UVDetailsMappingMask).x * texCoord0 +
ADD_IDX(_UVDetailsMappingMask).y * texCoord1 +
ADD_IDX(_UVDetailsMappingMask).z * texCoord2 +
ADD_IDX(_UVDetailsMappingMask).w * texCoord3;
//float3 position = localTriplanar ? TransformWorldToObject(input.positionWS) : input.positionWS;
float3 position = input.positionWS;
//float3 position = localTriplanar ? TransformWorldToObject(positionWS) : positionWS;
float3 position = positionWS;
position *= ADD_IDX(_TexWorldScale);
if (ADD_IDX(_UVMappingPlanar) > 0.0)

// triplanar
ADD_IDX(layerTexCoord.base).isTriplanar = isTriplanar;
float3 direction = sign(input.tangentToWorld[2].xyz);
float3 direction = sign(normalWS);
// In triplanar, if we are facing away from the world axis, a different axis will be flipped for each direction.
// This is particularly problematic for tangent space normal maps which need to be in the right direction.

ADD_IDX(layerTexCoord.details).uvXY = TRANSFORM_TEX(uvXY, ADD_IDX(_DetailMap));
}
float ADD_IDX(ApplyDisplacement)(inout FragInputs input, float3 viewDirTS, inout LayerTexCoord layerTexCoord)
float ADD_IDX(SampleHeightmap)(LayerTexCoord layerTexCoord, float centerOffset = 0.0, float multiplier = 1.0)
float height = 0.0f;
#ifdef _HEIGHTMAP
return (SAMPLE_LAYER_TEXTURE2D(ADD_IDX(_HeightMap), ADD_ZERO_IDX(sampler_HeightMap), ADD_IDX(layerTexCoord.base)).r - ADD_IDX(_HeightCenter) - centerOffset) * ADD_IDX(_HeightAmplitude) * multiplier;
#else
return 0.0;
#endif
}
float ADD_IDX(SampleHeightmapLod)(LayerTexCoord layerTexCoord, float lod, float centerOffset = 0.0, float multiplier = 1.0)
{
height = (SAMPLE_LAYER_TEXTURE2D(ADD_IDX(_HeightMap), ADD_ZERO_IDX(sampler_HeightMap), ADD_IDX(layerTexCoord.base)).r - ADD_IDX(_HeightCenter)) * ADD_IDX(_HeightAmplitude);
return (SAMPLE_LAYER_TEXTURE2D_LOD(ADD_IDX(_HeightMap), ADD_ZERO_IDX(sampler_HeightMap), ADD_IDX(layerTexCoord.base), lod).r - ADD_IDX(_HeightCenter) - centerOffset) * ADD_IDX(_HeightAmplitude) * multiplier;
#else
return 0.0;
#endif
}
//#ifdef _PER_PIXEL_DISPLACEMENT
// //height = SAMPLE_LAYER_TEXTURE2D(ADD_IDX(_HeightMap), ADD_ZERO_IDX(sampler_HeightMap), ADD_IDX(layerTexCoord.base)).r * ADD_IDX(_HeightScale) + ADD_IDX(_HeightBias);
// float2 offset = ParallaxOffset(viewDirTS, height);
// Note: The sampling of heightmap inside POM don't use sampling abstraction (with triplanar) as
// POM must be apply separately for each uv set (so 3 time for triplanar)
void ADD_IDX(ParallaxOcclusionMappingLayer)(inout LayerTexCoord layerTexCoord, int numSteps, float3 viewDirTS)
{
// Convention: 1.0 is top, 0.0 is bottom - POM is always inward, no extrusion
float stepSize = 1.0 / (float)numSteps;
// ADD_IDX(layerTexCoord.base).uv += offset;
// ADD_IDX(layerTexCoord.base).uvYZ += offset;
// ADD_IDX(layerTexCoord.base).uvZX += offset;
// ADD_IDX(layerTexCoord.base).uvXY += offset;
// View vector is from the point to the camera, but we want to raymarch from camera to point, so reverse the sign
// The length of viewDirTS vector determines the furthest amount of displacement:
// float parallaxLimit = -length(viewDirTS.xy) / viewDirTS.z;
// float2 parallaxDir = normalize(Out.viewDirTS.xy);
// float2 parallaxMaxOffsetTS = parallaxDir * parallaxLimit;
// Above code simplify to
float2 parallaxMaxOffsetTS = (viewDirTS.xy / -viewDirTS.z) * ADD_IDX(_HeightAmplitude);
float2 texOffsetPerStep = stepSize * parallaxMaxOffsetTS;
// ADD_IDX(layerTexCoord.details).uv += offset;
// ADD_IDX(layerTexCoord.details).uvYZ += offset;
// ADD_IDX(layerTexCoord.details).uvZX += offset;
// ADD_IDX(layerTexCoord.details).uvXY += offset;
float2 uv = ADD_IDX(layerTexCoord.base).uv;
// Compute lod as we will sample inside a loop (so can't use regular sampling)
// It appear that CALCULATE_TEXTURE2D_LOD only return interger lod. We want to use float lod to have smoother transition and fading
// float lod = CALCULATE_TEXTURE2D_LOD(ADD_IDX(_HeightMap), ADD_ZERO_IDX(sampler_HeightMap), uv);
float lod = ComputeTextureLOD(uv, GET_TEXELSIZE_NAME(ADD_IDX(_HeightMap)));
// Do a first step before the loop to init all value correctly
float2 texOffsetCurrent = 0;
float prevHeight = SAMPLE_TEXTURE2D_LOD(ADD_IDX(_HeightMap), ADD_ZERO_IDX(sampler_HeightMap), uv + texOffsetCurrent, lod).r;
texOffsetCurrent += texOffsetPerStep;
float currHeight = SAMPLE_TEXTURE2D_LOD(ADD_IDX(_HeightMap), ADD_ZERO_IDX(sampler_HeightMap), uv + texOffsetCurrent, lod).r;
float rayHeight = 1.0 - stepSize; // Start at top less one sample
// Linear search
for (int stepIndex = 0; stepIndex < numSteps; ++stepIndex)
{
// Have we found a height below our ray height ? then we have an intersection
if (currHeight > rayHeight)
break; // end the loop
prevHeight = currHeight;
rayHeight -= stepSize;
texOffsetCurrent += texOffsetPerStep;
// Sample height map which in this case is stored in the alpha channel of the normal map:
currHeight = SAMPLE_TEXTURE2D_LOD(ADD_IDX(_HeightMap), ADD_ZERO_IDX(sampler_HeightMap), uv + texOffsetCurrent, lod).r;
}
// Found below and above points, now perform line interesection (ray) with piecewise linear heightfield approximation
// Refine the search by adding few extra intersection
#define POM_REFINE 1
#if POM_REFINE
// // Only modify texcoord for first layer, this will be use by for builtin data (like lightmap)
// if (LAYER_INDEX == 0)
// {
// input.texCoord0 += offset;
// input.texCoord1 += offset;
// input.texCoord2 += offset;
// input.texCoord3 += offset;
// }
float pt0 = rayHeight + stepSize;
float pt1 = rayHeight;
float delta0 = pt0 - prevHeight;
float delta1 = pt1 - currHeight;
// // Need to refetch for the right parallaxed height for layer blending to behave correctly...
// height = SAMPLE_LAYER_TEXTURE2D(ADD_IDX(_HeightMap), ADD_ZERO_IDX(sampler_HeightMap), ADD_IDX(layerTexCoord.base)).r * ADD_IDX(_HeightScale) + ADD_IDX(_HeightBias);
float2 offset = float2(0.0, 0.0);
// #endif
float threshold = 1.0;
for (int i = 0; i < 5; ++i)
{
float t = (pt0 * delta1 - pt1 * delta0) / (delta1 - delta0);
offset = (1 - t) * texOffsetPerStep * numSteps;
currHeight = SAMPLE_TEXTURE2D_LOD(ADD_IDX(_HeightMap), ADD_ZERO_IDX(sampler_HeightMap), uv + offset, lod).r;
threshold = t - currHeight;
if (abs(threshold) <= 0.01)
break;
if (threshold < 0.0)
{
delta1 = threshold;
pt1 = t;
}
else
{
delta0 = threshold;
pt0 = t;
}
}
#else
//float pt0 = rayHeight + stepSize;
//float pt1 = rayHeight;
//float delta0 = pt0 - prevHeight;
//float delta1 = pt1 - currHeight;
//float t = (pt0 * delta1 - pt1 * delta0) / (delta1 - delta0);
//float2 offset = (1 - t) * texOffsetPerStep * numSteps;
// A bit more optimize
float delta0 = currHeight - rayHeight;
float delta1 = (rayHeight + stepSize) - prevHeight;
float ratio = delta0 / (delta0 + delta1);
float2 offset = texOffsetCurrent - ratio * texOffsetPerStep;
return height;
// TODO: expose LOD fading
//float lodThreshold = 0.0;
//offset *= (1.0 - saturate(lod - lodThreshold));
// Apply offset only on base. Details could use another mapping and will not be consistant...
// Don't know if this will still ok.
// TODO: check with artists
ADD_IDX(layerTexCoord.base).uv += offset;
}
float3 ADD_IDX(GetNormalTS)(FragInputs input, LayerTexCoord layerTexCoord, float3 detailNormalTS, float detailMask, bool useBias, float bias)
{
float3 normalTS;
#ifdef _NORMALMAP
#ifdef _NORMALMAP_TANGENT_SPACE
if (useBias)
{
normalTS = SAMPLE_LAYER_NORMALMAP_BIAS(ADD_IDX(_NormalMap), ADD_ZERO_IDX(sampler_NormalMap), ADD_IDX(layerTexCoord.base), ADD_IDX(_NormalScale), bias);
}
else
{
normalTS = SAMPLE_LAYER_NORMALMAP(ADD_IDX(_NormalMap), ADD_ZERO_IDX(sampler_NormalMap), ADD_IDX(layerTexCoord.base), ADD_IDX(_NormalScale));
}
#else // Object space
// to be able to combine object space normal with detail map we transform it to tangent space (object space normal composition is not simple).
// then later we will re-transform it to world space.
if (useBias)
{
float3 normalOS = SAMPLE_LAYER_NORMALMAP_RGB_BIAS(ADD_IDX(_NormalMap), ADD_ZERO_IDX(sampler_NormalMap), ADD_IDX(layerTexCoord.base), ADD_IDX(_NormalScale), bias).rgb;
normalTS = TransformObjectToTangent(normalOS, input.tangentToWorld);
}
else
{
float3 normalOS = SAMPLE_LAYER_NORMALMAP_RGB(ADD_IDX(_NormalMap), ADD_ZERO_IDX(sampler_NormalMap), ADD_IDX(layerTexCoord.base), ADD_IDX(_NormalScale)).rgb;
normalTS = TransformObjectToTangent(normalOS, input.tangentToWorld);
}
#endif
#ifdef _DETAIL_MAP
normalTS = lerp(normalTS, BlendNormalRNM(normalTS, detailNormalTS), detailMask);
#endif
#else
normalTS = float3(0.0, 0.0, 1.0);
#endif
#if defined(_DOUBLESIDED_LIGHTING_FLIP) || defined(_DOUBLESIDED_LIGHTING_MIRROR)
#ifdef _DOUBLESIDED_LIGHTING_FLIP
float3 oppositeNormalTS = -normalTS;
#else
// Mirror the normal with the plane define by vertex normal
float3 oppositeNormalTS = reflect(normalTS, float3(0.0, 0.0, 1.0)); // Reflect around vertex normal (in tangent space this is z)
#endif
// TODO : Test if GetOddNegativeScale() is necessary here in case of normal map, as GetOddNegativeScale is take into account in CreateTangentToWorld();
normalTS = input.isFrontFace ?
(GetOddNegativeScale() >= 0.0 ? normalTS : oppositeNormalTS) :
(-GetOddNegativeScale() >= 0.0 ? normalTS : oppositeNormalTS);
#endif
return normalTS;
}
// Return opacity

#endif
// Perform alha test very early to save performance (a killed pixel will not sample textures)
#ifdef _ALPHATEST_ON
#if defined(_ALPHATEST_ON) && !defined(LAYERED_LIT_SHADER)
float3 detailNormalTS = float3(0.0, 0.0, 0.0);
float detailMask = 0.0;
float detailMask = SAMPLE_LAYER_TEXTURE2D(ADD_IDX(_DetailMask), ADD_ZERO_IDX(sampler_DetailMask), ADD_IDX(layerTexCoord.base)).b;
detailMask = SAMPLE_LAYER_TEXTURE2D(ADD_IDX(_DetailMask), ADD_ZERO_IDX(sampler_DetailMask), ADD_IDX(layerTexCoord.base)).g;
float2 detailAlbedoAndSmoothness = SAMPLE_LAYER_TEXTURE2D(ADD_IDX(_DetailMap), ADD_ZERO_IDX(sampler_DetailMap), ADD_IDX(layerTexCoord.details)).rb;
float detailAlbedo = detailAlbedoAndSmoothness.r;
float detailSmoothness = detailAlbedoAndSmoothness.g;

float3 detailNormalTS = SAMPLE_LAYER_NORMALMAP_AG(ADD_IDX(_DetailMap), ADD_ZERO_IDX(sampler_DetailMap), ADD_IDX(layerTexCoord.details), ADD_ZERO_IDX(_DetailNormalScale));
detailNormalTS = SAMPLE_LAYER_NORMALMAP_AG(ADD_IDX(_DetailMap), ADD_ZERO_IDX(sampler_DetailMap), ADD_IDX(layerTexCoord.details), ADD_ZERO_IDX(_DetailNormalScale));
float3 detailNormalTS = float3(0.0, 0.0, 1.0);
detailNormalTS = float3(0.0, 0.0, 1.0);
//float detailAO = detail.b;
#endif
#endif

surfaceData.normalWS = float3(0.0, 0.0, 0.0); // Need to init this so that the compiler leaves us alone.
// TODO: think about using BC5
#ifdef _NORMALMAP
#ifdef _NORMALMAP_TANGENT_SPACE
normalTS = SAMPLE_LAYER_NORMALMAP(ADD_IDX(_NormalMap), ADD_ZERO_IDX(sampler_NormalMap), ADD_IDX(layerTexCoord.base), ADD_ZERO_IDX(_NormalScale));
#else // Object space
float3 normalOS = SAMPLE_LAYER_NORMALMAP_RGB(ADD_IDX(_NormalMap), ADD_ZERO_IDX(sampler_NormalMap), ADD_IDX(layerTexCoord.base), ADD_ZERO_IDX(_NormalScale)).rgb;
normalTS = TransformObjectToTangent(normalOS, input.tangentToWorld);
#endif
#ifdef _DETAIL_MAP
normalTS = lerp(normalTS, BlendNormalRNM(normalTS, detailNormalTS), detailMask);
#endif
#else
normalTS = float3(0.0, 0.0, 1.0);
#endif
#if defined(_DOUBLESIDED_LIGHTING_FLIP) || defined(_DOUBLESIDED_LIGHTING_MIRROR)
#ifdef _DOUBLESIDED_LIGHTING_FLIP
float3 oppositeNormalTS = -normalTS;
#else
// Mirror the normal with the plane define by vertex normal
float3 oppositeNormalTS = reflect(normalTS, float3(0.0, 0.0, 1.0)); // Reflect around vertex normal (in tangent space this is z)
#endif
// TODO : Test if GetOddNegativeScale() is necessary here in case of normal map, as GetOddNegativeScale is take into account in CreateTangentToWorld();
normalTS = input.isFrontFace ?
(GetOddNegativeScale() >= 0.0 ? normalTS : oppositeNormalTS) :
(-GetOddNegativeScale() >= 0.0 ? normalTS : oppositeNormalTS);
#endif
normalTS = ADD_IDX(GetNormalTS)(input, layerTexCoord, detailNormalTS, detailMask, false, 0.0);
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
surfaceData.perceptualSmoothness = SAMPLE_LAYER_TEXTURE2D(ADD_IDX(_BaseColorMap), ADD_ZERO_IDX(sampler_BaseColorMap), ADD_IDX(layerTexCoord.base)).a;

// TODO: Is there anything todo regarding flip normal but for the tangent ?
#ifdef _ANISOTROPYMAP
surfaceData.anisotropy = SAMPLE_LAYER_TEXTURE2D(ADD_IDX(_AnisotropyMap), ADD_ZERO_IDX(sampler_AnisotropyMap), ADD_IDX(layerTexCoord.base)).g;
surfaceData.anisotropy = SAMPLE_LAYER_TEXTURE2D(ADD_IDX(_AnisotropyMap), ADD_ZERO_IDX(sampler_AnisotropyMap), ADD_IDX(layerTexCoord.base)).b;
#else
surfaceData.anisotropy = 1.0;
#endif

48
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/LitProperties.hlsl


TEXTURE2D(_HeightMap);
SAMPLER2D(sampler_HeightMap);
float4 _HeightMap_TexelSize; // Unity facility. This will provide the size of the heightmap to the shader
float _HeightAmplitude;
float _HeightCenter;

float4 _UVMappingMask;
float4 _UVDetailsMappingMask;
float _PPDMaxSamples;
float _PPDMinSamples;
#else // LAYERED_LIT_SHADER
// Set of users variables

PROP_DECL_TEX2D(_NormalMap);
PROP_DECL(float, _NormalScale);
float4 _NormalMap0_TexelSize; // Unity facility. This will provide the size of the base normal to the shader
float4 _HeightMap0_TexelSize;
float4 _HeightMap1_TexelSize;
float4 _HeightMap2_TexelSize;
float4 _HeightMap3_TexelSize;
PROP_DECL_TEX2D(_DetailMask);
PROP_DECL_TEX2D(_DetailMap);

TEXTURE2D(_LayerMaskMap);
SAMPLER2D(sampler_LayerMaskMap);
float _HeightOffset1;
float _HeightOffset2;
float _HeightOffset3;
float _HeightFactor1;
float _HeightFactor2;
float _HeightFactor3;
float _BlendSize1;
float _BlendSize2;
float _BlendSize3;
float _VertexColorHeightFactor;
float _InheritBaseLayer1;
float _InheritBaseLayer2;
float _InheritBaseLayer3;
float _BlendUsingHeight1;
float _BlendUsingHeight2;
float _BlendUsingHeight3;
PROP_DECL(float, _HeightFactor);
PROP_DECL(float, _HeightCenterOffset);
PROP_DECL(float, _MinimumOpacity);
PROP_DECL(float, _OpacityAsDensity);
float _InheritBaseNormal1;
float _InheritBaseNormal2;
float _InheritBaseNormal3;
float _InheritBaseHeight1;
float _InheritBaseHeight2;
float _InheritBaseHeight3;
float _InheritBaseColor1;
float _InheritBaseColor2;
float _InheritBaseColor3;
float _InheritBaseColorThreshold1;
float _InheritBaseColorThreshold2;
float _InheritBaseColorThreshold3;
PROP_DECL(float, _LayerTiling);
float3 _EmissiveColor;
TEXTURE2D(_EmissiveColorMap);

float _AlphaCutoff;
float _PPDMaxSamples;
float _PPDMinSamples;
float _TessellationFactorFixed;
float _TessellationFactor;
float _TessellationFactorMinDistance;
float _TessellationFactorMaxDistance;
float _TessellationFactorTriangleSize;
float _TessellationShapeFactor;

119
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/LitTessellation.hlsl


/*
float _Tess;
float _TessNear;
float _TessFar;
float _UseDisplacementfalloff;
float _DisplacementfalloffNear;
float _DisplacementfalloffFar;
*/
float4 TessellationEdge(float3 p0, float3 p1, float3 p2, float3 n0, float3 n1, float3 n2)
float4 GetTessellationFactors(float3 p0, float3 p1, float3 p2, float3 n0, float3 n1, float3 n2)
// if (_TessellationFactorFixed >= 0.0f)
float maxDisplacement = ADD_ZERO_IDX(_HeightAmplitude);
#ifdef _LAYER_COUNT
maxDisplacement = max(maxDisplacement, _HeightAmplitude1);
#if _LAYER_COUNT >= 3
maxDisplacement = max(maxDisplacement, _HeightAmplitude2);
#endif
#if _LAYER_COUNT >= 4
maxDisplacement = max(maxDisplacement, _HeightAmplitude3);
#endif
#endif
bool frustumCulled = WorldViewFrustumCull(p0, p1, p2, maxDisplacement, (float4[4])unity_CameraWorldClipPlanes);
bool faceCull = false;
#if !(defined(_DOUBLESIDED) || defined(_DOUBLESIDED_LIGHTING_FLIP) || defined(_DOUBLESIDED_LIGHTING_MIRROR))
// TODO: Handle inverse culling (for mirror)!
if (_TessellationBackFaceCullEpsilon > -0.99) // Is backface culling enabled ?
// return _TessellationFactorFixed.xxxx;
faceCull = BackFaceCullTriangle(p0, p1, p2, _TessellationBackFaceCullEpsilon, _WorldSpaceCameraPos);
return DistanceBasedTess(p0, p1, p2, 0.0, _TessellationFactorMaxDistance, unity_ObjectToWorld, _WorldSpaceCameraPos) * _TessellationFactorFixed.xxxx;
#endif
if (frustumCulled || faceCull)
{
// Settings factor to 0 will kill the triangle
return float4(0.0, 0.0, 0.0, 0.0);
}
float3 tessFactor = float3(1.0, 1.0, 1.0);
// Aaptive screen space tessellation
if (_TessellationFactorTriangleSize > 0.0)
{
// return a value between 0 and 1
tessFactor *= GetScreenSpaceTessFactor( p0, p1, p2, GetWorldToHClipMatrix(), _ScreenParams, _TessellationFactorTriangleSize);
}
// Distance based tessellation
if (_TessellationFactorMaxDistance > 0.0)
{
float3 distFactor = GetDistanceBasedTessFactor(p0, p1, p2, _WorldSpaceCameraPos, _TessellationFactorMinDistance, _TessellationFactorMaxDistance);
// We square the disance factor as it allow a better percptual descrease of vertex density.
tessFactor *= distFactor * distFactor;
}
tessFactor *= _TessellationFactor;
// TessFactor below 1.0 have no effect. At 0 it kill the triangle, so clamp it to 1.0
tessFactor.xyz = float3(max(1.0, tessFactor.x), max(1.0, tessFactor.y), max(1.0, tessFactor.z));
return CalcTriEdgeTessFactors(tessFactor);
void Displacement(inout Attributes v)
float3 GetDisplacement(VaryingsMeshToDS input)
/*
float LengthLerp = length(ObjSpaceViewDir(v.vertex));
LengthLerp -= _DisplacementfalloffNear;
LengthLerp /= _DisplacementfalloffFar - _DisplacementfalloffNear;
LengthLerp = 1 - (saturate(LengthLerp));
// This call will work for both LayeredLit and Lit shader
LayerTexCoord layerTexCoord;
GetLayerTexCoord(
#ifdef VARYINGS_DS_NEED_TEXCOORD0
input.texCoord0,
#else
float2(0.0, 0.0),
#endif
#ifdef VARYINGS_DS_NEED_TEXCOORD1
input.texCoord1,
#else
float2(0.0, 0.0),
#endif
#ifdef VARYINGS_DS_NEED_TEXCOORD2
input.texCoord2,
#else
float2(0.0, 0.0),
#endif
#ifdef VARYINGS_DS_NEED_TEXCOORD3
input.texCoord3,
#else
float2(0.0, 0.0),
#endif
input.positionWS,
input.normalWS,
layerTexCoord);
float d = ((tex2Dlod(_DispTex, float4(v.texcoord.xy * _Tiling, 0, 0)).r) - _DisplacementCenter) * (_Displacement * LengthLerp);
d /= max(0.0001, _Tiling);
*/
// TODO: Move to camera relative and change distance to length
float lod = 0.0;
float4 vertexColor = float4(0.0, 0.0, 0.0, 0.0);
#ifdef VARYINGS_DS_NEED_COLOR
vertexColor = input.color;
#endif
float height = ComputePerVertexDisplacement(layerTexCoord, vertexColor, lod);
float3 displ = height * input.normalWS;
#ifdef _HEIGHTMAP
float height = (SAMPLE_TEXTURE2D_LOD(ADD_ZERO_IDX(_HeightMap), ADD_ZERO_IDX(sampler_HeightMap), v.uv0, 0).r - ADD_ZERO_IDX(_HeightCenter)) * ADD_IDX(_HeightAmplitude);
#else
float height = 0.0;
// Applying scaling of the object if requested
#ifdef _TESSELLATION_OBJECT_SCALE
displ *= input.objectScale;
#if (SHADERPASS != SHADERPASS_VELOCITY) && (SHADERPASS != SHADERPASS_DISTORTION)
v.positionOS.xyz += height * v.normalOS;
#endif
return displ;
}

88
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/LitTessellation.shader


[HideInInspector] _UVMappingPlanar("_UVMappingPlanar", Float) = 0
[Enum(TangentSpace, 0, ObjectSpace, 1)] _NormalMapSpace("NormalMap space", Float) = 0
[ToggleOff] _EnablePerPixelDisplacement("Enable per pixel displacement", Float) = 0.0
_PPDMinSamples("Min sample for POM", Range(1.0, 64.0)) = 5
_PPDMaxSamples("Max sample for POM", Range(1.0, 64.0)) = 15
[Enum(DetailMapNormal, 0, DetailMapAOHeight, 1)] _DetailMapMode("DetailMap mode", Float) = 0
[Enum(UV0, 0, UV1, 1, UV2, 2, UV3, 3)] _UVDetail("UV Set for detail", Float) = 0
[HideInInspector] _UVDetailsMappingMask("_UVDetailsMappingMask", Color) = (1, 0, 0, 0)

[Enum(Phong, 0, Displacement, 1, DisplacementPhong, 2)] _TessellationMode("Tessellation mode", Float) = 0
_TessellationFactorFixed("Tessellation Factor", Float) = 4.0 // if != -1.0 force fixed factor
_TessellationFactorMaxDistance("Tessellation max distance factor", Float) = 12.0
_TessellationFactorTriangleSize("Tessellation triangle size", Float) = 20.0
_TessellationFactor("Tessellation Factor", Range(0.0, 15.0)) = 4.0
_TessellationFactorMinDistance("Tessellation start fading distance", Float) = 20.0
_TessellationFactorMaxDistance("Tessellation end fading distance", Float) = 50.0
_TessellationFactorTriangleSize("Tessellation triangle size", Float) = 100.0
_TessellationBackFaceCullEpsilon("Tessellation back face epsilon", Range(-1.0, 1.0)) = 0.25
_TessellationBackFaceCullEpsilon("Tessellation back face epsilon", Range(-1.0, 0.0)) = -0.25
[ToggleOff] _TessellationObjectScale("Tessellation object scale", Float) = 0.0
// TODO: Handle culling mode for backface culling
}

#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _DISTORTION_ON
#pragma shader_feature _DEPTHOFFSET_ON
#pragma shader_feature _ _DOUBLESIDED_LIGHTING_FLIP _DOUBLESIDED_LIGHTING_MIRROR
#pragma shader_feature _ _DOUBLESIDED _DOUBLESIDED_LIGHTING_FLIP _DOUBLESIDED_LIGHTING_MIRROR
#pragma shader_feature _TESSELLATION_OBJECT_SCALE
#pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature _MAPPING_TRIPLANAR

#pragma shader_feature _REQUIRE_UV2_OR_UV3
#pragma shader_feature _ _REQUIRE_UV2 _REQUIRE_UV3
#pragma shader_feature _EMISSIVE_COLOR
#pragma shader_feature _NORMALMAP

#pragma shader_feature _HEIGHTMAP
#pragma shader_feature _TANGENTMAP
#pragma shader_feature _ANISOTROPYMAP
#pragma shader_feature _DETAIL_MAP
#pragma shader_feature _DETAIL_MAP
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED

#include "tessellation.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderConfig.cs.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderVariables.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Attributes.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/FragInputs.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPass.cs.hlsl"
//-------------------------------------------------------------------------------------

#include "Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/LitProperties.hlsl"
// All our shaders use same name for entry point
#pragma vertex Vert
#pragma fragment Frag
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTessellation
#pragma hull Hull
#pragma domain Domain
#pragma hull Hull
#pragma domain Domain
#include "LitData.hlsl"
#include "../Tessellation/TessellationShare.hlsl"
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTessellation
#pragma hull Hull
#pragma domain Domain
#pragma hull Hull
#pragma domain Domain
#include "LitData.hlsl"
#include "../Tessellation/TessellationShare.hlsl"
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassDebugViewMaterial.hlsl"
ENDHLSL

// both direct and indirect lighting) will hand up in the "regular" lightmap->LIGHTMAP_ON.
// No tessellation for Meta pass
#pragma vertex Vert
#undef TESSELLATION_ON
#include "../../ShaderPass/ShaderPassLightTransport.hlsl"
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTessellation
#pragma hull Hull
#pragma domain Domain
#pragma hull Hull
#pragma domain Domain
#include "LitData.hlsl"
#include "../Tessellation/TessellationShare.hlsl"
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTessellation
#pragma hull Hull
#pragma domain Domain
#pragma hull Hull
#pragma domain Domain
#include "LitData.hlsl"
#include "../Tessellation/TessellationShare.hlsl"
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTessellation
#pragma hull Hull
#pragma domain Domain
// TODO: Tesselation can't work with velocity for now...
#include "LitData.hlsl"
#include "../Tessellation/TessellationShare.hlsl"
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassVelocity.hlsl"
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTessellation
#pragma hull Hull
#pragma domain Domain
#pragma hull Hull
#pragma domain Domain
#include "../Tessellation/TessellationShare.hlsl"
#include "../../ShaderPass/ShaderPassDistortion.hlsl"
ENDHLSL

HLSLPROGRAM
#pragma vertex VertTessellation
#pragma hull Hull
#pragma domain Domain
#pragma hull Hull
#pragma domain Domain
#define SHADERPASS SHADERPASS_FORWARD
#define SHADERPASS SHADERPASS_FORWARD
#include "../../Lighting/Forward.hlsl"
// #include "../../Lighting/Forward.hlsl"
//#pragma multi_compile SHADOWFILTERING_FIXED_SIZE_PCF
#include "../Tessellation/TessellationShare.hlsl"
}
CustomEditor "Experimental.Rendering.HDPipeline.LitGUI"

4
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/Resources/PreIntegratedFGD.shader


HLSLPROGRAM
#pragma vertex Vert
#pragma fragment Frag
#pragma target 5.0
#pragma only_renderers d3d11 ps4// TEMP: unitl we go futher in dev
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#include "Common.hlsl"
#include "ImageBasedLighting.hlsl"

196
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/ShaderPass/LitDepthPass.hlsl


#error Undefine_SHADERPASS
#endif
// Check if Alpha test is enabled. If it is, check if parallax is enabled on this material
#define NEED_TEXCOORD0 1 // defined(_ALPHATEST_ON)
#define NEED_TANGENT_TO_WORLD 1 // NEED_TEXCOORD0 && (defined(_HEIGHTMAP) && defined(_PER_PIXEL_DISPLACEMENT)) TEMP!!!: until we fix tessellation so it can access normalOS
// When modifying this structure, update the tessellation code below
struct Attributes
{
float3 positionOS : POSITION;
#if NEED_TEXCOORD0
float2 uv0 : TEXCOORD0;
#endif
#if NEED_TANGENT_TO_WORLD
float3 normalOS : NORMAL;
float4 tangentOS : TANGENT;
#endif
};
#ifdef TESSELLATION_ON
// Copy paste of above struct with POSITION rename to INTERNALTESSPOS (internal of unity shader compiler)
struct AttributesTessellation
{
float3 positionOS : INTERNALTESSPOS;
#if NEED_TEXCOORD0
float2 uv0 : TEXCOORD0;
#endif
#if NEED_TANGENT_TO_WORLD
float3 normalOS : NORMAL;
float4 tangentOS : TANGENT;
#endif
};
AttributesTessellation AttributesToAttributesTessellation(Attributes input)
{
AttributesTessellation output;
output.positionOS = input.positionOS;
#if NEED_TEXCOORD0
output.uv0 = input.uv0;
#endif
#if NEED_TANGENT_TO_WORLD
output.normalOS = input.normalOS;
output.tangentOS = input.tangentOS;
#endif
return output;
}
Attributes AttributesTessellationToAttributes(AttributesTessellation input)
{
Attributes output;
output.positionOS = input.positionOS;
#if NEED_TEXCOORD0
output.uv0 = input.uv0;
#endif
#if NEED_TANGENT_TO_WORLD
output.normalOS = input.normalOS;
output.tangentOS = input.tangentOS;
#endif
// Attributes
#define REQUIRE_UV_FOR_TESSELATION (defined(TESSELLATION_ON) && (defined(_TESSELLATION_DISPLACEMENT) || defined(_TESSELLATION_DISPLACEMENT_PHONG)))
#define REQUIRE_VERTEX_COLOR_FOR_TESSELATION REQUIRE_UV_FOR_TESSELATION
#define REQUIRE_TANGENT_TO_WORLD (defined(_HEIGHTMAP) && defined(_PER_PIXEL_DISPLACEMENT))
return output;
}
AttributesTessellation InterpolateWithBaryCoords(AttributesTessellation input0, AttributesTessellation input1, AttributesTessellation input2, float3 baryCoords)
{
AttributesTessellation ouput;
// This first set of define allow to say which attributes will be use by the mesh in the vertex and domain shader (for tesselation)
TESSELLATION_INTERPOLATE_BARY(positionOS, baryCoords);
#if NEED_TEXCOORD0
TESSELLATION_INTERPOLATE_BARY(uv0, baryCoords);
// Tesselation require normal
#if defined(TESSELLATION_ON) || REQUIRE_TANGENT_TO_WORLD
#define ATTRIBUTES_NEED_NORMAL
#if NEED_TANGENT_TO_WORLD
TESSELLATION_INTERPOLATE_BARY(normalOS, baryCoords);
TESSELLATION_INTERPOLATE_BARY(tangentOS, baryCoords);
#endif
return ouput;
}
#endif // TESSELLATION_ON
struct Varyings
{
float4 positionCS;
#if NEED_TEXCOORD0
float2 texCoord0;
#endif
#if NEED_TANGENT_TO_WORLD
float3 positionWS;
float3 tangentToWorld[3];
#endif
};
struct PackedVaryings
{
float4 positionCS : SV_Position;
#if NEED_TANGENT_TO_WORLD
float4 interpolators[4] : TEXCOORD0;
#elif NEED_TEXCOORD0
float4 interpolators[1] : TEXCOORD0;
#if REQUIRE_TANGENT_TO_WORLD
#define ATTRIBUTES_NEED_TANGENT
};
// Function to pack data to use as few interpolator as possible, the ShaderGraph should generate these functions
PackedVaryings PackVaryings(Varyings input)
{
PackedVaryings output;
output.positionCS = input.positionCS;
#if NEED_TANGENT_TO_WORLD
output.interpolators[0].xyz = input.positionWS.xyz;
output.interpolators[1].xyz = input.tangentToWorld[0];
output.interpolators[2].xyz = input.tangentToWorld[1];
output.interpolators[3].xyz = input.tangentToWorld[2];
// About UV
// If we have a lit shader, only the UV0 is available for opacity or heightmap
// If we have a layered shader, any UV can be use for this. To reduce the number of variant we groupt UV0/UV1 and UV2/UV3 instead of having variant for UV0/UV1/UV2/UV3
// When UVX is present, we assume that UVX - 1 ... UV0 is present
output.interpolators[0].w = input.texCoord0.x;
output.interpolators[1].w = input.texCoord0.y;
#elif NEED_TEXCOORD0
output.interpolators[0] = float4(input.texCoord0, 0.0, 0.0);
#if REQUIRE_UV_FOR_TESSELATION || REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON)
#define ATTRIBUTES_NEED_TEXCOORD0
#ifdef LAYERED_LIT_SHADER
#define ATTRIBUTES_NEED_TEXCOORD1
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#define ATTRIBUTES_NEED_TEXCOORD2
#endif
#if defined(_REQUIRE_UV3)
#define ATTRIBUTES_NEED_TEXCOORD3
#endif
#endif
return output;
}
FragInputs UnpackVaryings(PackedVaryings input)
{
FragInputs output;
ZERO_INITIALIZE(FragInputs, output);
output.unPositionSS = input.positionCS; // input.positionCS is SV_Position
#if NEED_TANGENT_TO_WORLD
output.positionWS.xyz = input.interpolators[0].xyz;
output.tangentToWorld[0] = input.interpolators[1].xyz;
output.tangentToWorld[1] = input.interpolators[2].xyz;
output.tangentToWorld[2] = input.interpolators[3].xyz;
output.texCoord0.xy = float2(input.interpolators[0].w, input.interpolators[1].w);
#elif NEED_TEXCOORD0
output.texCoord0.xy = input.interpolators[0].xy;
#if REQUIRE_VERTEX_COLOR_FOR_TESSELATION
#define ATTRIBUTES_NEED_COLOR
return output;
}
PackedVaryings Vert(Attributes input)
{
Varyings output;
float3 positionWS = TransformObjectToWorld(input.positionOS);
output.positionCS = TransformWorldToHClip(positionWS);
#if NEED_TEXCOORD0
output.texCoord0 = input.uv0;
// Varying - Use for pixel shader
// This second set of define allow to say which varyings will be output in the vertex (no more tesselation)
#if REQUIRE_TANGENT_TO_WORLD
#define VARYINGS_NEED_TANGENT_TO_WORLD
#if NEED_TANGENT_TO_WORLD
output.positionWS = positionWS;
float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
float4 tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
float3x3 tangentToWorld = CreateTangentToWorld(normalWS, tangentWS.xyz, tangentWS.w);
output.tangentToWorld[0] = tangentToWorld[0];
output.tangentToWorld[1] = tangentToWorld[1];
output.tangentToWorld[2] = tangentToWorld[2];
#if REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON)
#define VARYINGS_NEED_TEXCOORD0
#ifdef LAYERED_LIT_SHADER
#define VARYINGS_NEED_TEXCOORD1
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#define VARYINGS_NEED_TEXCOORD2
#endif
#if defined(_REQUIRE_UV3)
#define VARYINGS_NEED_TEXCOORD3
#endif
#endif
return PackVaryings(output);
}
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"

174
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/ShaderPass/LitDistortionPass.hlsl


#error Undefine_SHADERPASS
#endif
#define NEED_TANGENT_TO_WORLD NEED_TEXCOORD0 && (defined(_HEIGHTMAP) && defined(_PER_PIXEL_DISPLACEMENT))
// Attributes
#define REQUIRE_UV_FOR_TESSELATION (defined(TESSELLATION_ON) && (defined(_TESSELLATION_DISPLACEMENT) || defined(_TESSELLATION_DISPLACEMENT_PHONG)))
#define REQUIRE_VERTEX_COLOR_FOR_TESSELATION REQUIRE_UV_FOR_TESSELATION
#define REQUIRE_TANGENT_TO_WORLD (defined(_HEIGHTMAP) && defined(_PER_PIXEL_DISPLACEMENT))
struct Attributes
{
float3 positionOS : POSITION;
float2 uv0 : TEXCOORD0;
#if NEED_TANGENT_TO_WORLD
float3 normalOS : NORMAL;
float4 tangentOS : TANGENT;
#endif
};
// This first set of define allow to say which attributes will be use by the mesh in the vertex and domain shader (for tesselation)
#ifdef TESSELLATION_ON
// Copy paste of above struct with POSITION rename to INTERNALTESSPOS (internal of unity shader compiler)
struct AttributesTessellation
{
float3 positionOS : INTERNALTESSPOS;
float2 uv0 : TEXCOORD0;
#if NEED_TANGENT_TO_WORLD
float3 normalOS : NORMAL;
float4 tangentOS : TANGENT;
// Tesselation require normal
#if defined(TESSELLATION_ON) || REQUIRE_TANGENT_TO_WORLD
#define ATTRIBUTES_NEED_NORMAL
};
AttributesTessellation AttributesToAttributesTessellation(Attributes input)
{
AttributesTessellation output;
output.positionOS = input.positionOS;
output.uv0 = input.uv0;
#if NEED_TANGENT_TO_WORLD
output.normalOS = input.normalOS;
output.tangentOS = input.tangentOS;
#if REQUIRE_TANGENT_TO_WORLD
#define ATTRIBUTES_NEED_TANGENT
return output;
}
// About UV
// If we have a lit shader, only the UV0 is available for opacity or heightmap
// If we have a layered shader, any UV can be use for this. To reduce the number of variant we groupt UV0/UV1 and UV2/UV3 instead of having variant for UV0/UV1/UV2/UV3
// When UVX is present, we assume that UVX - 1 ... UV0 is present
Attributes AttributesTessellationToAttributes(AttributesTessellation input)
{
Attributes output;
output.positionOS = input.positionOS;
output.uv0 = input.uv0;
#if NEED_TANGENT_TO_WORLD
output.normalOS = input.normalOS;
output.tangentOS = input.tangentOS;
#endif
return output;
}
AttributesTessellation InterpolateWithBaryCoords(AttributesTessellation input0, AttributesTessellation input1, AttributesTessellation input2, float3 baryCoords)
{
AttributesTessellation ouput;
TESSELLATION_INTERPOLATE_BARY(positionOS, baryCoords);
TESSELLATION_INTERPOLATE_BARY(uv0, baryCoords);
#if NEED_TANGENT_TO_WORLD
TESSELLATION_INTERPOLATE_BARY(normalOS, baryCoords);
TESSELLATION_INTERPOLATE_BARY(tangentOS, baryCoords);
#endif
return ouput;
}
#endif // TESSELLATION_ON
struct Varyings
{
float4 positionCS;
float3 positionWS;
float2 texCoord0;
#if NEED_TANGENT_TO_WORLD
float3 tangentToWorld[3];
#endif
};
struct PackedVaryings
{
float4 positionCS : SV_Position;
#if NEED_TANGENT_TO_WORLD
float4 interpolators[4] : TEXCOORD0;
#else
float4 interpolators[2] : TEXCOORD0;
#if REQUIRE_UV_FOR_TESSELATION || REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON) || defined(_DISTORTION_ON)
#define ATTRIBUTES_NEED_TEXCOORD0
#ifdef LAYERED_LIT_SHADER
#define ATTRIBUTES_NEED_TEXCOORD1
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#define ATTRIBUTES_NEED_TEXCOORD2
#endif
#if defined(_REQUIRE_UV3)
#define ATTRIBUTES_NEED_TEXCOORD3
#endif
#endif
};
// Function to pack data to use as few interpolator as possible, the ShaderGraph should generate these functions
PackedVaryings PackVaryings(Varyings input)
{
PackedVaryings output;
output.positionCS = input.positionCS;
output.interpolators[0] = float4(input.positionWS, 0.0);
output.interpolators[0].w = input.texCoord0.x;
output.interpolators[1] = float4(0.0, 0.0, 0.0, input.texCoord0.y);
#if NEED_TANGENT_TO_WORLD
output.interpolators[1].xyz = input.tangentToWorld[0];
output.interpolators[2].xyz = input.tangentToWorld[1];
output.interpolators[3].xyz = input.tangentToWorld[2];
#if REQUIRE_VERTEX_COLOR_FOR_TESSELATION
#define ATTRIBUTES_NEED_COLOR
return output;
}
FragInputs UnpackVaryings(PackedVaryings input)
{
FragInputs output;
ZERO_INITIALIZE(FragInputs, output);
output.unPositionSS = input.positionCS; // input.positionCS is SV_Position
output.positionWS = input.interpolators[0].xyz;
#if NEED_TANGENT_TO_WORLD
output.texCoord0.xy = float2(input.interpolators[0].w, input.interpolators[1].w);
output.tangentToWorld[0] = input.interpolators[1].xyz;
output.tangentToWorld[1] = input.interpolators[2].xyz;
output.tangentToWorld[2] = input.interpolators[3].xyz;
// Varying - Use for pixel shader
// This second set of define allow to say which varyings will be output in the vertex (no more tesselation)
#if REQUIRE_TANGENT_TO_WORLD
#define VARYINGS_NEED_TANGENT_TO_WORLD
return output;
}
PackedVaryings Vert(Attributes input)
{
Varyings output;
output.positionWS = TransformObjectToWorld(input.positionOS);
// TODO deal with camera center rendering and instancing (This is the reason why we always perform tow steps transform to clip space + instancing matrix)
output.positionCS = TransformWorldToHClip(output.positionWS);
output.texCoord0 = input.uv0;
#if NEED_TANGENT_TO_WORLD
float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
float4 tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
float3x3 tangentToWorld = CreateTangentToWorld(normalWS, tangentWS.xyz, tangentWS.w);
output.tangentToWorld[0] = tangentToWorld[0];
output.tangentToWorld[1] = tangentToWorld[1];
output.tangentToWorld[2] = tangentToWorld[2];
#if REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON) || defined(_DISTORTION_ON)
#define VARYINGS_NEED_TEXCOORD0
#ifdef LAYERED_LIT_SHADER
#define VARYINGS_NEED_TEXCOORD1
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#define VARYINGS_NEED_TEXCOORD2
#endif
#if defined(_REQUIRE_UV3)
#define VARYINGS_NEED_TEXCOORD3
#endif
#endif
return PackVaryings(output);
}
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"

91
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/ShaderPass/LitMetaPass.hlsl


#ifndef SHADERPASS
#error Undefine_SHADERPASS
#endif
CBUFFER_START(UnityMetaPass)
// x = use uv1 as raster position
// y = use uv2 as raster position
bool4 unity_MetaVertexControl;
// x = return albedo
// y = return normal
bool4 unity_MetaFragmentControl;
CBUFFER_END
// This was not in constant buffer in original unity, so keep outiside. But should be in as ShaderRenderPass frequency
float unity_OneOverOutputBoost;
float unity_MaxOutputValue;
struct Attributes
{
float3 positionOS : POSITION;
float3 normalOS : NORMAL;
float2 uv0 : TEXCOORD0;
float2 uv1 : TEXCOORD1;
float2 uv2 : TEXCOORD2;
};
struct Varyings
{
float4 positionCS;
float2 texCoord0;
float2 texCoord1;
};
#define ATTRIBUTES_NEED_TEXCOORD0
#define ATTRIBUTES_NEED_TEXCOORD1
#define ATTRIBUTES_NEED_TEXCOORD2
struct PackedVaryings
{
float4 positionCS : SV_Position;
float4 interpolators[1] : TEXCOORD0;
};
#define VARYINGS_NEED_TEXCOORD0
#define VARYINGS_NEED_TEXCOORD1
// Function to pack data to use as few interpolator as possible, the ShaderGraph should generate these functions
PackedVaryings PackVaryings(Varyings input)
{
PackedVaryings output;
output.positionCS = input.positionCS;
output.interpolators[0].xy = input.texCoord0;
output.interpolators[0].zw = input.texCoord1;
return output;
}
FragInputs UnpackVaryings(PackedVaryings input)
{
FragInputs output;
ZERO_INITIALIZE(FragInputs, output);
output.unPositionSS = input.positionCS; // input.positionCS is SV_Position
output.texCoord0 = input.interpolators[0].xy;
output.texCoord1 = input.interpolators[0].zw;
return output;
}
PackedVaryings Vert(Attributes input)
{
Varyings output;
// Output UV coordinate in vertex shader
if (unity_MetaVertexControl.x)
{
input.positionOS.xy = input.uv1 * unity_LightmapST.xy + unity_LightmapST.zw;
// OpenGL right now needs to actually use incoming vertex position,
// so use it in a very dummy way
//v.positionOS.z = vertex.z > 0 ? 1.0e-4f : 0.0f;
}
if (unity_MetaVertexControl.y)
{
input.positionOS.xy = input.uv2 * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
// OpenGL right now needs to actually use incoming vertex position,
// so use it in a very dummy way
//v.positionOS.z = vertex.z > 0 ? 1.0e-4f : 0.0f;
}
float3 positionWS = TransformObjectToWorld(input.positionOS);
output.positionCS = TransformWorldToHClip(positionWS);
output.texCoord0 = input.uv0;
output.texCoord1 = input.uv1;
return PackVaryings(output);
}
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"

252
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/ShaderPass/LitSharePass.hlsl


#error Undefine_SHADERPASS
#endif
//-------------------------------------------------------------------------------------
// Attribute/Varying
//-------------------------------------------------------------------------------------
#define WANT_UV2 (DYNAMICLIGHTMAP_ON) || (SHADERPASS == SHADERPASS_DEBUG_VIEW_MATERIAL) || defined(_REQUIRE_UV2_OR_UV3)
#define WANT_UV3 (SHADERPASS == SHADERPASS_DEBUG_VIEW_MATERIAL) || defined(_REQUIRE_UV2_OR_UV3)
struct Attributes
{
float3 positionOS : POSITION;
float3 normalOS : NORMAL;
float2 uv0 : TEXCOORD0;
float2 uv1 : TEXCOORD1;
#if WANT_UV2
float2 uv2 : TEXCOORD2;
#endif
#if WANT_UV3
float2 uv3 : TEXCOORD3;
#endif
float4 tangentOS : TANGENT; // Always present as we require it also in case of anisotropic lighting
float4 color : COLOR;
// UNITY_INSTANCE_ID
};
#ifdef TESSELLATION_ON
// Copy paste of above struct with POSITION rename to INTERNALTESSPOS (internal of unity shader compiler)
struct AttributesTessellation
{
float3 positionOS : INTERNALTESSPOS;
float3 normalOS : NORMAL;
float2 uv0 : TEXCOORD0;
float2 uv1 : TEXCOORD1;
#if WANT_UV2
float2 uv2 : TEXCOORD2;
#endif
#if WANT_UV3
float2 uv3 : TEXCOORD3;
#endif
float4 tangentOS : TANGENT; // Always present as we require it also in case of anisotropic lighting
float4 color : COLOR;
};
AttributesTessellation AttributesToAttributesTessellation(Attributes input)
{
AttributesTessellation output;
output.positionOS = input.positionOS;
output.normalOS = input.normalOS;
output.uv0 = input.uv0;
output.uv1 = input.uv1;
#if WANT_UV2
output.uv2 = input.uv2;
#endif
#if WANT_UV3
output.uv3 = input.uv3;
#endif
output.tangentOS = input.tangentOS;
output.color = input.color;
return output;
}
Attributes AttributesTessellationToAttributes(AttributesTessellation input)
{
Attributes output;
output.positionOS = input.positionOS;
output.normalOS = input.normalOS;
output.uv0 = input.uv0;
output.uv1 = input.uv1;
#if WANT_UV2
output.uv2 = input.uv2;
#endif
#if WANT_UV3
output.uv3 = input.uv3;
#endif
output.tangentOS = input.tangentOS;
output.color = input.color;
return output;
}
AttributesTessellation InterpolateWithBaryCoords(AttributesTessellation input0, AttributesTessellation input1, AttributesTessellation input2, float3 baryCoords)
{
AttributesTessellation ouput;
TESSELLATION_INTERPOLATE_BARY(positionOS, baryCoords);
TESSELLATION_INTERPOLATE_BARY(normalOS, baryCoords);
TESSELLATION_INTERPOLATE_BARY(uv0, baryCoords);
TESSELLATION_INTERPOLATE_BARY(uv1, baryCoords);
#if WANT_UV2
TESSELLATION_INTERPOLATE_BARY(uv2, baryCoords);
#endif
#if WANT_UV3
TESSELLATION_INTERPOLATE_BARY(uv3, baryCoords);
#endif
TESSELLATION_INTERPOLATE_BARY(tangentOS, baryCoords);
TESSELLATION_INTERPOLATE_BARY(color, baryCoords);
return ouput;
}
#endif // TESSELLATION_ON
struct Varyings
{
float4 positionCS;
float3 positionWS;
float2 texCoord0;
float2 texCoord1;
#if WANT_UV2
float2 texCoord2;
#endif
#if WANT_UV3
float2 texCoord3;
#endif
float3 tangentToWorld[3];
float4 color;
};
struct PackedVaryings
{
float4 positionCS : SV_Position;
#if (WANT_UV2) || (WANT_UV3)
float4 interpolators[6] : TEXCOORD0;
#else
float4 interpolators[5] : TEXCOORD0;
#endif
#if SHADER_STAGE_FRAGMENT
#if defined(_DOUBLESIDED_LIGHTING_FLIP) || defined(_DOUBLESIDED_LIGHTING_MIRROR)
FRONT_FACE_TYPE cullFace : FRONT_FACE_SEMATIC;
#endif
#endif
};
// Function to pack data to use as few interpolator as possible, the ShaderGraph should generate these functions
PackedVaryings PackVaryings(Varyings input)
{
PackedVaryings output;
output.positionCS = input.positionCS;
output.interpolators[0].xyz = input.positionWS.xyz;
output.interpolators[1].xyz = input.tangentToWorld[0];
output.interpolators[2].xyz = input.tangentToWorld[1];
output.interpolators[3].xyz = input.tangentToWorld[2];
output.interpolators[0].w = input.texCoord0.x;
output.interpolators[1].w = input.texCoord0.y;
output.interpolators[2].w = input.texCoord1.x;
output.interpolators[3].w = input.texCoord1.y;
output.interpolators[4] = input.color;
// This first set of define allow to say which attributes will be use by the mesh in the vertex and domain shader (for tesselation)
#if (WANT_UV2) || (WANT_UV3)
output.interpolators[5] = float4(0.0, 0.0, 0.0, 0.0);
#if WANT_UV2
output.interpolators[5].xy = input.texCoord2.xy;
#endif
#if WANT_UV3
output.interpolators[5].zw = input.texCoord3.xy;
#endif
#endif
return output;
}
FragInputs UnpackVaryings(PackedVaryings input)
{
FragInputs output;
ZERO_INITIALIZE(FragInputs, output);
output.unPositionSS = input.positionCS; // input.positionCS is SV_Position
output.positionWS.xyz = input.interpolators[0].xyz;
output.tangentToWorld[0] = input.interpolators[1].xyz;
output.tangentToWorld[1] = input.interpolators[2].xyz;
output.tangentToWorld[2] = input.interpolators[3].xyz;
output.texCoord0.xy = float2(input.interpolators[0].w, input.interpolators[1].w);
output.texCoord1.xy = float2(input.interpolators[2].w, input.interpolators[3].w);
output.vertexColor = input.interpolators[4];
// Attributes
#define ATTRIBUTES_NEED_NORMAL
#define ATTRIBUTES_NEED_TANGENT // Always present as we require it also in case of anisotropic lighting
#define ATTRIBUTES_NEED_TEXCOORD0
#define ATTRIBUTES_NEED_TEXCOORD1
#define ATTRIBUTES_NEED_COLOR
#if WANT_UV2
output.texCoord2 = input.interpolators[5].xy;
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3) || defined(DYNAMICLIGHTMAP_ON) || (SHADERPASS == SHADERPASS_DEBUG_VIEW_MATERIAL)
#define ATTRIBUTES_NEED_TEXCOORD2
#if WANT_UV3
output.texCoord3 = input.interpolators[5].zw;
#if defined(_REQUIRE_UV3) || (SHADERPASS == SHADERPASS_DEBUG_VIEW_MATERIAL)
#define ATTRIBUTES_NEED_TEXCOORD3
#if SHADER_STAGE_FRAGMENT
#if defined(_DOUBLESIDED_LIGHTING_FLIP) || defined(_DOUBLESIDED_LIGHTING_MIRROR)
output.isFrontFace = IS_FRONT_VFACE(input.cullFace, true, false);
#endif
// Varying - Use for pixel shader
// This second set of define allow to say which varyings will be output in the vertex (no more tesselation)
#define VARYINGS_NEED_POSITION_WS
#define VARYINGS_NEED_TANGENT_TO_WORLD
#define VARYINGS_NEED_TEXCOORD0
#define VARYINGS_NEED_TEXCOORD1
#ifdef ATTRIBUTES_NEED_TEXCOORD2
#define VARYINGS_NEED_TEXCOORD2
return output;
}
//-------------------------------------------------------------------------------------
// Vertex shader
//-------------------------------------------------------------------------------------
// TODO: Here we will also have all the vertex deformation (GPU skinning, vertex animation, morph target...) or we will need to generate a compute shaders instead (better! but require work to deal with unpacking like fp16)
PackedVaryings Vert(Attributes input)
{
Varyings output;
output.positionWS = TransformObjectToWorld(input.positionOS);
// TODO deal with camera center rendering and instancing (This is the reason why we always perform tow steps transform to clip space + instancing matrix)
output.positionCS = TransformWorldToHClip(output.positionWS);
float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
output.texCoord0 = input.uv0;
output.texCoord1 = input.uv1;
#if WANT_UV2
output.texCoord2 = input.uv2;
#ifdef ATTRIBUTES_NEED_TEXCOORD3
#define VARYINGS_NEED_TEXCOORD3
#define VARYINGS_NEED_COLOR
#if WANT_UV3
output.texCoord3 = input.uv3;
#if defined(_DOUBLESIDED_LIGHTING_FLIP) || defined(_DOUBLESIDED_LIGHTING_MIRROR)
#define VARYINGS_NEED_CULLFACE
float4 tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
float3x3 tangentToWorld = CreateTangentToWorld(normalWS, tangentWS.xyz, tangentWS.w);
output.tangentToWorld[0] = tangentToWorld[0];
output.tangentToWorld[1] = tangentToWorld[1];
output.tangentToWorld[2] = tangentToWorld[2];
output.color = input.color;
return PackVaryings(output);
}
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"

215
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Lit/ShaderPass/LitVelocityPass.hlsl


#error Undefine_SHADERPASS
#endif
#define NEED_TEXCOORD0 defined(_ALPHATEST_ON)
#define NEED_TANGENT_TO_WORLD NEED_TEXCOORD0 && (defined(_HEIGHTMAP) && defined(_PER_PIXEL_DISPLACEMENT))
// TODO: Caution - For now the tesselation doesn't displace along the normal with Velocity shader as the previous previous position
// conflict with the normal in the semantic. This need to be fix! Also no per pixel displacement is possible either.
struct Attributes
{
float3 positionOS : POSITION;
float3 previousPositionOS : NORMAL; // Contain previous transform position (in case of skinning for example)
#if NEED_TEXCOORD0
float2 uv0 : TEXCOORD0;
#endif
#if NEED_TANGENT_TO_WORLD
// float3 normalOS : NORMAL; // TODO: This won't compile as we conflict with previousPositionOS. FIXME
float4 tangentOS : TANGENT;
#endif
};
// Attributes
#define REQUIRE_UV_FOR_TESSELATION (defined(TESSELLATION_ON) && (defined(_TESSELLATION_DISPLACEMENT) || defined(_TESSELLATION_DISPLACEMENT_PHONG)))
#define REQUIRE_VERTEX_COLOR_FOR_TESSELATION REQUIRE_UV_FOR_TESSELATION
#define REQUIRE_TANGENT_TO_WORLD 0 /* (defined(_HEIGHTMAP) && defined(_PER_PIXEL_DISPLACEMENT)) */
#ifdef TESSELLATION_ON
// Copy paste of above struct with POSITION rename to INTERNALTESSPOS (internal of unity shader compiler)
struct AttributesTessellation
{
float3 positionOS : INTERNALTESSPOS;
float3 previousPositionOS : NORMAL;
#if NEED_TEXCOORD0
float2 uv0 : TEXCOORD0;
#endif
#if NEED_TANGENT_TO_WORLD
// float3 normalOS : NORMAL;
float4 tangentOS : TANGENT;
#endif
};
// This first set of define allow to say which attributes will be use by the mesh in the vertex and domain shader (for tesselation)
AttributesTessellation AttributesToAttributesTessellation(Attributes input)
{
AttributesTessellation output;
output.positionOS = input.positionOS;
output.previousPositionOS = input.previousPositionOS;
#if NEED_TEXCOORD0
output.uv0 = input.uv0;
// Tesselation require normal
#if defined(TESSELLATION_ON) || REQUIRE_TANGENT_TO_WORLD
// #define ATTRIBUTES_NEED_NORMAL - When reenable, think to also enable code in VertMesh.hlsl
#if NEED_TANGENT_TO_WORLD
// output.normalOS = input.normalOS;
output.tangentOS = input.tangentOS;
#if REQUIRE_TANGENT_TO_WORLD
#define ATTRIBUTES_NEED_TANGENT
return output;
}
// About UV
// If we have a lit shader, only the UV0 is available for opacity or heightmap
// If we have a layered shader, any UV can be use for this. To reduce the number of variant we groupt UV0/UV1 and UV2/UV3 instead of having variant for UV0/UV1/UV2/UV3
// When UVX is present, we assume that UVX - 1 ... UV0 is present
Attributes AttributesTessellationToAttributes(AttributesTessellation input)
{
Attributes output;
output.positionOS = input.positionOS;
output.previousPositionOS = input.previousPositionOS;
#if NEED_TEXCOORD0
output.uv0 = input.uv0;
#if defined(_ALPHATEST_ON)
#define ATTRIBUTES_NEED_TEXCOORD0
#ifdef LAYERED_LIT_SHADER
#define ATTRIBUTES_NEED_TEXCOORD1
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#define ATTRIBUTES_NEED_TEXCOORD2
#endif
#if defined(_REQUIRE_UV3)
#define ATTRIBUTES_NEED_TEXCOORD3
#endif
#endif
#if NEED_TANGENT_TO_WORLD
// output.normalOS = input.normalOS;
output.tangentOS = input.tangentOS;
#endif
return output;
}
AttributesTessellation InterpolateWithBaryCoords(AttributesTessellation input0, AttributesTessellation input1, AttributesTessellation input2, float3 baryCoords)
{
AttributesTessellation ouput;
TESSELLATION_INTERPOLATE_BARY(positionOS, baryCoords);
TESSELLATION_INTERPOLATE_BARY(previousPositionOS, baryCoords);
#if NEED_TEXCOORD0
TESSELLATION_INTERPOLATE_BARY(uv0, baryCoords);
#endif
#if NEED_TANGENT_TO_WORLD
// TESSELLATION_INTERPOLATE_BARY(normalOS, baryCoords);
TESSELLATION_INTERPOLATE_BARY(tangentOS, baryCoords);
#if REQUIRE_VERTEX_COLOR_FOR_TESSELATION
#define ATTRIBUTES_NEED_COLOR
return ouput;
}
#endif // TESSELLATION_ON
struct Varyings
{
float4 positionCS;
float3 positionWS;
// Note: Z component is not use
float4 transferPositionCS;
float4 transferPreviousPositionCS;
#if NEED_TEXCOORD0
float2 texCoord0;
#endif
#if NEED_TANGENT_TO_WORLD
float3 tangentToWorld[3];
#endif
};
// Varying - Use for pixel shader
// This second set of define allow to say which varyings will be output in the vertex (no more tesselation)
#define VARYINGS_NEED_POSITION_WS
struct PackedVaryings
{
float4 positionCS : SV_Position;
#if NEED_TANGENT_TO_WORLD
float4 interpolators[5] : TEXCOORD0;
#elif NEED_TEXCOORD0
float4 interpolators[3] : TEXCOORD0;
#else
float4 interpolators[3] : TEXCOORD0;
#if REQUIRE_TANGENT_TO_WORLD
#define VARYINGS_NEED_TANGENT_TO_WORLD
};
// Function to pack data to use as few interpolator as possible, the ShaderGraph should generate these functions
PackedVaryings PackVaryings(Varyings input)
{
PackedVaryings output;
output.positionCS = input.positionCS;
output.interpolators[0] = float4(input.positionWS, 0.0);
output.interpolators[1] = float4(input.transferPositionCS.xyw, 0.0);
output.interpolators[2] = float4(input.transferPreviousPositionCS.xyw, 0.0);
#if NEED_TANGENT_TO_WORLD
output.interpolators[0].w = input.texCoord0.x;
output.interpolators[1].w = input.texCoord0.y;
output.interpolators[3].xyz = input.tangentToWorld[0];
output.interpolators[4].xyz = input.tangentToWorld[1];
output.interpolators[2].w = input.tangentToWorld[2].x;
output.interpolators[3].w = input.tangentToWorld[2].y;
output.interpolators[4].w = input.tangentToWorld[2].z;
#elif NEED_TEXCOORD0
output.interpolators[0].w = input.texCoord0.x;
output.interpolators[1].w = input.texCoord0.y;
#if REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON)
#define VARYINGS_NEED_TEXCOORD0
#ifdef LAYERED_LIT_SHADER
#define VARYINGS_NEED_TEXCOORD1
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#define VARYINGS_NEED_TEXCOORD2
#endif
#if defined(_REQUIRE_UV3)
#define VARYINGS_NEED_TEXCOORD3
#endif
#endif
return output;
}
FragInputs UnpackVaryings(PackedVaryings input)
{
FragInputs output;
ZERO_INITIALIZE(FragInputs, output);
output.unPositionSS = input.positionCS; // input.positionCS is SV_Position
output.positionWS = input.interpolators[0].xyz;
output.positionCS = float4(input.interpolators[1].xy, 0.0, input.interpolators[1].z);
output.previousPositionCS = float4(input.interpolators[1].xy, 0.0, input.interpolators[2].z);
#if NEED_TANGENT_TO_WORLD
output.texCoord0.xy = float2(input.interpolators[0].w, input.interpolators[1].w);
output.tangentToWorld[0] = input.interpolators[3].xyz;
output.tangentToWorld[1] = input.interpolators[4].xyz;
output.tangentToWorld[2] = float3(input.interpolators[2].w, input.interpolators[3].w, input.interpolators[4].w);
#elif NEED_TEXCOORD0
output.texCoord0.xy = float2(input.interpolators[0].w, input.interpolators[1].w);
#endif
return output;
}
PackedVaryings Vert(Attributes input)
{
Varyings output;
output.positionWS = TransformObjectToWorld(input.positionOS);
// TODO deal with camera center rendering and instancing (This is the reason why we always perform tow steps transform to clip space + instancing matrix)
output.positionCS = TransformWorldToHClip(output.positionWS);
// TODO: Clean this code, put in function ?
output.transferPositionCS = mul(_NonJitteredVP, mul(unity_ObjectToWorld, float4(input.positionOS, 1.0)));
output.transferPreviousPositionCS = mul(_PreviousVP, mul(_PreviousM, _HasLastPositionData ? float4(input.previousPositionOS, 1.0) : float4(input.positionOS, 1.0)));
#if NEED_TEXCOORD0
output.texCoord0 = input.uv0;
#endif
#if NEED_TANGENT_TO_WORLD
float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
float4 tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
float3x3 tangentToWorld = CreateTangentToWorld(normalWS, tangentWS.xyz, tangentWS.w);
output.tangentToWorld[0] = tangentToWorld[0];
output.tangentToWorld[1] = tangentToWorld[1];
output.tangentToWorld[2] = tangentToWorld[2];
#endif
return PackVaryings(output);
}
// This include will define the various Attributes/Varyings structure
#include "../../ShaderPass/VaryingMesh.hlsl"

21
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/MaterialUtilities.hlsl


// TODO: Move all this to C++!
float4x4 identity = 0;
identity._m00_m11_m22_m33 = 1.0;
float4x4 WorldToTexture = (unity_ProbeVolumeParams.y == 1.0f) ? unity_ProbeVolumeWorldToObject : identity;
float4x4 WorldToTexture = (unity_ProbeVolumeParams.y == 1.0) ? unity_ProbeVolumeWorldToObject : identity;
float4x4 translation = identity;
translation._m30_m31_m32 = -unity_ProbeVolumeMin.xyz;

#else
return float2(0.0, 0.0);
#endif
}
}
// This function convert the tangent space normal/tangent to world space and orthonormalize it + apply a correction of the normal if it is not pointing towards the near plane
void GetNormalAndTangentWS(FragInputs input, float3 V, float3 normalTS, inout float3 normalWS, inout float3 tangentWS, bool twoSided = false)
{
normalWS = TransformTangentToWorld(normalTS, input.tangentToWorld);
// NdotV should not be negative for visible pixels, but it can happen due to the
// perspective projection and the normal mapping + decals. In that case, the normal
// should be modified to become valid (i.e facing the camera) to avoid weird artifacts.
// Note: certain applications (e.g. SpeedTree) require to still have negative normal to perform their own two sided lighting
// This will potentially reduce the length of the normal at edges of geometry.
GetShiftedNdotV(normalWS, V, twoSided);
// Orthonormalize the basis vectors using the Gram-Schmidt process.
// We assume that the length of the surface normal is sufficiently close to 1.
tangentWS = normalize(tangentWS - dot(tangentWS, normalWS));
}

140
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Unlit/Unlit.shader


HLSLINCLUDE
#pragma target 5.0
#pragma only_renderers d3d11 ps4 // TEMP: unitl we go futher in dev
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
//-------------------------------------------------------------------------------------
// Variant

#pragma shader_feature _DISTORTION_ON
#pragma shader_feature _ _DOUBLESIDED_LIGHTING_FLIP _DOUBLESIDED_LIGHTING_MIRROR
#pragma shader_feature _ _DOUBLESIDED
#pragma shader_feature _EMISSIVE_COLOR_MAP

#include "common.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderConfig.cs.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderVariables.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Attributes.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/FragInputs.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPass.cs.hlsl"
//-------------------------------------------------------------------------------------

#define SHADERPASS SHADERPASS_DEBUG_VIEW_MATERIAL
#include "../../Material/Material.hlsl"
#include "UnlitSharePass.hlsl"
#include "UnlitData.hlsl"
#include "../../ShaderPass/ShaderPassDebugViewMaterial.hlsl"
ENDHLSL
}
// ------------------------------------------------------------------
// forward opaque pass
// Material opaque that are always forward (i.e can't render in deferred) need to implement ForwardOnlyOpaque pass
// (Code is exactly the same as "Forward", it simply allow our system to filter objects correctly
// TODO: can we do this another way ? Like relying on QueueIndex ? But it will be require anyway for material with two forward pass like hair
Pass
{
Name "ForwardUnlit"
Tags { "LightMode" = "ForwardOnlyOpaque" }
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]
Cull [_CullMode]
HLSLPROGRAM
#define SHADERPASS SHADERPASS_FORWARD_UNLIT
#include "../../Material/Material.hlsl"
#include "UnlitSharePass.hlsl"
#include "ShaderPass/UnlitSharePass.hlsl"
#include "../../ShaderPass/ShaderPassForwardUnlit.hlsl"
#include "../../ShaderPass/ShaderPassDebugViewMaterial.hlsl"
ENDHLSL
}

#define SHADERPASS SHADERPASS_FORWARD_UNLIT
#include "../../Material/Material.hlsl"
#include "UnlitSharePass.hlsl"
#include "ShaderPass/UnlitSharePass.hlsl"
#include "../../ShaderPass/ShaderPassForwardUnlit.hlsl"
ENDHLSL

// both direct and indirect lighting) will hand up in the "regular" lightmap->LIGHTMAP_ON.
#define SHADERPASS SHADERPASS_LIGHT_TRANSPORT
#include "UnlitData.hlsl"
#include "../../Material/Material.hlsl"
CBUFFER_START(UnityMetaPass)
// x = use uv1 as raster position
// y = use uv2 as raster position
bool4 unity_MetaVertexControl;
// x = return albedo
// y = return normal
bool4 unity_MetaFragmentControl;
CBUFFER_END
// This was not in constant buffer in original unity, so keep outiside. But should be in as ShaderRenderPass frequency
float unity_OneOverOutputBoost;
float unity_MaxOutputValue;
struct Attributes
{
float3 positionOS : POSITION;
float3 normalOS : NORMAL;
float2 uv0 : TEXCOORD0;
float2 uv1 : TEXCOORD1;
float2 uv2 : TEXCOORD2;
};
struct Varyings
{
float4 positionCS;
float2 texCoord0;
float2 texCoord1;
};
struct PackedVaryings
{
float4 positionCS : SV_Position;
float4 interpolators[1] : TEXCOORD0;
};
// Function to pack data to use as few interpolator as possible, the ShaderGraph should generate these functions
PackedVaryings PackVaryings(Varyings input)
{
PackedVaryings output;
output.positionCS = input.positionCS;
output.interpolators[0].xy = input.texCoord0;
output.interpolators[0].zw = input.texCoord1;
return output;
}
FragInputs UnpackVaryings(PackedVaryings input)
{
FragInputs output;
ZERO_INITIALIZE(FragInputs, output);
output.unPositionSS = input.positionCS;
output.texCoord0 = input.interpolators[0].xy;
output.texCoord1 = input.interpolators[0].zw;
return output;
}
PackedVaryings Vert(Attributes input)
{
Varyings output;
// Output UV coordinate in vertex shader
if (unity_MetaVertexControl.x)
{
input.positionOS.xy = input.uv1 * unity_LightmapST.xy + unity_LightmapST.zw;
// OpenGL right now needs to actually use incoming vertex position,
// so use it in a very dummy way
//v.positionOS.z = vertex.z > 0 ? 1.0e-4f : 0.0f;
}
if (unity_MetaVertexControl.y)
{
input.positionOS.xy = input.uv2 * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
// OpenGL right now needs to actually use incoming vertex position,
// so use it in a very dummy way
//v.positionOS.z = vertex.z > 0 ? 1.0e-4f : 0.0f;
}
float3 positionWS = TransformObjectToWorld(input.positionOS);
output.positionCS = TransformWorldToHClip(positionWS);
output.texCoord0 = input.uv0;
output.texCoord1 = input.uv1;
return PackVaryings(output);
}
#include "../../Material/Material.hlsl"
#include "ShaderPass/UnlitMetaPass.hlsl"
#include "UnlitData.hlsl"
#include "../../ShaderPass/ShaderPassLightTransport.hlsl"
ENDHLSL

#define SHADERPASS SHADERPASS_DISTORTION
#include "../../Material/Material.hlsl"
#include "UnlitSharePass.hlsl"
#include "ShaderPass/UnlitSharePass.hlsl"
#include "../../ShaderPass/ShaderPassDistortion.hlsl"
ENDHLSL

22
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/Unlit/UnlitData.hlsl


builtinData.depthOffset = 0.0;
}
#ifdef TESSELLATION_ON
float4 TessellationEdge(float3 p0, float3 p1, float3 p2, float3 n0, float3 n1, float3 n2)
{
return DistanceBasedTess(p0, p1, p2, 0.0, _TessellationFactorMaxDistance, unity_ObjectToWorld, _WorldSpaceCameraPos) * _TessellationFactorFixed.xxxx;
}
void Displacement(inout Attributes v)
{
#ifdef _HEIGHTMAP
float height = (SAMPLE_TEXTURE2D_LOD(ADD_ZERO_IDX(_HeightMap), ADD_ZERO_IDX(sampler_HeightMap), v.uv0, 0).r - ADD_ZERO_IDX(_HeightCenter)) * ADD_IDX(_HeightAmplitude);
#else
float height = 0.0;
#endif
#if (SHADERPASS != SHADERPASS_VELOCITY) && (SHADERPASS != SHADERPASS_DISTORTION)
v.positionOS.xyz += height * v.normalOS;
#endif
}
#endif

2
Assets/ScriptableRenderLoop/HDRenderPipeline/PostProcess/Resources/EyeAdaptation.shader


HLSLINCLUDE
#pragma target 5.0
#pragma target 4.5
#include "Common.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderVariables.hlsl"
#include "EyeAdaptation.hlsl"

2
Assets/ScriptableRenderLoop/HDRenderPipeline/PostProcess/Resources/FinalPass.shader


HLSLINCLUDE
#pragma target 5.0
#pragma target 4.5
#include "Common.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderVariables.hlsl"
#include "ColorGrading.hlsl"

2
Assets/ScriptableRenderLoop/HDRenderPipeline/PostProcess/Resources/LutGen.shader


{
HLSLINCLUDE
#pragma target 5.0
#pragma target 4.5
#include "Common.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderVariables.hlsl"
#include "ColorGrading.hlsl"

26
Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassDebugViewMaterial.hlsl


#include "Color.hlsl"
int _DebugViewMaterial;
#include "VertMesh.hlsl"
PackedVaryingsType Vert(AttributesMesh inputMesh)
{
VaryingsType varyingsType;
varyingsType.vmesh = VertMesh(inputMesh);
return PackVaryingsType(varyingsType);
}
#ifdef TESSELLATION_ON
PackedVaryingsToPS VertTesselation(VaryingsToDS input)
{
VaryingsToPS output;
output.vmesh = VertMeshTesselation(input.vmesh);
return PackVaryingsToPS(output);
}
#include "TessellationShare.hlsl"
#endif // TESSELLATION_ON
float4 Frag(PackedVaryings packedInput) : SV_Target
float4 Frag(PackedVaryingsToPS packedInput) : SV_Target
FragInputs input = UnpackVaryings(packedInput);
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.unPositionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.unPositionSS.xy, _ScreenSize.zw);

26
Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl


#error SHADERPASS_is_not_correctly_define
#endif
void Frag( PackedVaryings packedInput,
#include "VertMesh.hlsl"
PackedVaryingsType Vert(AttributesMesh inputMesh)
{
VaryingsType varyingsType;
varyingsType.vmesh = VertMesh(inputMesh);
return PackVaryingsType(varyingsType);
}
#ifdef TESSELLATION_ON
PackedVaryingsToPS VertTesselation(VaryingsToDS input)
{
VaryingsToPS output;
output.vmesh = VertMeshTesselation(input.vmesh);
return PackVaryingsToPS(output);
}
#include "TessellationShare.hlsl"
#endif // TESSELLATION_ON
void Frag( PackedVaryingsToPS packedInput,
out float4 outColor : SV_Target
#ifdef _DEPTHOFFSET_ON
, out float outputDepth : SV_Depth

FragInputs input = UnpackVaryings(packedInput);
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.unPositionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.unPositionSS.xy, _ScreenSize.zw);

26
Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassDistortion.hlsl


#error SHADERPASS_is_not_correctly_define
#endif
float4 Frag(PackedVaryings packedInput) : SV_Target
#include "VertMesh.hlsl"
PackedVaryingsType Vert(AttributesMesh inputMesh)
FragInputs input = UnpackVaryings(packedInput);
VaryingsType varyingsType;
varyingsType.vmesh = VertMesh(inputMesh);
return PackVaryingsType(varyingsType);
}
#ifdef TESSELLATION_ON
PackedVaryingsToPS VertTesselation(VaryingsToDS input)
{
VaryingsToPS output;
output.vmesh = VertMeshTesselation(input.vmesh);
return PackVaryingsToPS(output);
}
#include "TessellationShare.hlsl"
#endif // TESSELLATION_ON
float4 Frag(PackedVaryingsToPS packedInput) : SV_Target
{
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.unPositionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.unPositionSS.xy, _ScreenSize.zw);

26
Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassForward.hlsl


#error SHADERPASS_is_not_correctly_define
#endif
void Frag( PackedVaryings packedInput,
#include "VertMesh.hlsl"
PackedVaryingsType Vert(AttributesMesh inputMesh)
{
VaryingsType varyingsType;
varyingsType.vmesh = VertMesh(inputMesh);
return PackVaryingsType(varyingsType);
}
#ifdef TESSELLATION_ON
PackedVaryingsToPS VertTesselation(VaryingsToDS input)
{
VaryingsToPS output;
output.vmesh = VertMeshTesselation(input.vmesh);
return PackVaryingsToPS(output);
}
#include "TessellationShare.hlsl"
#endif // TESSELLATION_ON
void Frag( PackedVaryingsToPS packedInput,
out float4 outColor : SV_Target
#ifdef _DEPTHOFFSET_ON
, out float outputDepth : SV_Depth

FragInputs input = UnpackVaryings(packedInput);
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.unPositionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.unPositionSS.xy, _ScreenSize.zw);

26
Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassForwardUnlit.hlsl


#error SHADERPASS_is_not_correctly_define
#endif
float4 Frag(PackedVaryings packedInput) : SV_Target
#include "VertMesh.hlsl"
PackedVaryingsType Vert(AttributesMesh inputMesh)
FragInputs input = UnpackVaryings(packedInput);
VaryingsType varyingsType;
varyingsType.vmesh = VertMesh(inputMesh);
return PackVaryingsType(varyingsType);
}
#ifdef TESSELLATION_ON
PackedVaryingsToPS VertTesselation(VaryingsToDS input)
{
VaryingsToPS output;
output.vmesh = VertMeshTesselation(input.vmesh);
return PackVaryingsToPS(output);
}
#include "TessellationShare.hlsl"
#endif // TESSELLATION_ON
float4 Frag(PackedVaryingsToPS packedInput) : SV_Target
{
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.unPositionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.unPositionSS.xy, _ScreenSize.zw);

26
Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassGBuffer.hlsl


#error SHADERPASS_is_not_correctly_define
#endif
void Frag( PackedVaryings packedInput,
#include "VertMesh.hlsl"
PackedVaryingsType Vert(AttributesMesh inputMesh)
{
VaryingsType varyingsType;
varyingsType.vmesh = VertMesh(inputMesh);
return PackVaryingsType(varyingsType);
}
#ifdef TESSELLATION_ON
PackedVaryingsToPS VertTesselation(VaryingsToDS input)
{
VaryingsToPS output;
output.vmesh = VertMeshTesselation(input.vmesh);
return PackVaryingsToPS(output);
}
#include "TessellationShare.hlsl"
#endif // TESSELLATION_ON
void Frag( PackedVaryingsToPS packedInput,
OUTPUT_GBUFFER(outGBuffer)
OUTPUT_GBUFFER_VELOCITY(outVelocityBuffer)
#ifdef _DEPTHOFFSET_ON

{
FragInputs input = UnpackVaryings(packedInput);
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.unPositionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.unPositionSS.xy, _ScreenSize.zw);

49
Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl


#include "Color.hlsl"
float4 Frag(PackedVaryings packedInput) : SV_Target
CBUFFER_START(UnityMetaPass)
// x = use uv1 as raster position
// y = use uv2 as raster position
bool4 unity_MetaVertexControl;
// x = return albedo
// y = return normal
bool4 unity_MetaFragmentControl;
CBUFFER_END
// This was not in constant buffer in original unity, so keep outiside. But should be in as ShaderRenderPass frequency
float unity_OneOverOutputBoost;
float unity_MaxOutputValue;
#include "VertMesh.hlsl"
PackedVaryingsToPS Vert(AttributesMesh inputMesh)
{
VaryingsToPS output;
// Output UV coordinate in vertex shader
if (unity_MetaVertexControl.x)
{
inputMesh.positionOS.xy = inputMesh.uv1 * unity_LightmapST.xy + unity_LightmapST.zw;
// OpenGL right now needs to actually use incoming vertex position,
// so use it in a very dummy way
//v.positionOS.z = vertex.z > 0 ? 1.0e-4 : 0.0;
}
if (unity_MetaVertexControl.y)
{
inputMesh.positionOS.xy = inputMesh.uv2 * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
// OpenGL right now needs to actually use incoming vertex position,
// so use it in a very dummy way
//v.positionOS.z = vertex.z > 0 ? 1.0e-4 : 0.0;
}
float3 positionWS = TransformObjectToWorld(inputMesh.positionOS);
output.vmesh.positionCS = TransformWorldToHClip(positionWS);
output.vmesh.texCoord0 = inputMesh.uv0;
output.vmesh.texCoord1 = inputMesh.uv1;
return PackVaryingsToPS(output);
}
float4 Frag(PackedVaryingsToPS packedInput) : SV_Target
FragInputs input = UnpackVaryings(packedInput);
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.unPositionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.unPositionSS.xy, _ScreenSize.zw);

126
Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/ShaderPassVelocity.hlsl


#error SHADERPASS_is_not_correctly_define
#endif
float4 Frag(PackedVaryings packedInput) : SV_Target
// Available semantic start from TEXCOORD4
struct AttributesPass
{
float3 previousPositionOS : NORMAL; // Contain previous transform position (in case of skinning for example)
// TODO: Caution - For now the tesselation doesn't displace along the normal with Velocity shader as the previous previous position
// conflict with the normal in the semantic. This need to be fix!
};
struct VaryingsPassToPS
{
// Note: Z component is not use currently
// This is the clip space position. Warning, do not confuse with the value of positionCS in PackedVarying which is SV_POSITION and store in unPositionSS
float4 positionCS;
float4 previousPositionCS;
};
// Available interpolator start from TEXCOORD8
struct PackedVaryingsPassToPS
{
// Note: Z component is not use
float3 interpolators0 : TEXCOORD8;
float3 interpolators1 : TEXCOORD9;
};
PackedVaryingsPassToPS PackVaryingsPassToPS(VaryingsPassToPS input)
{
PackedVaryingsPassToPS output;
output.interpolators0 = float3(input.positionCS.xyw);
output.interpolators1 = float3(input.previousPositionCS.xyw);
return output;
}
VaryingsPassToPS UnpackVaryingsPassToPS(PackedVaryingsPassToPS input)
{
VaryingsPassToPS output;
output.positionCS = float4(input.interpolators0.xy, 0.0, input.interpolators0.z);
output.previousPositionCS = float4(input.interpolators1.xy, 0.0, input.interpolators1.z);
return output;
}
#ifdef TESSELLATION_ON
// Available interpolator start from TEXCOORD4
// Same as ToPS here
#define VaryingsPassToDS VaryingsPassToPS
#define PackedVaryingsPassToDS PackedVaryingsPassToPS
#define PackVaryingsPassToDS PackVaryingsPassToPS
#define UnpackVaryingsPassToDS UnpackVaryingsPassToPS
VaryingsPassToDS InterpolateWithBaryCoordsPassToDS(VaryingsPassToDS input0, VaryingsPassToDS input1, VaryingsPassToDS input2, float3 baryCoords)
FragInputs input = UnpackVaryings(packedInput);
VaryingsPassToDS ouput;
TESSELLATION_INTERPOLATE_BARY(positionCS, baryCoords);
TESSELLATION_INTERPOLATE_BARY(previousPositionCS, baryCoords);
return ouput;
}
#endif // TESSELLATION_ON
#ifdef TESSELLATION_ON
#define VaryingsPassType VaryingsPassToDS
#else
#define VaryingsPassType VaryingsPassToPS
#endif
// We will use custom attributes for this pass
#define VARYINGS_NEED_PASS
#include "VertMesh.hlsl"
PackedVaryingsType Vert(AttributesMesh inputMesh,
AttributesPass inputPass)
{
VaryingsType varyingsType;
varyingsType.vmesh = VertMesh(inputMesh);
// It is not possible to correctly generate the motion vector for tesselated geometry as tessellation parameters can change
// from one frame to another (adaptative, lod) + in Unity we only receive information for one non tesselated vertex.
// So motion vetor will be based on interpolate previous position at vertex level instead.
varyingsType.vpass.positionCS = mul(_NonJitteredVP, mul(unity_ObjectToWorld, float4(inputMesh.positionOS, 1.0)));
varyingsType.vpass.previousPositionCS = mul(_PreviousVP, mul(_PreviousM, _HasLastPositionData ? float4(inputPass.previousPositionOS, 1.0) : float4(inputMesh.positionOS, 1.0)));
return PackVaryingsType(varyingsType);
}
#ifdef TESSELLATION_ON
PackedVaryingsToPS VertTesselation(VaryingsToDS input)
{
VaryingsToPS output;
output.vmesh = VertMeshTesselation(input.vmesh);
output.vpass.positionCS = input.vpass.positionCS;
output.vpass.previousPositionCS = input.vpass.previousPositionCS;
return PackVaryingsToPS(output);
}
#include "TessellationShare.hlsl"
#endif // TESSELLATION_ON
float4 Frag(PackedVaryingsToPS packedInput) : SV_Target
{
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.unPositionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.unPositionSS.xy, _ScreenSize.zw);

BuiltinData builtinData;
GetSurfaceAndBuiltinData(input, V, posInput, surfaceData, builtinData);
VaryingsPassToPS inputPass = UnpackVaryingsPassToPS(packedInput.vpass);
#ifdef _DEPTHOFFSET_ON
inputPass.positionCS.w += builtinData.depthOffset;
inputPass.previousPositionCS.w += builtinData.depthOffset;
#endif
// TODO: How to allow overriden velocity vector from GetSurfaceAndBuiltinData ?
float2 velocity = CalculateVelocity(inputPass.positionCS, inputPass.previousPositionCS);
EncodeVelocity(builtinData.velocity, outBuffer);
EncodeVelocity(velocity, outBuffer);

2
Assets/ScriptableRenderLoop/HDRenderPipeline/Shadow/Shadow.hlsl


// - Could be return by GetShadowTextureCoordinate() and pass to GetPunctualShadowAttenuation(). But in this case, who control the atlas application ?
// TODO:
// Caution: formula doesn't work as we are texture atlas...
// if (max3(abs(NDC.x), abs(NDC.y), 1.0f - texCoordXYZ.z) <= 1.0f) return 1.0;
// if (max3(abs(NDC.x), abs(NDC.y), 1.0 - texCoordXYZ.z) <= 1.0) return 1.0;

16
Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/HDRISky/HDRISkyRenderer.cs


return GetParameters(skyParameters).skyHDRI != null;
}
override public void RenderSky(BuiltinSkyParameters builtinParams, SkyParameters skyParameters)
public override void SetRenderTargets(BuiltinSkyParameters builtinParams)
{
if (builtinParams.depthBuffer == BuiltinSkyParameters.nullRT)
{
Utilities.SetRenderTarget(builtinParams.renderContext, builtinParams.colorBuffer);
}
else
{
Utilities.SetRenderTarget(builtinParams.renderContext, builtinParams.colorBuffer, builtinParams.depthBuffer);
}
}
override public void RenderSky(BuiltinSkyParameters builtinParams, SkyParameters skyParameters, bool renderForCubemap)
{
HDRISkyParameters hdriSkyParams = GetParameters(skyParameters);

var cmd = new CommandBuffer { name = "" };
cmd.DrawMesh(builtinParams.skyMesh, Matrix4x4.identity, m_SkyHDRIMaterial);
cmd.DrawMesh(builtinParams.skyMesh, Matrix4x4.identity, m_SkyHDRIMaterial, 0, renderForCubemap ? 0 : 1);
builtinParams.renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}

113
Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/HDRISky/Resources/SkyHDRI.shader


Shader "Hidden/HDRenderPipeline/Sky/SkyHDRI"
{
SubShader
HLSLINCLUDE
#pragma vertex Vert
#pragma fragment Frag
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#include "Color.hlsl"
#include "Common.hlsl"
#include "CommonLighting.hlsl"
TEXTURECUBE(_Cubemap);
SAMPLERCUBE(sampler_Cubemap);
float4 _SkyParam; // x exposure, y multiplier, z rotation
struct Attributes
Pass
{
ZWrite Off
ZTest LEqual
Blend One Zero
float3 positionCS : POSITION;
float3 eyeVector : NORMAL;
};
HLSLPROGRAM
#pragma target 5.0
#pragma only_renderers d3d11 ps4 // TEMP: unitl we go futher in dev
struct Varyings
{
float4 positionCS : SV_POSITION;
float3 eyeVector : TEXCOORD0;
};
#pragma vertex Vert
#pragma fragment Frag
Varyings Vert(Attributes input)
{
// TODO: implement SV_vertexID full screen quad
Varyings output;
output.positionCS = float4(input.positionCS.xy, UNITY_RAW_FAR_CLIP_VALUE, 1.0);
output.eyeVector = input.eyeVector;
#include "Color.hlsl"
#include "Common.hlsl"
#include "CommonLighting.hlsl"
return output;
}
TEXTURECUBE(_Cubemap);
SAMPLERCUBE(sampler_Cubemap);
float4 Frag(Varyings input) : SV_Target
{
float3 dir = normalize(input.eyeVector);
float4 _SkyParam; // x exposure, y multiplier, z rotation
struct Attributes
{
float3 positionCS : POSITION;
float3 eyeVector : NORMAL;
};
// Rotate direction
float phi = DegToRad(_SkyParam.z);
float cosPhi, sinPhi;
sincos(phi, sinPhi, cosPhi);
float3 rotDirX = float3(cosPhi, 0, -sinPhi);
float3 rotDirY = float3(sinPhi, 0, cosPhi);
dir = float3(dot(rotDirX, dir), dir.y, dot(rotDirY, dir));
struct Varyings
{
float4 positionCS : SV_POSITION;
float3 eyeVector : TEXCOORD0;
};
float3 skyColor = ClampToFloat16Max(SAMPLE_TEXTURECUBE_LOD(_Cubemap, sampler_Cubemap, dir, 0).rgb * exp2(_SkyParam.x) * _SkyParam.y);
return float4(skyColor, 1.0);
}
Varyings Vert(Attributes input)
{
// TODO: implement SV_vertexID full screen quad
Varyings output;
output.positionCS = float4(input.positionCS.xy, UNITY_RAW_FAR_CLIP_VALUE, 1.0);
output.eyeVector = input.eyeVector;
ENDHLSL
return output;
}
SubShader
{
Pass
{
ZWrite Off
ZTest Always
Blend One Zero
float4 Frag(Varyings input) : SV_Target
{
float3 dir = normalize(input.eyeVector);
HLSLPROGRAM
ENDHLSL
// Rotate direction
float phi = DegToRad(_SkyParam.z);
float cosPhi, sinPhi;
sincos(phi, sinPhi, cosPhi);
float3 rotDirX = float3(cosPhi, 0, -sinPhi);
float3 rotDirY = float3(sinPhi, 0, cosPhi);
dir = float3(dot(rotDirX, dir), dir.y, dot(rotDirY, dir));
}
float3 skyColor = ClampToFloat16Max(SAMPLE_TEXTURECUBE_LOD(_Cubemap, sampler_Cubemap, dir, 0).rgb * exp2(_SkyParam.x) * _SkyParam.y);
return float4(skyColor, 1.0);
}
Pass
{
ZWrite Off
ZTest LEqual
Blend One Zero
HLSLPROGRAM
ENDHLSL
}

30
Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkyParameters.cs


public Gradient worldMieColorRamp = null;
public float worldMieDensity = 15f;
public float worldMieExtinctionFactor = 0f;
public float worldMieNearScatterPush = 0f;
public float worldNearScatterPush = 0f;
public float worldNormalDistance = 1000f;
public float worldRayleighColorIntensity = 1f;
public Gradient worldRayleighColorRamp = null;

public float worldRayleighNearScatterPush = 0f;
public float heightNearScatterPush = 0f;
public float heightMieNearScatterPush = 0f;
public float heightRayleighNearScatterPush = 0f;
public float heightSeaLevel = 0f;
/*

public void OnValidate()
{
worldMieDensity = Mathf.Clamp(worldMieDensity, 0f, 1000f);
worldMiePhaseAnisotropy = Mathf.Clamp01(worldMiePhaseAnisotropy);
worldNearScatterPush = Mathf.Clamp(worldNearScatterPush, -200f, 300f);
worldNormalDistance = Mathf.Clamp(worldNormalDistance, 1f, 10000f);
worldRayleighDensity = Mathf.Clamp(worldRayleighDensity, 0, 1000f);
worldRayleighIndirectScatter = Mathf.Clamp(worldRayleighIndirectScatter, 0f, 1f);
worldMieDensity = Mathf.Clamp(worldMieDensity, 0f, 1000f);
worldMiePhaseAnisotropy = Mathf.Clamp01(worldMiePhaseAnisotropy);
worldMieNearScatterPush = Mathf.Clamp(worldMieNearScatterPush, -200f, 300f);
worldNormalDistance = Mathf.Clamp(worldNormalDistance, 1f, 10000f);
worldRayleighDensity = Mathf.Clamp(worldRayleighDensity, 0, 1000f);
worldRayleighIndirectScatter = Mathf.Clamp(worldRayleighIndirectScatter, 0f, 1f);
worldRayleighNearScatterPush = Mathf.Clamp(worldRayleighNearScatterPush, -200f, 300f);
heightMieDensity = Mathf.Clamp(heightMieDensity, 0, 1000f);
heightNearScatterPush = Mathf.Clamp(heightNearScatterPush, -200f, 300f);
heightNormalDistance = Mathf.Clamp(heightNormalDistance, 1f, 10000f);
heightRayleighDensity = Mathf.Clamp(heightRayleighDensity, 0, 1000f);
heightMieDensity = Mathf.Clamp(heightMieDensity, 0, 1000f);
heightMieNearScatterPush = Mathf.Clamp(heightMieNearScatterPush, -200f, 300f);
heightNormalDistance = Mathf.Clamp(heightNormalDistance, 1f, 10000f);
heightRayleighDensity = Mathf.Clamp(heightRayleighDensity, 0, 1000f);
heightRayleighNearScatterPush = Mathf.Clamp(heightRayleighNearScatterPush, -200f, 300f);
worldScaleExponent = Mathf.Clamp(worldScaleExponent, 1f, 2f);
worldScaleExponent = Mathf.Clamp(worldScaleExponent, 1f, 2f);
/*
occlusionBias = Mathf.Clamp01(occlusionBias);

73
Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkyRenderer.cs


allParams.worldRayleighColorRamp != null;
}
void SetKeywords(BuiltinSkyParameters builtinParams, ProceduralSkyParameters param)
public override void SetRenderTargets(BuiltinSkyParameters builtinParams)
{
// We do not bind the depth buffer as a depth-stencil target since it is
// bound as a color texture which is then sampled from within the shader.
Utilities.SetRenderTarget(builtinParams.renderContext, builtinParams.colorBuffer);
}
void SetKeywords(BuiltinSkyParameters builtinParams, ProceduralSkyParameters param, bool renderForCubemap)
{
// Ensure that all preprocessor symbols are initially undefined.
m_ProceduralSkyMaterial.DisableKeyword("ATMOSPHERICS");

*/
// Expected to be valid for the sky pass, and invalid for the cube map generation pass.
if (builtinParams.depthBuffer != BuiltinSkyParameters.invalidRTI)
if (!renderForCubemap)
{
m_ProceduralSkyMaterial.EnableKeyword("PERFORM_SKY_OCCLUSION_TEST");
}

}
}
void SetUniforms(BuiltinSkyParameters builtinParams, ProceduralSkyParameters param)
void SetUniforms(BuiltinSkyParameters builtinParams, ProceduralSkyParameters param, bool renderForCubemap, ref MaterialPropertyBlock properties)
m_ProceduralSkyMaterial.SetTexture("_Cubemap", param.skyHDRI);
m_ProceduralSkyMaterial.SetVector("_SkyParam", new Vector4(param.exposure, param.multiplier, param.rotation, 0.0f));
m_ProceduralSkyMaterial.SetMatrix("_ViewProjMatrix", builtinParams.viewProjMatrix);
m_ProceduralSkyMaterial.SetMatrix("_InvViewProjMatrix", builtinParams.invViewProjMatrix);
m_ProceduralSkyMaterial.SetVector("_CameraPosWS", builtinParams.cameraPosWS);
m_ProceduralSkyMaterial.SetVector("_ScreenSize", builtinParams.screenSize);
properties.SetTexture("_Cubemap", param.skyHDRI);
properties.SetVector("_SkyParam", new Vector4(param.exposure, param.multiplier, param.rotation, 0.0f));
properties.SetMatrix("_InvViewProjMatrix", builtinParams.invViewProjMatrix);
properties.SetVector("_CameraPosWS", builtinParams.cameraPosWS);
properties.SetVector("_ScreenSize", builtinParams.screenSize);
m_ProceduralSkyMaterial.SetInt("_AtmosphericsDebugMode", (int)param.debugMode);

var pixelRect = new Rect(0f, 0f, builtinParams.screenSize.x, builtinParams.screenSize.y);
var scale = 1.0f; //(float)(int)occlusionDownscale;
var depthTextureScaledTexelSize = new Vector4(scale / pixelRect.width,
scale / pixelRect.height,
-scale / pixelRect.width,
-scale / pixelRect.height);
properties.SetVector("_DepthTextureScaledTexelSize", depthTextureScaledTexelSize);
/*
m_ProceduralSkyMaterial.SetFloat("_ShadowBias", useOcclusion ? occlusionBias : 1f);
m_ProceduralSkyMaterial.SetFloat("_ShadowBiasIndirect", useOcclusion ? occlusionBiasIndirect : 1f);

m_ProceduralSkyMaterial.SetVector("_OcclusionTexture_TexelSize", ???);
*/
var pixelRect = new Rect(0f, 0f, builtinParams.screenSize.x, builtinParams.screenSize.y);
var scale = 1.0f; //(float)(int)occlusionDownscale;
var depthTextureScaledTexelSize = new Vector4(scale / pixelRect.width,
scale / pixelRect.height,
-scale / pixelRect.width,
-scale / pixelRect.height);
m_ProceduralSkyMaterial.SetVector("_DepthTextureScaledTexelSize", depthTextureScaledTexelSize);
m_ProceduralSkyMaterial.SetFloat("_WorldNearScatterPush", -Mathf.Pow(Mathf.Abs(param.worldNearScatterPush), param.worldScaleExponent) * Mathf.Sign(param.worldNearScatterPush));
m_ProceduralSkyMaterial.SetFloat("_WorldMieNearScatterPush", -Mathf.Pow(Mathf.Abs(param.worldMieNearScatterPush), param.worldScaleExponent) * Mathf.Sign(param.worldMieNearScatterPush));
m_ProceduralSkyMaterial.SetFloat("_WorldRayleighNearScatterPush", -Mathf.Pow(Mathf.Abs(param.worldRayleighNearScatterPush), param.worldScaleExponent) * Mathf.Sign(param.worldRayleighNearScatterPush));
m_ProceduralSkyMaterial.SetFloat("_WorldRayleighDensity", -param.worldRayleighDensity / 100000f);
m_ProceduralSkyMaterial.SetFloat("_WorldMieDensity", -param.worldMieDensity / 100000f);

m_ProceduralSkyMaterial.SetVector("_MieColorP20", (Vector4)mieColorP20 * param.worldMieColorIntensity);
m_ProceduralSkyMaterial.SetFloat("_HeightNormalDistanceRcp", 1f / param.heightNormalDistance);
m_ProceduralSkyMaterial.SetFloat("_HeightNearScatterPush", -Mathf.Pow(Mathf.Abs(param.heightNearScatterPush), param.worldScaleExponent) * Mathf.Sign(param.heightNearScatterPush));
m_ProceduralSkyMaterial.SetFloat("_HeightRayleighDensity", -param.heightRayleighDensity / 100000f);
m_ProceduralSkyMaterial.SetFloat("_HeightMieDensity", -param.heightMieDensity / 100000f);
m_ProceduralSkyMaterial.SetFloat("_HeightMieNearScatterPush", -Mathf.Pow(Mathf.Abs(param.heightMieNearScatterPush), param.worldScaleExponent) * Mathf.Sign(param.heightMieNearScatterPush));
m_ProceduralSkyMaterial.SetFloat("_HeightRayleighNearScatterPush", -Mathf.Pow(Mathf.Abs(param.heightRayleighNearScatterPush), param.worldScaleExponent) * Mathf.Sign(param.heightRayleighNearScatterPush));
// m_ProceduralSkyMaterial.SetFloat("_HeightRayleighDensity", -param.heightRayleighDensity / 100000f);
// m_ProceduralSkyMaterial.SetFloat("_HeightMieDensity", -param.heightMieDensity / 100000f);
m_ProceduralSkyMaterial.SetFloat("_HeightSeaLevel", param.heightSeaLevel);
m_ProceduralSkyMaterial.SetVector("_HeightPlaneShift", param.heightPlaneShift);
m_ProceduralSkyMaterial.SetFloat("_HeightDistanceRcp", 1f / param.heightDistance);

m_ProceduralSkyMaterial.SetFloat("_MiePhaseAnisotropy", param.worldMiePhaseAnisotropy);
m_ProceduralSkyMaterial.SetFloat("_MieExtinctionFactor", param.worldMieExtinctionFactor);
// Since we use the material for rendering the sky both into the cubemap, and
// during the fullscreen pass, setting the 'PERFORM_SKY_OCCLUSION_TEST' keyword has no effect.
properties.SetFloat("_DisableSkyOcclusionTest", renderForCubemap ? 1.0f : 0.0f);
// We flip the screens-space Y axis in case we follow the D3D convention.
properties.SetFloat("_FlipY", renderForCubemap ? 1.0f : 0.0f);
// We do not render the height fog into the sky IBL cubemap.
properties.SetFloat("_HeightRayleighDensity", renderForCubemap ? -0.0f : -param.heightRayleighDensity / 100000f);
properties.SetFloat("_HeightMieDensity", renderForCubemap ? -0.0f : -param.heightMieDensity / 100000f);
override public void RenderSky(BuiltinSkyParameters builtinParams, SkyParameters skyParameters)
override public void RenderSky(BuiltinSkyParameters builtinParams, SkyParameters skyParameters, bool renderForCubemap)
MaterialPropertyBlock properties = new MaterialPropertyBlock();
SetKeywords(builtinParams, proceduralSkyParams);
SetKeywords(builtinParams, proceduralSkyParams, renderForCubemap);
SetUniforms(builtinParams, proceduralSkyParams);
SetUniforms(builtinParams, proceduralSkyParams, renderForCubemap, ref properties);
if (builtinParams.depthBuffer != BuiltinSkyParameters.invalidRTI)
if (!renderForCubemap)
cmd.DrawMesh(builtinParams.skyMesh, Matrix4x4.identity, m_ProceduralSkyMaterial);
cmd.DrawMesh(builtinParams.skyMesh, Matrix4x4.identity, m_ProceduralSkyMaterial, 0, 0, properties);
builtinParams.renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}

35
Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/ProceduralSky/Resources/AtmosphericScattering.hlsl


uniform float _WorldScaleExponent;
uniform float _WorldNormalDistanceRcp;
uniform float _WorldNearScatterPush;
uniform float _WorldRayleighNearScatterPush;
uniform float _WorldMieNearScatterPush;
uniform float _WorldRayleighDensity;
uniform float _WorldMieDensity;

uniform float3 _MieColorP45;
uniform float _HeightNormalDistanceRcp;
uniform float _HeightNearScatterPush;
uniform float _HeightMieNearScatterPush;
uniform float _HeightRayleighNearScatterPush;
uniform float _HeightRayleighDensity;
uniform float _HeightMieDensity;
uniform float _HeightSeaLevel;

if(angleY >= 0.f) mieColor = lerp(_MieColorO00, _MieColorP20, saturate(angleY / angle20));
else mieColor = lerp(_MieColorM20, _MieColorO00, saturate((angleY + angle20) / angle20));
const float pushedDistance = max(0.f, worldVecLen + _WorldNearScatterPush);
const float pushedDensity = /*HeightDensity **/ pushedDistance /** exp(-scaledWorldPos.y / 8000.f)*/;
const float rayleighScatter = (1.f - exp(_WorldRayleighDensity * pushedDensity)) * rayleighPh;
const float pushedMieDistance = max(0.f, worldVecLen + _WorldMieNearScatterPush);
const float pushedRayleighDistance = max(0.f, worldVecLen + _WorldRayleighNearScatterPush);
const float pushedMieDensity = /*HeightDensity **/ pushedMieDistance /** exp(-scaledWorldPos.y / 8000.f)*/;
const float pushedRayleighDensity = /*HeightDensity **/ pushedRayleighDistance /** exp(-scaledWorldPos.y / 8000.f)*/;
const float rayleighScatter = (1.f - exp(_WorldRayleighDensity * pushedRayleighDensity)) * rayleighPh;
const float mieScatter = (1.f - exp(_WorldMieDensity * pushedDensity));
const float mieScatter = (1.f - exp(_WorldMieDensity * pushedMieDensity));
const float mieScatter = (1.f - exp(_WorldMieDensity * pushedDensity)) * miePh;
const float mieScatter = (1.f - exp(_WorldMieDensity * pushedMieDensity)) * miePh;
const float pushedHeightDistance = max(0.f, worldVecLen + _HeightNearScatterPush);
const float heightScatter = (1.f - exp(_HeightRayleighDensity * pushedHeightDistance)) * HeightDensity;
const float pushedRayleighHeightDistance = max(0.f, worldVecLen + _HeightRayleighNearScatterPush);
const float pushedMieHeightDistance = max(0.f, worldVecLen + _HeightMieNearScatterPush);
const float heightRayleighScatter = (1.f - exp(_HeightRayleighDensity * pushedRayleighHeightDistance)) * HeightDensity;
const float heightMieScatter = (1.f - exp(_HeightMieDensity * pushedHeightDistance)) * HeightDensity;
const float heightMieScatter = (1.f - exp(_HeightMieDensity * pushedMieHeightDistance)) * HeightDensity;
const float heightMieScatter = (1.f - exp(_HeightMieDensity * pushedHeightDistance)) * HeightDensity * miePh;
const float heightMieScatter = (1.f - exp(_HeightMieDensity * pushedMieHeightDistance)) * HeightDensity * miePh;
rayleighColor = lerp(Luminance(rayleighColor).rrr, rayleighColor, saturate(pushedDistance * _WorldNormalDistanceRcp));
float3 heightRayleighColor = lerp(Luminance(_HeightRayleighColor.xyz).rrr, _HeightRayleighColor.xyz, saturate(pushedHeightDistance * _HeightNormalDistanceRcp));
rayleighColor = lerp(Luminance(rayleighColor).rrr, rayleighColor, saturate(pushedRayleighDistance * _WorldNormalDistanceRcp));
float3 heightRayleighColor = lerp(Luminance(_HeightRayleighColor.xyz).rrr, _HeightRayleighColor.xyz, saturate(pushedRayleighHeightDistance * _HeightNormalDistanceRcp));
coords3.rgb = saturate(heightScatter) * heightRayleighColor;
coords3.a = heightScatter;
coords3.rgb = saturate(heightRayleighScatter) * heightRayleighColor;
coords3.a = heightRayleighScatter;
coords2.rgb = mieScatter * mieColor + saturate(heightMieScatter) * mieColor;
coords2.a = mieScatter;

34
Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/ProceduralSky/Resources/SkyProcedural.shader


Pass
{
ZWrite Off
ZTest LEqual
ZTest Always
#pragma target 5.0
#pragma only_renderers d3d11 ps4 // TEMP: unitl we go futher in dev
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#pragma vertex Vert
#pragma fragment Frag

float4 _CameraPosWS;
float4x4 _InvViewProjMatrix;
float4x4 _ViewProjMatrix;
float _DisableSkyOcclusionTest;
float _FlipY;
#define IS_RENDERING_SKY
#include "AtmosphericScattering.hlsl"

sincos(phi, sinPhi, cosPhi);
float3 rotDirX = float3(cosPhi, 0, -sinPhi);
float3 rotDirY = float3(sinPhi, 0, cosPhi);
dir = float3(dot(rotDirX, dir), dir.y, dot(rotDirY, dir));
float3 rotatedDir = float3(dot(rotDirX, dir), dir.y, dot(rotDirY, dir));
// input.positionCS is SV_Position
// input.positionCS is SV_Position
// If the sky box is too far away (depth set to 0), the resulting look is too foggy.
const float skyDepth = 0.002;
// An arbitrary value attempting to match the size of the sky mesh from the Blacksmith demo.
const float skyDepth = 0.00025;
#ifdef PERFORM_SKY_OCCLUSION_TEST
// Determine whether the sky is occluded by the scene geometry.

float skyTexWeight = 1.0;
#endif
UpdatePositionInput(depthRaw, _InvViewProjMatrix, _ViewProjMatrix, posInput);
if (_DisableSkyOcclusionTest != 0.0)
{
depthRaw = skyDepth;
skyTexWeight = 1.0;
}
// Since we only need the world space position, so we don't pass the view-projection matrix.
UpdatePositionInput(depthRaw, _InvViewProjMatrix, k_identity4x4, posInput, _FlipY != 0);
float4 c1, c2, c3;
VolundTransferScatter(posInput.positionWS, c1, c2, c3);

#endif
float3 skyColor = float3(0.0, 0.0, 0.0);
float opacity = extinction;
// Opacity should be proportional to extinction, but this produces wrong results.
// It appears what the algorithm computes is not actually extinction.
float opacity = (1.0 - extinction);
skyColor = SAMPLE_TEXTURECUBE_LOD(_Cubemap, sampler_Cubemap, dir, 0).rgb;
skyColor = SAMPLE_TEXTURECUBE_LOD(_Cubemap, sampler_Cubemap, rotatedDir, 0).rgb;
skyColor *= exp2(_SkyParam.x) * _SkyParam.y;
opacity = 1.0; // Fully overwrite unoccluded scene regions.
}

30
Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/Resources/GGXConvolve.shader


Pass
{
ZWrite Off
ZTest LEqual
ZTest Always
#pragma target 5.0
#pragma only_renderers d3d11 ps4 // TEMP: unitl we go futher in dev
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#pragma multi_compile _ USE_MIS

TEXTURECUBE(_MainTex);
SAMPLERCUBE(sampler_MainTex);
TEXTURE2D(_GgxIblSamples);
#ifdef USE_MIS
TEXTURE2D(_MarginalRowDensities);

float _Level;
float _MaxLevel;
float _LastLevel;
float _InvOmegaP;
half4 Frag(Varyings input) : SV_Target

// Remove view-dependency from GGX, effectively making the BSDF isotropic.
float3 V = N;
float perceptualRoughness = mipmapLevelToPerceptualRoughness(_Level);
float perceptualRoughness = MipmapLevelToPerceptualRoughness(_Level);
uint sampleCount = GetIBLRuntimeFilterSampleCount(_Level);
#ifdef USE_MIS
float4 val = IntegrateLD_MIS(TEXTURECUBE_PARAM(_MainTex, sampler_MainTex),

1024,
false);
#else
uint sampleCount = 0;
switch (_Level)
{
case 1: sampleCount = 21; break;
case 2: sampleCount = 34; break;
case 3: sampleCount = 55; break;
case 4: sampleCount = 89; break;
case 5: sampleCount = 89; break;
case 6: sampleCount = 89; break; // UNITY_SPECCUBE_LOD_STEPS
}
_GgxIblSamples,
_MaxLevel,
_Level - 1,
_LastLevel,
true,
true);
#endif

128
Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/SkyManager.cs


public class BuiltinSkyParameters
{
public Matrix4x4 viewProjMatrix;
public Matrix4x4 invViewProjMatrix;
public Vector3 cameraPosWS;
public Vector4 screenSize;

public RenderTargetIdentifier colorBuffer;
public RenderTargetIdentifier depthBuffer;
public static RenderTargetIdentifier invalidRTI = -1;
public static RenderTargetIdentifier nullRT = -1;
}
public class SkyManager

RenderTexture m_SkyboxConditionalCdfRT = null;
Material m_StandardSkyboxMaterial = null; // This is the Unity standard skybox material. Used to pass the correct cubemap to Enlighten.
Material m_GGXConvolveMaterial = null; // Apply GGX convolution to cubemap
ComputeShader m_BuildProbabilityTablesCS = null;
int m_ConditionalDensitiesKernel = -1;
int m_MarginalRowDensitiesKernel = -1;
IBLFilterGGX m_iblFilterGgx = null;
Vector4 m_CubemapScreenSize;
Matrix4x4[] m_faceCameraViewProjectionMatrix = new Matrix4x4[6];

if (m_SkyboxCubemapRT == null)
{
m_SkyboxCubemapRT = new RenderTexture(resolution, resolution, 1, RenderTextureFormat.ARGBHalf);
m_SkyboxCubemapRT = new RenderTexture(resolution, resolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
m_SkyboxCubemapRT.dimension = TextureDimension.Cube;
m_SkyboxCubemapRT.useMipMap = true;
m_SkyboxCubemapRT.autoGenerateMips = true; // Generate regular mipmap for filtered importance sampling

m_SkyboxGGXCubemapRT = new RenderTexture(resolution, resolution, 1, RenderTextureFormat.ARGBHalf);
m_SkyboxGGXCubemapRT = new RenderTexture(resolution, resolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
m_SkyboxGGXCubemapRT.dimension = TextureDimension.Cube;
m_SkyboxGGXCubemapRT.useMipMap = true;
m_SkyboxGGXCubemapRT.autoGenerateMips = false;

int height = (int)LightSamplingParameters.TextureHeight;
// + 1 because we store the value of the integral of the cubemap at the end of the texture.
m_SkyboxMarginalRowCdfRT = new RenderTexture(height + 1, 1, 1, RenderTextureFormat.RFloat);
m_SkyboxMarginalRowCdfRT.dimension = TextureDimension.Tex2D;
m_SkyboxMarginalRowCdfRT = new RenderTexture(height + 1, 1, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear);
m_SkyboxMarginalRowCdfRT.useMipMap = false;
m_SkyboxMarginalRowCdfRT.autoGenerateMips = false;
m_SkyboxMarginalRowCdfRT.enableRandomWrite = true;

// TODO: switch the format to R16 (once it's available) to save some bandwidth.
m_SkyboxConditionalCdfRT = new RenderTexture(width, height, 1, RenderTextureFormat.RFloat);
m_SkyboxConditionalCdfRT.dimension = TextureDimension.Tex2D;
m_SkyboxConditionalCdfRT = new RenderTexture(width, height, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear);
m_SkyboxConditionalCdfRT.useMipMap = false;
m_SkyboxConditionalCdfRT.autoGenerateMips = false;
m_SkyboxConditionalCdfRT.enableRandomWrite = true;

m_CubemapScreenSize = new Vector4((float)resolution, (float)resolution, 1.0f / (float)resolution, 1.0f / (float)resolution);
}
void RebuildSkyMeshes()
void RebuildSkyMeshes(float nearPlane, float farPlane)
Matrix4x4 cubeProj = Matrix4x4.Perspective(90.0f, 1.0f, 0.1f, 1.0f);
Matrix4x4 cubeProj = Matrix4x4.Perspective(90.0f, 1.0f, nearPlane, farPlane);
Vector3[] lookAtList = {
new Vector3(1.0f, 0.0f, 0.0f),

m_faceCameraViewProjectionMatrix[i] = Utilities.GetViewProjectionMatrix(lookAt, cubeProj);
m_faceCameraInvViewProjectionMatrix[i] = m_faceCameraViewProjectionMatrix[i].inverse;
// When rendering into a texture the render will be flip (due to legacy unity openGL behavior), so we need to flip UV here...
m_CubemapFaceMesh[i] = BuildSkyMesh(Vector3.zero, m_faceCameraInvViewProjectionMatrix[i], true);
}
}

Shader.SetGlobalTexture("_SkyTexture", m_SkyboxGGXCubemapRT);
}
public void Resize()
public void Resize(float nearPlane, float farPlane)
RebuildSkyMeshes();
RebuildSkyMeshes(nearPlane, farPlane);
}
public void Build()

// Create unititialized. Lazy initialization is performed later.
m_iblFilterGgx = new IBLFilterGGX();
m_GGXConvolveMaterial = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/GGXConvolve");
m_BuildProbabilityTablesCS = Resources.Load<ComputeShader>("BuildProbabilityTables");
m_ConditionalDensitiesKernel = m_BuildProbabilityTablesCS.FindKernel("ComputeConditionalDensities");
m_MarginalRowDensitiesKernel = m_BuildProbabilityTablesCS.FindKernel("ComputeMarginalRowDensities");
m_CurrentUpdateTime = 0.0f;
}

Utilities.Destroy(m_StandardSkyboxMaterial);
Utilities.Destroy(m_GGXConvolveMaterial);
Utilities.Destroy(m_SkyboxCubemapRT);
Utilities.Destroy(m_SkyboxGGXCubemapRT);
Utilities.Destroy(m_SkyboxMarginalRowCdfRT);

{
for (int i = 0; i < 6; ++i)
{
Utilities.SetRenderTarget(builtinParams.renderContext, target, ClearFlag.ClearNone, 0, (CubemapFace)i);
builtinParams.viewProjMatrix = m_faceCameraViewProjectionMatrix[i];
builtinParams.depthBuffer = BuiltinSkyParameters.invalidRTI;
m_Renderer.RenderSky(builtinParams, skyParameters);
}
}
private void BuildProbabilityTables(ScriptableRenderContext renderContext)
{
// Bind the input cubemap.
m_BuildProbabilityTablesCS.SetTexture(m_ConditionalDensitiesKernel, "envMap", m_SkyboxCubemapRT);
builtinParams.depthBuffer = BuiltinSkyParameters.nullRT;
// Bind the outputs.
m_BuildProbabilityTablesCS.SetTexture(m_ConditionalDensitiesKernel, "marginalRowDensities", m_SkyboxMarginalRowCdfRT);
m_BuildProbabilityTablesCS.SetTexture(m_ConditionalDensitiesKernel, "conditionalDensities", m_SkyboxConditionalCdfRT);
m_BuildProbabilityTablesCS.SetTexture(m_MarginalRowDensitiesKernel, "marginalRowDensities", m_SkyboxMarginalRowCdfRT);
var cmd = new CommandBuffer() { name = "" };
cmd.DispatchCompute(m_BuildProbabilityTablesCS, m_ConditionalDensitiesKernel, (int)LightSamplingParameters.TextureHeight, 1, 1);
cmd.DispatchCompute(m_BuildProbabilityTablesCS, m_MarginalRowDensitiesKernel, 1, 1, 1);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
Utilities.SetRenderTarget(builtinParams.renderContext, target, ClearFlag.ClearNone, 0, (CubemapFace)i);
m_Renderer.RenderSky(builtinParams, skyParameters, true);
}
}
private void RenderCubemapGGXConvolution(ScriptableRenderContext renderContext, BuiltinSkyParameters builtinParams, SkyParameters skyParams, Texture input, RenderTexture target)

return;
}
if (m_useMIS)
if (!m_iblFilterGgx.IsInitialized())
BuildProbabilityTables(renderContext);
m_iblFilterGgx.Initialize(renderContext);
// Copy the first mip.
// WARNING:
// Since we can't instanciate the parameters anymore (we don't know the final type here)
// we can't make sure that exposure/multiplier etc are at neutral values
// This will be solved with proper CopyTexture
// TEMP code until CopyTexture is implemented for command buffer
// All parameters are neutral because exposure/multiplier have already been applied in the first copy.
//SkyParameters skyParams = new SkyParameters();
//skyParams.exposure = 0.0f;
//skyParams.multiplier = 1.0f;
//skyParams.rotation = 0.0f;
//skyParams.skyHDRI = input;
RenderSkyToCubemap(builtinParams, skyParams, target);
// End temp
//for (int f = 0; f < 6; f++)
// Graphics.CopyTexture(input, f, 0, target, f, 0);
// Copy the first mip
var cmd = new CommandBuffer { name = "" };
for (int f = 0; f < 6; f++)
{
cmd.CopyTexture(input, f, 0, target, f, 0);
}
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
m_GGXConvolveMaterial.EnableKeyword("USE_MIS");
m_GGXConvolveMaterial.SetTexture("_MarginalRowDensities", m_SkyboxMarginalRowCdfRT);
m_GGXConvolveMaterial.SetTexture("_ConditionalDensities", m_SkyboxConditionalCdfRT);
m_iblFilterGgx.FilterCubemapMIS(renderContext, input, target, mipCount, m_SkyboxConditionalCdfRT, m_SkyboxMarginalRowCdfRT, m_CubemapFaceMesh);
m_GGXConvolveMaterial.DisableKeyword("USE_MIS");
m_iblFilterGgx.FilterCubemap(renderContext, input, target, mipCount, m_CubemapFaceMesh);
// Do the convolution on remaining mipmaps
float invOmegaP = (6.0f * input.width * input.width) / (4.0f * Mathf.PI); // Solid angle associated to a pixel of the cubemap;
m_GGXConvolveMaterial.SetTexture("_MainTex", input);
m_GGXConvolveMaterial.SetFloat("_MaxLevel", mipCount - 1);
m_GGXConvolveMaterial.SetFloat("_InvOmegaP", invOmegaP);
for (int mip = 1; mip < ((int)EnvConstants.SpecCubeLodStep + 1); ++mip)
{
MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
propertyBlock.SetFloat("_Level", mip);
for (int face = 0; face < 6; ++face)
{
Utilities.SetRenderTarget(renderContext, target, ClearFlag.ClearNone, mip, (CubemapFace)face);
var cmd = new CommandBuffer { name = "" };
cmd.DrawMesh(m_CubemapFaceMesh[face], Matrix4x4.identity, m_GGXConvolveMaterial, 0, 0, propertyBlock);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
}
}
}

m_BuiltinParameters.renderContext = renderContext;
m_BuiltinParameters.sunLight = sunLight;
m_BuiltinParameters.invViewProjMatrix = camera.invViewProjectionMatrix;
m_BuiltinParameters.viewProjMatrix = camera.viewProjectionMatrix;
m_BuiltinParameters.cameraPosWS = camera.camera.transform.position;
m_BuiltinParameters.screenSize = camera.screenSize;
m_BuiltinParameters.skyMesh = BuildSkyMesh(camera.camera.GetComponent<Transform>().position, m_BuiltinParameters.invViewProjMatrix, false);

Utilities.SetRenderTarget(renderContext, colorBuffer, depthBuffer);
m_Renderer.RenderSky(m_BuiltinParameters, skyParameters);
m_Renderer.SetRenderTargets(m_BuiltinParameters);
m_Renderer.RenderSky(m_BuiltinParameters, skyParameters, false);
}
}
}

4
Assets/ScriptableRenderLoop/HDRenderPipeline/Sky/SkyRenderer.cs


{
abstract public void Build();
abstract public void Cleanup();
abstract public void RenderSky(BuiltinSkyParameters builtinParams, SkyParameters skyParameters);
abstract public void SetRenderTargets(BuiltinSkyParameters builtinParams);
// renderForCubemap: When rendering into a cube map, no depth buffer is available so user has to make sure not to use depth testing or the depth texture.
abstract public void RenderSky(BuiltinSkyParameters builtinParams, SkyParameters skyParameters, bool renderForCubemap);
abstract public bool IsSkyValid(SkyParameters skyParameters);
virtual public bool IsParameterValid(SkyParameters skyParameters) { return false; }

17
Assets/ScriptableRenderLoop/HDRenderPipeline/Utilities.cs


public class Utilities
{
public const RendererConfiguration kRendererConfigurationBakedLighting = RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbeProxyVolume;
public const RendererConfiguration kRendererConfigurationBakedLighting = RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbeProxyVolume;
public static void SetRenderTarget(ScriptableRenderContext renderContext, RenderTargetIdentifier buffer, ClearFlag clearFlag = ClearFlag.ClearNone, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)
public static void SetRenderTarget(ScriptableRenderContext renderContext, RenderTargetIdentifier buffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)
if (clearFlag != ClearFlag.ClearNone)
cmd.ClearRenderTarget((clearFlag & ClearFlag.ClearDepth) != 0, (clearFlag & ClearFlag.ClearColor) != 0, clearColor);
public static void SetRenderTarget(ScriptableRenderContext renderContext, RenderTargetIdentifier buffer, ClearFlag clearFlag = ClearFlag.ClearNone, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)
{
SetRenderTarget(renderContext, buffer, clearFlag, Color.black, miplevel, cubemapFace);
}
SetRenderTarget(renderContext, colorBuffer, depthBuffer, ClearFlag.ClearNone, new Color(0.0f, 0.0f, 0.0f, 0.0f), miplevel, cubemapFace);
SetRenderTarget(renderContext, colorBuffer, depthBuffer, ClearFlag.ClearNone, Color.black, miplevel, cubemapFace);
SetRenderTarget(renderContext, colorBuffer, depthBuffer, clearFlag, new Color(0.0f, 0.0f, 0.0f, 0.0f), miplevel, cubemapFace);
SetRenderTarget(renderContext, colorBuffer, depthBuffer, clearFlag, Color.black, miplevel, cubemapFace);
}
public static void SetRenderTarget(ScriptableRenderContext renderContext, RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthBuffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)

public static HDRenderPipeline GetHDRenderPipeline()
{
HDRenderPipeline renderContext = UnityEngine.Rendering.GraphicsSettings.renderPipeline as HDRenderPipeline;
HDRenderPipeline renderContext = GraphicsSettings.renderPipelineAsset as HDRenderPipeline;
if (renderContext == null)
{
Debug.LogWarning("SkyParameters component can only be used with HDRenderPipeline custom RenderPipeline.");

2
Assets/ScriptableRenderLoop/RenderPasses/ShadowRenderPass.cs


commandBuffer.Dispose();
// Render
loop.DrawShadows(ref settings);
loop.DrawShadows(settings);
}
}
}

9
Assets/ScriptableRenderLoop/ShaderLibrary/API/D3D11.hlsl


// Do not exist on some platform, in this case we need to have a standard name that call a function that will initialize all parameters to 0
#define ZERO_INITIALIZE(type, name) name = (type)0;
// Texture util abstraction
#define CALCULATE_TEXTURE2D_LOD(textureName, samplerName, coord2) textureName.CalculateLevelOfDetail(samplerName, coord2)
// Texture abstraction
#define TEXTURE2D(textureName) Texture2D textureName

#define SAMPLE_TEXTURE2D(textureName, samplerName, coord2) textureName.Sample(samplerName, coord2)
#define SAMPLE_TEXTURE2D_LOD(textureName, samplerName, coord2, lod) textureName.SampleLevel(samplerName, coord2, lod)
#define SAMPLE_TEXTURE2D_BIAS(textureName, samplerName, coord2, bias) textureName.SampleBias(samplerName, coord2, bias)
#define SAMPLE_TEXTURE2D_GRAD(textureName, samplerName, coord2, ddx, ddy) textureName.SampleGrad(samplerName, coord2, ddx, ddy)
#define SAMPLE_TEXTURE2D_ARRAY_BIAS(textureName, samplerName, coord2, index, bias) textureName.SampleBias(samplerName, float3(coord2, index), bias)
#define SAMPLE_TEXTURECUBE_BIAS(textureName, samplerName, coord3, bias) textureName.SampleBias(samplerName, coord3, bias)
#define SAMPLE_TEXTURECUBE_ARRAY_BIAS(textureName, samplerName, coord3, index, bias) textureName.SampleBias(samplerName, float4(coord3, index), bias)
#define SAMPLE_TEXTURE3D(textureName, samplerName, coord3) textureName.Sample(samplerName, coord3)
#define SAMPLE_TEXTURE2D_SHADOW(textureName, samplerName, coord3) textureName.SampleCmpLevelZero(samplerName, (coord3).xy, (coord3).z)
#define SAMPLE_TEXTURE2D_ARRAY_SHADOW(textureName, samplerName, coord3, index) textureName.SampleCmpLevelZero(samplerName, float3((coord3).xy, index), (coord3).z)

9
Assets/ScriptableRenderLoop/ShaderLibrary/API/PSSL.hlsl


// Do not exist on some platform, in this case we need to have a standard name that call a function that will initialize all parameters to 0
#define ZERO_INITIALIZE(type, name) name = (type)0;
// Texture util abstraction
#define CALCULATE_TEXTURE2D_LOD(textureName, samplerName, coord2) textureName.GetLOD(samplerName, coord2)
// Texture abstraction
#define TEXTURE2D(textureName) Texture2D textureName

#define SAMPLE_TEXTURE2D(textureName, samplerName, coord2) textureName.Sample(samplerName, coord2)
#define SAMPLE_TEXTURE2D_LOD(textureName, samplerName, coord2, lod) textureName.SampleLevel(samplerName, coord2, lod)
#define SAMPLE_TEXTURE2D_BIAS(textureName, samplerName, coord2, bias) textureName.SampleBias(samplerName, coord2, bias)
#define SAMPLE_TEXTURE2D_GRAD(textureName, samplerName, coord2, ddx, ddy) textureName.SampleGrad(samplerName, coord2, ddx, ddy)
#define SAMPLE_TEXTURE2D_ARRAY_BIAS(textureName, samplerName, coord2, index, bias) textureName.SampleBias(samplerName, float3(coord2, index), bias)
#define SAMPLE_TEXTURECUBE_BIAS(textureName, samplerName, coord3, bias) textureName.SampleBias(samplerName, coord3, bias)
#define SAMPLE_TEXTURECUBE_ARRAY_BIAS(textureName, samplerName, coord3, index, bias) textureName.SampleBias(samplerName, float4(coord3, index), bias)
#define SAMPLE_TEXTURE3D(textureName, samplerName, coord3) textureName.Sample(samplerName, coord3)
#define SAMPLE_TEXTURE2D_SHADOW(textureName, samplerName, coord3) textureName.SampleCmpLevelZero(samplerName, (coord3).xy, (coord3).z)
#define SAMPLE_TEXTURE2D_ARRAY_SHADOW(textureName, samplerName, coord3, index) textureName.SampleCmpLevelZero(samplerName, float3((coord3).xy, index), (coord3).z)

2
Assets/ScriptableRenderLoop/ShaderLibrary/AreaLighting.hlsl


// Clamp to avoid artifacts. This particular constant gives the best results.
cosTheta = Clamp(cosTheta, -0.9999, 0.9999);
float theta = FastACos(cosTheta);
float res = cross(v1, v2).z * theta * rsqrt(1.0f - cosTheta * cosTheta); // optimization from * 1 / sin(theta)
float res = cross(v1, v2).z * theta * rsqrt(1.0 - cosTheta * cosTheta); // optimization from * 1 / sin(theta)
return res;
}

13
Assets/ScriptableRenderLoop/ShaderLibrary/BSDF.hlsl


return INV_PI * D_GGXNoPI(NdotH, roughness);
}
float D_GGX_Inverse(float NdotH, float roughness)
{
float a2 = roughness * roughness;
float f = (NdotH * a2 - NdotH) * NdotH + 1.0;
float g = (f * f) / a2;
return PI * g;
}
// Ref: Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs, p. 19, 29.
float G_MaskingSmithGGX(float NdotV, float VdotH, float roughness)
{

float lambdaV = NdotL * sqrt((-NdotV * a2 + NdotV) * NdotV + a2);
float lambdaL = NdotV * sqrt((-NdotL * a2 + NdotL) * NdotL + a2);
// Simplify visibility term: (2.0f * NdotL * NdotV) / ((4.0f * NdotL * NdotV) * (lambda_v + lambda_l));
// Simplify visibility term: (2.0 * NdotL * NdotV) / ((4.0 * NdotL * NdotV) * (lambda_v + lambda_l));
return 0.5 / (lambdaV + lambdaL);
}

lambdaV *= NdotL;
float lambdaL = NdotV * sqrt((-NdotL * a2 + NdotL) * NdotL + a2);
// Simplify visibility term: (2.0f * NdotL * NdotV) / ((4.0f * NdotL * NdotV) * (lambda_v + lambda_l));
// Simplify visibility term: (2.0 * NdotL * NdotV) / ((4.0 * NdotL * NdotV) * (lambda_v + lambda_l));
return 0.5 / (lambdaV + lambdaL);
}

51
Assets/ScriptableRenderLoop/ShaderLibrary/Common.hlsl


#include "API/PSSL.hlsl"
#elif defined(SHADER_API_XBOXONE)
#include "API/D3D11_1.hlsl"
#elif defined(SHADER_API_METAL)
#include "API/Metal.hlsl"
#else
#error unsupported shader api
#endif

float3 adir = abs(dir);
// +Z -Z
faceIndex = dir.z > 0.0f ? CUBEMAPFACE_NEGATIVE_Z : CUBEMAPFACE_POSITIVE_Z;
faceIndex = dir.z > 0.0 ? CUBEMAPFACE_NEGATIVE_Z : CUBEMAPFACE_POSITIVE_Z;
// +X -X
if (adir.x > adir.y && adir.x > adir.z)

{
float x = abs(inX);
float res = (0.0468878 * x + -0.203471) * x + 1.570796; // p(x)
res *= sqrt(1.0f - x);
res *= sqrt(1.0 - x);
return (inX >= 0) ? res : PI - res; // Undo range reduction
}

return x * x * (3.0 - (2.0 * x));
}
const float3x3 k_identity3x3 = {1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0};
static const float3x3 k_identity3x3 = {1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0};
const float4x4 k_identity4x4 = {1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0 };
static const float4x4 k_identity4x4 = {1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0};
// Using pow often result to a warning like this
// "pow(f, e) will not work for negative f, use abs(f) or conditionally handle negative values if you expect them"

}
// ----------------------------------------------------------------------------
// Texture utilities
// ----------------------------------------------------------------------------
// texelSize is Unity XXX_TexelSize feature parameters
// x contains 1.0/width, y contains 1.0 / height, z contains width, w contains height
float ComputeTextureLOD(float2 uv, float4 texelSize)
{
uv *= texelSize.zw;
float2 ddx_ = ddx(uv);
float2 ddy_ = ddy(uv);
float d = max(dot(ddx_, ddx_), dot(ddy_, ddy_));
return max(0.5 * log2(d), 0.0);
}
// ----------------------------------------------------------------------------
// Texture format sampling
// ----------------------------------------------------------------------------

// From deferred or compute shader
// depth must be the depth from the raw depth buffer. This allow to handle all kind of depth automatically with the inverse view projection matrix.
// For information. In Unity Depth is always in range 0..1 (even on OpenGL) but can be reversed.
void UpdatePositionInput(float depth, float4x4 invViewProjectionMatrix, float4x4 ViewProjectionMatrix, inout PositionInputs posInput)
// It may be necessary to flip the Y axis as the origin of the screen-space coordinate system
// of Direct3D is at the top left corner of the screen, with the Y axis pointing downwards.
void UpdatePositionInput(float depth, float4x4 invViewProjectionMatrix, float4x4 ViewProjectionMatrix,
inout PositionInputs posInput, bool flipY = false)
// TODO: Do we need to flip Y axis here on OGL ?
posInput.positionCS = float4(posInput.positionSS.xy * 2.0 - 1.0, depth, 1.0);
float4 hpositionWS = mul(invViewProjectionMatrix, posInput.positionCS);
float2 screenSpacePos;
screenSpacePos.x = posInput.positionSS.x;
screenSpacePos.y = flipY ? 1.0 - posInput.positionSS.y : posInput.positionSS.y;
posInput.positionCS = float4(screenSpacePos * 2.0 - 1.0, depth, 1.0);
float4 hpositionWS = mul(invViewProjectionMatrix, posInput.positionCS);
posInput.positionWS = hpositionWS.xyz / hpositionWS.w;
// The compiler should optimize this (less expensive than reconstruct depth VS from depth buffer)

10
Assets/ScriptableRenderLoop/ShaderLibrary/CommonLighting.hlsl


float SmoothDistanceAttenuation(float squaredDistance, float invSqrAttenuationRadius)
{
float factor = squaredDistance * invSqrAttenuationRadius;
float smoothFactor = saturate(1.0f - factor * factor);
float smoothFactor = saturate(1.0 - factor * factor);
return smoothFactor * smoothFactor;
}

{
float sqrDist = dot(unL, unL);
float attenuation = 1.0f / (max(PUNCTUAL_LIGHT_THRESHOLD * PUNCTUAL_LIGHT_THRESHOLD, sqrDist));
float attenuation = 1.0 / (max(PUNCTUAL_LIGHT_THRESHOLD * PUNCTUAL_LIGHT_THRESHOLD, sqrDist));
// Non physically based hack to limit light influence to attenuationRadius.
attenuation *= SmoothDistanceAttenuation(sqrDist, invSqrAttenuationRadius);

// NdotV should not be negative for visible pixels, but it can happen due to the
// perspective projection and the normal mapping + decals. In that case, the normal
// should be modified to become valid (i.e facing the camera) to avoid weird artifacts.
// Note: certain applications (e.g. SpeedTree) make use of double-sided lighting.
// Note: certain applications (e.g. SpeedTree) require to still have negative normal to perform their own two sided lighting
// This will potentially reduce the length of the normal at edges of geometry.
float GetShiftedNdotV(inout float3 N, float3 V, bool twoSided)
{

float a = 1.0 / (1.0 + N.z);
float b = -N.x * N.y * a;
tangentX = float3(1.0f - N.x * N.x * a , b, -N.x);
tangentY = float3(b, 1.0f - N.y * N.y * a, -N.y);
tangentX = float3(1.0 - N.x * N.x * a , b, -N.x);
tangentY = float3(b, 1.0 - N.y * N.y * a, -N.y);
}
*/

7
Assets/ScriptableRenderLoop/ShaderLibrary/CommonMaterial.hlsl


float3 ComputeTriplanarWeights(float3 normal)
{
// Determine the blend weights for the 3 planar projections.
// N_orig is the vertex-interpolated normal vector.
float3 blendWeights = abs(normal);
// Tighten up the blending zone
blendWeights = (blendWeights - 0.2) * 7.0;

float oneMinusT = 1.0 - t;
return float3(oneMinusT, oneMinusT, oneMinusT) + b * t;
}
// MACRO from Legacy Untiy
// Transforms 2D UV by scale/bias property
#define TRANSFORM_TEX(tex, name) ((tex.xy) * name##_ST.xy + name##_ST.zw)
#define GET_TEXELSIZE_NAME(name) (name##_TexelSize)
#endif // UNITY_COMMON_MATERIAL_INCLUDED

111
Assets/ScriptableRenderLoop/ShaderLibrary/ImageBasedLighting.hlsl


// approximating the cone of the specular lobe, and then computing the MIP map level
// which (approximately) covers the footprint of the lobe with a single texel.
// Improves the perceptual roughness distribution.
float perceptualRoughnessToMipmapLevel(float perceptualRoughness)
float PerceptualRoughnessToMipmapLevel(float perceptualRoughness)
{
perceptualRoughness = perceptualRoughness * (1.7 - 0.7 * perceptualRoughness);

// which (approximately) covers the footprint of the lobe with a single texel.
// Improves the perceptual roughness distribution and adds reflection (contact) hardening.
// TODO: optimize!
float perceptualRoughnessToMipmapLevel(float perceptualRoughness, float NdotR)
float PerceptualRoughnessToMipmapLevel(float perceptualRoughness, float NdotR)
{
float m = PerceptualRoughnessToRoughness(perceptualRoughness);

}
// The inverse of the *approximated* version of perceptualRoughnessToMipmapLevel().
float mipmapLevelToPerceptualRoughness(float mipmapLevel)
float MipmapLevelToPerceptualRoughness(float mipmapLevel)
{
float perceptualRoughness = saturate(mipmapLevel / UNITY_SPECCUBE_LOD_STEPS);

return acc / sampleCount;
}
uint GetIBLRuntimeFilterSampleCount(uint mipLevel)
{
uint sampleCount = 0;
switch (mipLevel)
{
case 1: sampleCount = 21; break;
case 2: sampleCount = 34; break;
case 3: sampleCount = 55; break;
case 4: sampleCount = 89; break;
case 5: sampleCount = 89; break;
case 6: sampleCount = 89; break; // UNITY_SPECCUBE_LOD_STEPS
}
return sampleCount;
}
float3 V,
float3 N,
float roughness,
float maxMipLevel,
float invOmegaP,
uint sampleCount, // Must be a Fibonacci number
bool prefilter)
TEXTURE2D(ggxIblSamples),
float3 V,
float3 N,
float roughness,
float index, // Current MIP level minus one
float lastMipLevel,
float invOmegaP,
uint sampleCount, // Must be a Fibonacci number
bool prefilter,
bool usePrecomputedSamples)
// Bias samples towards the mirror direction to reduce variance.
// This will have a side effect of making the reflection sharper.
// Ref: Stochastic Screen-Space Reflections, p. 67.
const float bias = 0.5 * roughness;
float2 u = Fibonacci2d(i, sampleCount);
float3 L;
float NdotL, NdotH, VdotH;
bool isValid;
if (usePrecomputedSamples)
{
float3 localL = LOAD_TEXTURE2D(ggxIblSamples, uint2(i, index)).xyz;
L = mul(localL, localToWorld);
NdotL = localL.z;
isValid = true;
}
else
{
float2 u = Fibonacci2d(i, sampleCount);
u.x = lerp(u.x, 0.0, bias);
// Bias samples towards the mirror direction to reduce variance.
// This will have a side effect of making the reflection sharper.
// Ref: Stochastic Screen-Space Reflections, p. 67.
const float bias = 0.1 + 0.2 * roughness;
u.x = lerp(u.x, 0.0, bias);
SampleGGXDir(u, V, localToWorld, roughness, L, NdotL, NdotH, VdotH, true);
float3 L;
float NdotL, NdotH, VdotH;
SampleGGXDir(u, V, localToWorld, roughness, L, NdotL, NdotH, VdotH, true);
isValid = NdotL > 0.0;
}
float mipLevel;

// can be simplified:
// pdf = D * NdotH / (4 * LdotH) = D * 0.25;
//
// - OmegaS : Solid angle associated to a sample
// - OmegaP : Solid angle associated to a pixel of the cubemap
// - OmegaS : Solid angle associated with the sample
// - OmegaP : Solid angle associated with the texel of the cubemap
float invPdf = D_GGX_Inverse(NdotH, roughness) * 4.0;
// TODO: check the accuracy of the sample's solid angle fit for GGX.
float omegaS = rcp(sampleCount) * invPdf;
float omegaS;
if (usePrecomputedSamples)
{
omegaS = LOAD_TEXTURE2D(ggxIblSamples, uint2(i, index)).w;
}
else
{
float pdf = D_GGX(NdotH, roughness) * 0.25;
// TODO: check the accuracy of the sample's solid angle fit for GGX.
omegaS = rcp(sampleCount) / pdf;
}
// float omegaP = FOUR_PI / (6.0f * cubemapWidth * cubemapWidth);
mipLevel = 0.5 * log2(omegaS * invOmegaP + 1.0);
// float omegaP = FOUR_PI / (6.0 * cubemapWidth * cubemapWidth);
mipLevel = 0.5 * log2(omegaS * invOmegaP);
}
if (isValid)
{
mipLevel = lerp(mipLevel, maxMipLevel, bias);
mipLevel = lerp(mipLevel, lastMipLevel, bias);
// TODO: There is a bug currently where autogenerate mipmap for the cubemap seems to clamp the mipLevel to 6. correct it! Then remove this clamp
// All MIP map levels beyond UNITY_SPECCUBE_LOD_STEPS contain invalid data.
mipLevel = min(mipLevel, UNITY_SPECCUBE_LOD_STEPS);
}
if (NdotL > 0.0)
{
// TODO: use a Gaussian-like filter to generate the MIP pyramid.
float3 val = SAMPLE_TEXTURECUBE_LOD(tex, sampl, L, mipLevel).rgb;

// (LdotH == NdotH) && (NdotV == 1) && (Weight == F * G).
// We use the approximation of Brian Karis from "Real Shading in Unreal Engine 4":
// Weight ≈ NdotL, which produces nearly identical results in practice.
lightInt += NdotL * val;
cbsdfInt += NdotL;
}

2
Assets/ScriptableRenderLoop/ShaderLibrary/Packing.hlsl


vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;
float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;
vResult.w = frac(Le);
vResult.z = (Le - (floor(vResult.w*255.0f)) / 255.0f) / 255.0f;
vResult.z = (Le - (floor(vResult.w * 255.0)) / 255.0) / 255.0;
return vResult;
}

178
Assets/ScriptableRenderLoop/ShaderLibrary/Tessellation.hlsl


#define TESSELLATION_INTERPOLATE_BARY(name, bary) ouput.name = input0.name * bary.x + input1.name * bary.y + input2.name * bary.z
// TODO: Move in geomtry.hlsl
float3 ProjectPointOnPlane(float3 position, float3 planePosition, float3 planeNormal)
{
return position - (dot(position - planePosition, planeNormal) * planeNormal);

return lerp(positionWS, phongPositionWS, shape);
}
// ---- utility functions
float CalcDistanceTessFactor(float3 positionWS, float minDist, float maxDist, float4x4 objectToWorld, float3 cameraPosWS)
// Reference: http://twvideo01.ubm-us.net/o1/vault/gdc10/slides/Bilodeau_Bill_Direct3D11TutorialTessellation.pdf
// Return true if the triangle must be culled
// backFaceCullEpsilon is the threshold of the dot product between view and normal ( < 0 mean we cull)
bool BackFaceCullTriangle(float3 p0, float3 p1, float3 p2, float backFaceCullEpsilon, float3 cameraPosWS)
float dist = distance(positionWS, cameraPosWS);
float f = clamp(1.0 - (dist - minDist) / (maxDist - minDist), 0.01, 1.0);
return f;
float3 edge0 = p1 - p0;
float3 edge2 = p2 - p0;
float3 N = normalize(cross(edge0, edge2));
float3 midpoint = (p0 + p1 + p2) / 3.0;
float3 V = normalize(cameraPosWS - midpoint);
return (dot(V, N) < backFaceCullEpsilon) ? true : false;
float4 UnityCalcTriEdgeTessFactors(float3 triVertexFactors)
float2 GetScreenSpacePosition(float3 positionWS, float4x4 viewProjectionMatrix, float4 screenParams)
float4 tess;
tess.x = 0.5 * (triVertexFactors.y + triVertexFactors.z);
tess.y = 0.5 * (triVertexFactors.x + triVertexFactors.z);
tess.z = 0.5 * (triVertexFactors.x + triVertexFactors.y);
tess.w = (triVertexFactors.x + triVertexFactors.y + triVertexFactors.z) / 3.0f;
return tess;
float4 positionCS = mul(viewProjectionMatrix, float4(positionWS, 1.0));
float2 positionSS = positionCS.xy / positionCS.w;
// TODO: Check if we need to invert y
return (positionSS * 0.5 + 0.5) * float2(screenParams.x, -screenParams.y);
}
// Compute both screen and distance based adaptation - return factor between 0 and 1
float3 GetScreenSpaceTessFactor(float3 p0, float3 p1, float3 p2, float4x4 viewProjectionMatrix, float4 screenParams, float triangleSize)
{
// Get screen space adaptive scale factor
float2 edgeScreenPosition0 = GetScreenSpacePosition(p0, viewProjectionMatrix, screenParams);
float2 edgeScreenPosition1 = GetScreenSpacePosition(p1, viewProjectionMatrix, screenParams);
float2 edgeScreenPosition2 = GetScreenSpacePosition(p2, viewProjectionMatrix, screenParams);
float EdgeScale = 1.0 / triangleSize; // Edge size in reality, but name is simpler
float3 tessFactor;
tessFactor.x = saturate(distance(edgeScreenPosition1, edgeScreenPosition2) * EdgeScale);
tessFactor.y = saturate(distance(edgeScreenPosition0, edgeScreenPosition2) * EdgeScale);
tessFactor.z = saturate(distance(edgeScreenPosition0, edgeScreenPosition1) * EdgeScale);
return tessFactor;
/*
float UnityCalcEdgeTessFactor(float3 wpos0, float3 wpos1, float edgeLen)
float3 GetDistanceBasedTessFactor(float3 p0, float3 p1, float3 p2, float3 cameraPosWS, float tessMinDist, float tessMaxDist)
// distance to edge center
float dist = distance(0.5 * (wpos0 + wpos1), _WorldSpaceCameraPos);
// length of the edge
float len = distance(wpos0, wpos1);
// edgeLen is approximate desired size in pixels
float f = max(len * _ScreenParams.y / (edgeLen * dist), 1.0);
return f;
float3 edgePosition0 = 0.5 * (p1 + p2);
float3 edgePosition1 = 0.5 * (p0 + p2);
float3 edgePosition2 = 0.5 * (p0 + p1);
// TODO: Move to camera relative and change distance to length
float dist0 = distance(edgePosition0, cameraPosWS);
float dist1 = distance(edgePosition1, cameraPosWS);
float dist2 = distance(edgePosition2, cameraPosWS);
// The saturate will handle the produced NaN in case min == max
float fadeDist = tessMaxDist - tessMinDist;
float3 tessFactor;
tessFactor.x = saturate(1.0 - (dist0 - tessMinDist) / fadeDist);
tessFactor.y = saturate(1.0 - (dist1 - tessMinDist) / fadeDist);
tessFactor.z = saturate(1.0 - (dist2 - tessMinDist) / fadeDist);
return tessFactor;
float UnityDistanceFromPlane(float3 pos, float4 plane)
float4 CalcTriEdgeTessFactors(float3 triVertexFactors)
float d = dot(float4(pos, 1.0f), plane);
float4 tess;
tess.x = triVertexFactors.x;
tess.y = triVertexFactors.y;
tess.z = triVertexFactors.z;
tess.w = (triVertexFactors.x + triVertexFactors.y + triVertexFactors.z) / 3.0;
return tess;
}
// TODO: Move in geomtry.hlsl
float DistanceFromPlane(float3 pos, float4 plane)
{
float d = dot(float4(pos, 1.0), plane);
bool UnityWorldViewFrustumCull(float3 wpos0, float3 wpos1, float3 wpos2, float cullEps)
bool WorldViewFrustumCull(float3 p0, float3 p1, float3 p2, float cullEps, float4 cameraWorldClipPlanes[4])
planeTest.x = ((UnityDistanceFromPlane(wpos0, unity_CameraWorldClipPlanes[0]) > -cullEps) ? 1.0f : 0.0f) +
((UnityDistanceFromPlane(wpos1, unity_CameraWorldClipPlanes[0]) > -cullEps) ? 1.0f : 0.0f) +
((UnityDistanceFromPlane(wpos2, unity_CameraWorldClipPlanes[0]) > -cullEps) ? 1.0f : 0.0f);
// right
planeTest.y = ((UnityDistanceFromPlane(wpos0, unity_CameraWorldClipPlanes[1]) > -cullEps) ? 1.0f : 0.0f) +
((UnityDistanceFromPlane(wpos1, unity_CameraWorldClipPlanes[1]) > -cullEps) ? 1.0f : 0.0f) +
((UnityDistanceFromPlane(wpos2, unity_CameraWorldClipPlanes[1]) > -cullEps) ? 1.0f : 0.0f);
// top
planeTest.z = ((UnityDistanceFromPlane(wpos0, unity_CameraWorldClipPlanes[2]) > -cullEps) ? 1.0f : 0.0f) +
((UnityDistanceFromPlane(wpos1, unity_CameraWorldClipPlanes[2]) > -cullEps) ? 1.0f : 0.0f) +
((UnityDistanceFromPlane(wpos2, unity_CameraWorldClipPlanes[2]) > -cullEps) ? 1.0f : 0.0f);
// bottom
planeTest.w = ((UnityDistanceFromPlane(wpos0, unity_CameraWorldClipPlanes[3]) > -cullEps) ? 1.0f : 0.0f) +
((UnityDistanceFromPlane(wpos1, unity_CameraWorldClipPlanes[3]) > -cullEps) ? 1.0f : 0.0f) +
((UnityDistanceFromPlane(wpos2, unity_CameraWorldClipPlanes[3]) > -cullEps) ? 1.0f : 0.0f);
planeTest.x = ((DistanceFromPlane(p0, cameraWorldClipPlanes[0]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p1, cameraWorldClipPlanes[0]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p2, cameraWorldClipPlanes[0]) > -cullEps) ? 1.0 : 0.0);
// right
planeTest.y = ((DistanceFromPlane(p0, cameraWorldClipPlanes[1]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p1, cameraWorldClipPlanes[1]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p2, cameraWorldClipPlanes[1]) > -cullEps) ? 1.0 : 0.0);
// top
planeTest.z = ((DistanceFromPlane(p0, cameraWorldClipPlanes[2]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p1, cameraWorldClipPlanes[2]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p2, cameraWorldClipPlanes[2]) > -cullEps) ? 1.0 : 0.0);
// bottom
planeTest.w = ((DistanceFromPlane(p0, cameraWorldClipPlanes[3]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p1, cameraWorldClipPlanes[3]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p2, cameraWorldClipPlanes[3]) > -cullEps) ? 1.0 : 0.0);
*/
// ---- functions that compute tessellation factors
// Distance based tessellation:
// Tessellation level is "tess" before "minDist" from camera, and linearly decreases to 1
// up to "maxDist" from camera.
float4 DistanceBasedTess(float3 p0, float3 p1, float3 p2, float minDist, float maxDist, float4x4 objectToWorld, float3 cameraPosWS)
{
float3 f;
f.x = CalcDistanceTessFactor(p0, minDist, maxDist, objectToWorld, cameraPosWS);
f.y = CalcDistanceTessFactor(p1, minDist, maxDist, objectToWorld, cameraPosWS);
f.z = CalcDistanceTessFactor(p2, minDist, maxDist, objectToWorld, cameraPosWS);
return UnityCalcTriEdgeTessFactors(f);
}
/*
// Desired edge length based tessellation:
// Approximate resulting edge length in pixels is "edgeLength".
// Does not take viewing FOV into account, just flat out divides factor by distance.
float4 UnityEdgeLengthBasedTess(float4 v0, float4 v1, float4 v2, float edgeLength)
{
float3 pos0 = mul(unity_ObjectToWorld, v0).xyz;
float3 pos1 = mul(unity_ObjectToWorld, v1).xyz;
float3 pos2 = mul(unity_ObjectToWorld, v2).xyz;
float4 tess;
tess.x = UnityCalcEdgeTessFactor(pos1, pos2, edgeLength);
tess.y = UnityCalcEdgeTessFactor(pos2, pos0, edgeLength);
tess.z = UnityCalcEdgeTessFactor(pos0, pos1, edgeLength);
tess.w = (tess.x + tess.y + tess.z) / 3.0f;
return tess;
}
// Same as UnityEdgeLengthBasedTess, but also does patch frustum culling:
// patches outside of camera's view are culled before GPU tessellation. Saves some wasted work.
float4 UnityEdgeLengthBasedTessCull(float4 v0, float4 v1, float4 v2, float edgeLength, float maxDisplacement)
{
float3 pos0 = mul(unity_ObjectToWorld, v0).xyz;
float3 pos1 = mul(unity_ObjectToWorld, v1).xyz;
float3 pos2 = mul(unity_ObjectToWorld, v2).xyz;
float4 tess;
if (UnityWorldViewFrustumCull(pos0, pos1, pos2, maxDisplacement))
{
tess = 0.0f;
}
else
{
tess.x = UnityCalcEdgeTessFactor(pos1, pos2, edgeLength);
tess.y = UnityCalcEdgeTessFactor(pos2, pos0, edgeLength);
tess.z = UnityCalcEdgeTessFactor(pos0, pos1, edgeLength);
tess.w = (tess.x + tess.y + tess.z) / 3.0f;
}
return tess;
}
*/

6
Assets/ScriptableRenderLoop/fptl/FptlLighting.cs


//@TODO: need to get light probes + LPPV too?
settings.inputFilter.SetQueuesOpaque();
settings.rendererConfiguration = RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe;
loop.DrawRenderers(ref settings);
loop.DrawRenderers(settings);
}
void RenderForward(CullResults cull, Camera camera, ScriptableRenderContext loop, bool opaquesOnly)

if (opaquesOnly) settings.inputFilter.SetQueuesOpaque();
else settings.inputFilter.SetQueuesTransparent();
loop.DrawRenderers(ref settings);
loop.DrawRenderers(settings);
}
static void DepthOnlyForForwardOpaques(CullResults cull, Camera camera, ScriptableRenderContext loop)

sorting = { flags = SortFlags.CommonOpaque }
};
settings.inputFilter.SetQueuesOpaque();
loop.DrawRenderers(ref settings);
loop.DrawRenderers(settings);
}
bool usingFptl

292
Assets/ScriptableRenderLoop/fptl/Internal-DeferredComputeShading.compute


#pragma kernel ShadeDeferred_Fptl SHADE_DEFERRED_ENTRY=ShadeDeferred_Fptl USE_FPTL_LIGHTLIST=1 ENABLE_DEBUG=0
#pragma kernel ShadeDeferred_Clustered SHADE_DEFERRED_ENTRY=ShadeDeferred_Clustered USE_CLUSTERED_LIGHTLIST=1 ENABLE_DEBUG=0 //TODO: disabled clustered permutations so far as it leads to the error "All kernels must use same constant buffer layouts"
#pragma kernel ShadeDeferred_Fptl_Debug SHADE_DEFERRED_ENTRY=ShadeDeferred_Fptl_Debug USE_FPTL_LIGHTLIST=1 ENABLE_DEBUG=1
#pragma kernel ShadeDeferred_Clustered_Debug SHADE_DEFERRED_ENTRY=ShadeDeferred_Clustered_Debug USE_CLUSTERED_LIGHTLIST=1 ENABLE_DEBUG=1
#define TILE_SIZE 8
// Hacks to get the header to compile in compute
#define SHADER_TARGET 50
#define UNITY_PBS_USE_BRDF1
#define fixed4 float4
#include "UnityLightingCommon.cginc"
#undef fixed4
float3 EvalMaterial(UnityLight light, UnityIndirect ind);
float3 EvalIndirectSpecular(UnityLight light, UnityIndirect ind);
// uses the optimized single layered light list for opaques only
#ifdef USE_FPTL_LIGHTLIST
#define OPAQUES_ONLY
#endif
#include "TiledLightingTemplate.hlsl"
#include "TiledReflectionTemplate.hlsl"
Texture2D _CameraDepthTexture;
Texture2D _CameraGBufferTexture0;
Texture2D _CameraGBufferTexture1;
Texture2D _CameraGBufferTexture2;
Texture2D _CameraGBufferTexture3;
RWTexture2D<float4> uavOutput : register(u0);
struct v2f {
float4 vertex : SV_POSITION;
float2 texcoord : TEXCOORD0;
};
v2f vert(float4 vertex : POSITION, float2 texcoord : TEXCOORD0)
{
v2f o;
o.vertex = UnityObjectToClipPos(vertex);
o.texcoord = texcoord.xy;
return o;
}
struct StandardData
{
float3 specularColor;
float3 diffuseColor;
float3 normalWorld;
float smoothness;
float occlusion;
float3 emission;
};
struct LocalDataBRDF
{
StandardData gbuf;
// extras
float oneMinusReflectivity;
float3 Vworld;
};
static LocalDataBRDF g_localParams;
StandardData UnityStandardDataFromGbufferAux(float4 gbuffer0, float4 gbuffer1, float4 gbuffer2, float4 gbuffer3)
{
StandardData data;
data.normalWorld = normalize(2 * gbuffer2.xyz - 1);
data.smoothness = gbuffer1.a;
data.diffuseColor = gbuffer0.xyz; data.specularColor = gbuffer1.xyz;
data.occlusion = gbuffer0.a;
data.emission = gbuffer3.xyz;
return data;
}
half3 BRDF3_Direct2(half3 diffColor, half3 specColor, half rlPow4, half smoothness)
{
half LUT_RANGE = 16.0; // must match range in NHxRoughness() function in GeneratedTextures.cpp
// Lookup texture to save instructions
half specular = tex2Dlod(unity_NHxRoughness, half4(rlPow4, SmoothnessToPerceptualRoughness(smoothness), 0, 0)).UNITY_ATTEN_CHANNEL * LUT_RANGE;
#if defined(_SPECULARHIGHLIGHTS_OFF)
specular = 0.0;
#endif
return diffColor + specular * specColor;
}
float3 EvalMaterial(UnityLight light, UnityIndirect ind)
{
StandardData data = g_localParams.gbuf;
return UNITY_BRDF_PBS(data.diffuseColor, data.specularColor, g_localParams.oneMinusReflectivity, data.smoothness, data.normalWorld, g_localParams.Vworld, light, ind);
}
float3 EvalIndirectSpecular(UnityLight light, UnityIndirect ind)
{
StandardData data = g_localParams.gbuf;
return data.occlusion * UNITY_BRDF_PBS(0, data.specularColor, g_localParams.oneMinusReflectivity, data.smoothness, data.normalWorld, g_localParams.Vworld, light, ind).rgb;
}
[numthreads(TILE_SIZE, TILE_SIZE, 1)]
void SHADE_DEFERRED_ENTRY(uint2 dispatchThreadId : SV_DispatchThreadID, uint2 groupId : SV_GroupID)
{
uint2 pixCoord = dispatchThreadId;
float zbufDpth = FetchDepth(_CameraDepthTexture, pixCoord.xy).x;
float linDepth = GetLinearDepth(zbufDpth);
float3 vP = GetViewPosFromLinDepth(pixCoord, linDepth);
float3 vPw = mul(g_mViewToWorld, float4(vP, 1)).xyz;
float3 Vworld = normalize(mul((float3x3) g_mViewToWorld, -vP).xyz); //unity_CameraToWorld
float4 gbuffer0 = _CameraGBufferTexture0.Load(uint3(pixCoord.xy, 0));
float4 gbuffer1 = _CameraGBufferTexture1.Load(uint3(pixCoord.xy, 0));
float4 gbuffer2 = _CameraGBufferTexture2.Load(uint3(pixCoord.xy, 0));
float4 gbuffer3 = _CameraGBufferTexture3.Load(uint3(pixCoord.xy, 0));
StandardData data = UnityStandardDataFromGbufferAux(gbuffer0, gbuffer1, gbuffer2, gbuffer3);
g_localParams.gbuf = data;
g_localParams.oneMinusReflectivity = 1.0 - SpecularStrength(data.specularColor.rgb);
g_localParams.Vworld = Vworld;
uint2 tileCoord = groupId >> 1;
uint numLightsProcessed = 0;
float3 c = data.emission + ExecuteLightList(numLightsProcessed, tileCoord, vP, vPw, Vworld);
uint numReflectionsProcessed = 0;
c += ExecuteReflectionList(numReflectionsProcessed, tileCoord, vP, data.normalWorld, Vworld, data.smoothness);
#if ENABLE_DEBUG
c = OverlayHeatMap(pixCoord & 15, numLightsProcessed, c);
#endif
uavOutput[pixCoord] = float4(c, 1.0);
}
#pragma kernel ShadeDeferred_Fptl SHADE_DEFERRED_ENTRY=ShadeDeferred_Fptl USE_FPTL_LIGHTLIST=1 ENABLE_DEBUG=0
#pragma kernel ShadeDeferred_Clustered SHADE_DEFERRED_ENTRY=ShadeDeferred_Clustered USE_CLUSTERED_LIGHTLIST=1 ENABLE_DEBUG=0 //TODO: disabled clustered permutations so far as it leads to the error "All kernels must use same constant buffer layouts"
#pragma kernel ShadeDeferred_Fptl_Debug SHADE_DEFERRED_ENTRY=ShadeDeferred_Fptl_Debug USE_FPTL_LIGHTLIST=1 ENABLE_DEBUG=1
#pragma kernel ShadeDeferred_Clustered_Debug SHADE_DEFERRED_ENTRY=ShadeDeferred_Clustered_Debug USE_CLUSTERED_LIGHTLIST=1 ENABLE_DEBUG=1
#define TILE_SIZE 8
// Hacks to get the header to compile in compute
#define SHADER_TARGET 50
#define UNITY_PBS_USE_BRDF1
#define fixed4 float4
#include "UnityLightingCommon.cginc"
#undef fixed4
float3 EvalMaterial(UnityLight light, UnityIndirect ind);
float3 EvalIndirectSpecular(UnityLight light, UnityIndirect ind);
// uses the optimized single layered light list for opaques only
#ifdef USE_FPTL_LIGHTLIST
#define OPAQUES_ONLY
#endif
#include "TiledLightingTemplate.hlsl"
#include "TiledReflectionTemplate.hlsl"
UNITY_DECLARE_TEX2D_FLOAT(_CameraDepthTexture);
Texture2D _CameraGBufferTexture0;
Texture2D _CameraGBufferTexture1;
Texture2D _CameraGBufferTexture2;
Texture2D _CameraGBufferTexture3;
RWTexture2D<float4> uavOutput : register(u0);
struct v2f {
float4 vertex : SV_POSITION;
float2 texcoord : TEXCOORD0;
};
v2f vert(float4 vertex : POSITION, float2 texcoord : TEXCOORD0)
{
v2f o;
o.vertex = UnityObjectToClipPos(vertex);
o.texcoord = texcoord.xy;
return o;
}
struct StandardData
{
float3 specularColor;
float3 diffuseColor;
float3 normalWorld;
float smoothness;
float occlusion;
float3 emission;
};
struct LocalDataBRDF
{
StandardData gbuf;
// extras
float oneMinusReflectivity;
float3 Vworld;
};
static LocalDataBRDF g_localParams;
StandardData UnityStandardDataFromGbufferAux(float4 gbuffer0, float4 gbuffer1, float4 gbuffer2, float4 gbuffer3)
{
StandardData data;
data.normalWorld = normalize(2 * gbuffer2.xyz - 1);
data.smoothness = gbuffer1.a;
data.diffuseColor = gbuffer0.xyz; data.specularColor = gbuffer1.xyz;
data.occlusion = gbuffer0.a;
data.emission = gbuffer3.xyz;
return data;
}
half3 BRDF3_Direct2(half3 diffColor, half3 specColor, half rlPow4, half smoothness)
{
half LUT_RANGE = 16.0; // must match range in NHxRoughness() function in GeneratedTextures.cpp
// Lookup texture to save instructions
half specular = tex2Dlod(unity_NHxRoughness, half4(rlPow4, SmoothnessToPerceptualRoughness(smoothness), 0, 0)).UNITY_ATTEN_CHANNEL * LUT_RANGE;
#if defined(_SPECULARHIGHLIGHTS_OFF)
specular = 0.0;
#endif
return diffColor + specular * specColor;
}
float3 EvalMaterial(UnityLight light, UnityIndirect ind)
{
StandardData data = g_localParams.gbuf;
return UNITY_BRDF_PBS(data.diffuseColor, data.specularColor, g_localParams.oneMinusReflectivity, data.smoothness, data.normalWorld, g_localParams.Vworld, light, ind);
}
float3 EvalIndirectSpecular(UnityLight light, UnityIndirect ind)
{
StandardData data = g_localParams.gbuf;
return data.occlusion * UNITY_BRDF_PBS(0, data.specularColor, g_localParams.oneMinusReflectivity, data.smoothness, data.normalWorld, g_localParams.Vworld, light, ind).rgb;
}
[numthreads(TILE_SIZE, TILE_SIZE, 1)]
void SHADE_DEFERRED_ENTRY(uint2 dispatchThreadId : SV_DispatchThreadID, uint2 groupId : SV_GroupID)
{
uint2 pixCoord = dispatchThreadId;
float zbufDpth = FetchDepth(_CameraDepthTexture, pixCoord.xy).x;
float linDepth = GetLinearDepth(zbufDpth);
float3 vP = GetViewPosFromLinDepth(pixCoord, linDepth);
float3 vPw = mul(g_mViewToWorld, float4(vP, 1)).xyz;
float3 Vworld = normalize(mul((float3x3) g_mViewToWorld, -vP).xyz); //unity_CameraToWorld
float4 gbuffer0 = _CameraGBufferTexture0.Load(uint3(pixCoord.xy, 0));
float4 gbuffer1 = _CameraGBufferTexture1.Load(uint3(pixCoord.xy, 0));
float4 gbuffer2 = _CameraGBufferTexture2.Load(uint3(pixCoord.xy, 0));
float4 gbuffer3 = _CameraGBufferTexture3.Load(uint3(pixCoord.xy, 0));
StandardData data = UnityStandardDataFromGbufferAux(gbuffer0, gbuffer1, gbuffer2, gbuffer3);
g_localParams.gbuf = data;
g_localParams.oneMinusReflectivity = 1.0 - SpecularStrength(data.specularColor.rgb);
g_localParams.Vworld = Vworld;
uint2 tileCoord = groupId >> 1;
uint numLightsProcessed = 0;
float3 c = data.emission + ExecuteLightList(numLightsProcessed, tileCoord, vP, vPw, Vworld);
uint numReflectionsProcessed = 0;
c += ExecuteReflectionList(numReflectionsProcessed, tileCoord, vP, data.normalWorld, Vworld, data.smoothness);
#if ENABLE_DEBUG
c = OverlayHeatMap(pixCoord & 15, numLightsProcessed, c);
#endif
uavOutput[pixCoord] = float4(c, 1.0);
}

2
Assets/ScriptableRenderLoop/fptl/Internal-DeferredReflections.shader


#include "TiledReflectionTemplate.hlsl"
Texture2D _CameraDepthTexture;
Texture2D_float _CameraDepthTexture;
Texture2D _CameraGBufferTexture0;
Texture2D _CameraGBufferTexture1;
Texture2D _CameraGBufferTexture2;

2
Assets/ScriptableRenderLoop/fptl/Internal-DeferredShading.shader


#include "TiledLightingTemplate.hlsl"
Texture2D _CameraDepthTexture;
Texture2D_float _CameraDepthTexture;
Texture2D _CameraGBufferTexture0;
Texture2D _CameraGBufferTexture1;
Texture2D _CameraGBufferTexture2;

2
Assets/ScriptableRenderLoop/fptl/LightBoundsDebug.shader


CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 5.0
#pragma target 4.5
#include "UnityCG.cginc"
#include "LightDefinitions.cs.hlsl"

6
Assets/ScriptableRenderLoop/fptl/StandardTest.shader


ZWrite [_ZWrite]
CGPROGRAM
#pragma target 5.0
#pragma target 4.5
// -------------------------------------

ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 5.0
#pragma target 4.5
// TODO: figure out what's needed here wrt. alpha test etc.

ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 5.0
#pragma target 4.5
// -------------------------------------

7
Assets/ScriptableRenderLoop/fptl/lightlistbuild-bigtile.compute


const int totNrEdgePairs = 12*nrFrustEdges;
for(int l=0; l<iNrCoarseLights; l++)
{
const int idxCoarse = lightsListLDS[l];
[branch]if(idxCoarse<(uint) g_iNrVisibLights && g_vLightData[idxCoarse].lightType!=SPHERE_LIGHT) // don't bother doing edge tests for sphere lights since these have camera aligned bboxes.
const uint idxCoarse = lightsListLDS[l];
bool canEnter = idxCoarse<(uint) g_iNrVisibLights;
if(canEnter) canEnter = g_vLightData[idxCoarse].lightType!=SPHERE_LIGHT; // don't bother doing edge tests for sphere lights since these have camera aligned bboxes.
[branch]if(canEnter)
{
SFiniteLightBound lgtDat = g_data[idxCoarse];

603
Assets/TestScenes/HDTest/GlobalIlluminationTest.unity


m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.5456157, g: 0.39781958, b: 0.24038762, a: 1}
m_IndirectSpecularColor: {r: 0.3199536, g: 0.2875398, b: 0.2644253, a: 1}
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0

m_AlbedoBoost: 1
m_TemporalCoherenceThreshold: 1
m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 0
m_EnableBakedLightmaps: 1
serializedVersion: 6
serializedVersion: 7
m_Resolution: 2
m_BakeResolution: 40
m_TextureWidth: 1024

m_FinalGatherFiltering: 1
m_FinalGatherRayCount: 256
m_ReflectionCompression: 2
m_StationaryBakeMode: 1
m_LightingDataAsset: {fileID: 0}
m_StationaryBakeMode: 0
m_BakeBackend: 0
m_PVRSampling: 1
m_PVRSampleCount: 500
m_PVRBounces: 2
m_PVRFiltering: 0
m_PVRFilteringMode: 1
m_PVRCulling: 1
m_PVRFilteringGaussRadiusDirect: 1
m_PVRFilteringGaussRadiusIndirect: 5
m_PVRFilteringGaussRadiusAO: 2
m_PVRFilteringAtrousColorSigma: 1
m_PVRFilteringAtrousNormalSigma: 1
m_PVRFilteringAtrousPositionSigma: 1
m_LightingDataAsset: {fileID: 112000022, guid: 3d51fc2c60f333c44b613049001dfba8,
type: 2}
m_ShadowMaskMode: 2
m_ShadowMaskMode: 0
--- !u!196 &4
NavMeshSettings:
serializedVersion: 2

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 32562342}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!1 &136708337
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 136708338}
m_Layer: 0
m_Name: Base Cases
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &136708338
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 136708337}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 1108908832}
- {fileID: 531912535}
- {fileID: 190482350}
- {fileID: 434333376}
m_Father: {fileID: 1027688891}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &190482349
GameObject:
m_ObjectHideFlags: 0

- component: {fileID: 190482350}
- component: {fileID: 190482351}
m_Layer: 0
m_Name: Light Probe Group
m_Name: Light Probe Group 2
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0

m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 190482349}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_Father: {fileID: 1027688891}
m_RootOrder: 8
m_Father: {fileID: 136708338}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!220 &190482351
LightProbeGroup:

- {x: -1, y: 1, z: -1}
- {x: -1, y: -1, z: 1}
- {x: -1, y: -1, z: -1}
--- !u!1 &213766584
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 213766585}
- component: {fileID: 213766586}
m_Layer: 0
m_Name: SpotLight_Static
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &213766585
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 213766584}
m_LocalRotation: {x: 0.7071068, y: -0, z: -0, w: 0.7071068}
m_LocalPosition: {x: -19.037, y: 3.116, z: -4.49}
m_LocalScale: {x: 1, y: 1.0000005, z: 1.0000005}
m_Children: []
m_Father: {fileID: 1790703653}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 90, y: 0, z: 0}
--- !u!108 &213766586
Light:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 213766584}
m_Enabled: 1
serializedVersion: 8
m_Type: 0
m_Color: {r: 1, g: 0, b: 0, a: 1}
m_Intensity: 50
m_Range: 4
m_SpotAngle: 65.6
m_CookieSize: 10
m_Shadows:
m_Type: 0
m_Resolution: -1
m_CustomResolution: -1
m_Strength: 1
m_Bias: 0.05
m_NormalBias: 0.4
m_NearPlane: 0.2
m_Cookie: {fileID: 0}
m_DrawHalo: 0
m_Flare: {fileID: 0}
m_RenderMode: 0
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_Lightmapping: 2
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_ColorTemperature: 6570
m_UseColorTemperature: 0
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!1 &371098951
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 371098952}
- component: {fileID: 371098955}
- component: {fileID: 371098954}
- component: {fileID: 371098953}
m_Layer: 0
m_Name: Ground
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!4 &371098952
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 371098951}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -15.94, y: 0, z: -4.43}
m_LocalScale: {x: 1.5594857, y: 0.76538473, z: 0.76538473}
m_Children: []
m_Father: {fileID: 1790703653}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!23 &371098953
MeshRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 371098951}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 11d1f3b10d91bf64494441fa6b2c753f, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!64 &371098954
MeshCollider:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 371098951}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Convex: 0
m_InflateMesh: 0
m_SkinWidth: 0.01
m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &371098955
MeshFilter:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 371098951}
m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0}
--- !u!1 &434333375
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 434333376}
m_Layer: 0
m_Name: Geometry
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &434333376
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 434333375}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 1197900220}
- {fileID: 1330031309}
- {fileID: 841702835}
- {fileID: 1617519336}
- {fileID: 1232831964}
- {fileID: 1315831388}
- {fileID: 931864775}
- {fileID: 1543726726}
- {fileID: 696556422}
m_Father: {fileID: 136708338}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &439514135
GameObject:
m_ObjectHideFlags: 0

m_LocalPosition: {x: -0.491, y: 0.438, z: -4.858}
m_LocalScale: {x: 0.34397998, y: 0.34397998, z: 0.34397998}
m_Children: []
m_Father: {fileID: 1027688891}
m_RootOrder: 6
m_Father: {fileID: 136708338}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!220 &531912536
LightProbeGroup:

m_Lightmapping: 4
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_CCT: 6570
m_ColorTemperature: 6570
m_UseColorTemperature: 0
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!114 &565152817

isDoubleSided: 0
areaLightLength: 0
areaLightWidth: 0
--- !u!1 &696556421
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 696556422}
- component: {fileID: 696556425}
- component: {fileID: 696556424}
- component: {fileID: 696556423}
m_Layer: 0
m_Name: Sphere_Chrome
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &696556422
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 696556421}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -7.74, y: 1.191, z: -7.65}
m_LocalScale: {x: 1.6119599, y: 1.6119599, z: 1.6119599}
m_Children: []
m_Father: {fileID: 434333376}
m_RootOrder: 8
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!23 &696556423
MeshRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 696556421}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 19791e90790a8ca489ddca72c4934598, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!135 &696556424
SphereCollider:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 696556421}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Radius: 0.5
m_Center: {x: 0, y: 0, z: 0}
--- !u!33 &696556425
MeshFilter:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 696556421}
m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0}
--- !u!1 &841702834
GameObject:
m_ObjectHideFlags: 0

m_LocalPosition: {x: 0.077, y: 0.504, z: -3.264}
m_LocalScale: {x: 3.030049, y: 1.0127319, z: 0.07942477}
m_Children: []
m_Father: {fileID: 1027688891}
m_RootOrder: 3
m_Father: {fileID: 434333376}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!23 &841702836
MeshRenderer:

m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 2a49749e551c49a44acc0033cbbf7f22, type: 2}
- {fileID: 2100000, guid: 6f11cd0e29fe831488a0ca1f02e62fbb, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

m_LocalPosition: {x: 3.22, y: 0.504, z: -5.45}
m_LocalScale: {x: 3.03005, y: 1.01273, z: 0.07943}
m_Children: []
m_Father: {fileID: 1027688891}
m_RootOrder: 7
m_Father: {fileID: 434333376}
m_RootOrder: 6
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!23 &931864776
MeshRenderer:

m_LocalPosition: {x: 0, y: 0.05, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 1197900220}
- {fileID: 1330031309}
- {fileID: 1108908832}
- {fileID: 841702835}
- {fileID: 1617519336}
- {fileID: 1315831388}
- {fileID: 531912535}
- {fileID: 931864775}
- {fileID: 190482350}
- {fileID: 1232831964}
- {fileID: 1543726726}
- {fileID: 1790703653}
- {fileID: 136708338}
m_Father: {fileID: 0}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}

m_LocalPosition: {x: 0.1, y: 1.905, z: -6.889}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 1027688891}
m_RootOrder: 2
m_Father: {fileID: 136708338}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 45.944004, y: 0, z: 0}
--- !u!108 &1108908833
Light:

serializedVersion: 8
m_Type: 0
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Intensity: 100
m_Intensity: 20
m_Range: 5
m_SpotAngle: 85
m_CookieSize: 10

m_Lightmapping: 4
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_CCT: 6570
m_ColorTemperature: 6570
m_UseColorTemperature: 0
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!114 &1108908834

isDoubleSided: 0
areaLightLength: 0
areaLightWidth: 0
--- !u!1 &1157828761
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 1157828762}
- component: {fileID: 1157828763}
m_Layer: 0
m_Name: SpotLight_Stationnary
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1157828762
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1157828761}
m_LocalRotation: {x: 0.7071068, y: -0, z: -0, w: 0.7071068}
m_LocalPosition: {x: -12.09, y: 3.116, z: -4.49}
m_LocalScale: {x: 1, y: 1.0000005, z: 1.0000005}
m_Children: []
m_Father: {fileID: 1790703653}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 90, y: 0, z: 0}
--- !u!108 &1157828763
Light:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1157828761}
m_Enabled: 1
serializedVersion: 8
m_Type: 0
m_Color: {r: 1, g: 0, b: 0, a: 1}
m_Intensity: 50
m_Range: 4
m_SpotAngle: 65.6
m_CookieSize: 10
m_Shadows:
m_Type: 0
m_Resolution: -1
m_CustomResolution: -1
m_Strength: 1
m_Bias: 0.05
m_NormalBias: 0.4
m_NearPlane: 0.2
m_Cookie: {fileID: 0}
m_DrawHalo: 0
m_Flare: {fileID: 0}
m_RenderMode: 0
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_Lightmapping: 1
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_ColorTemperature: 6570
m_UseColorTemperature: 0
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!1 &1197900219
GameObject:
m_ObjectHideFlags: 0

m_LocalPosition: {x: 0, y: 0, z: -4.43}
m_LocalScale: {x: 1.0426999, y: 0.5117514, z: 0.5117514}
m_Children: []
m_Father: {fileID: 1027688891}
m_Father: {fileID: 434333376}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!23 &1197900221

m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 6abcdf01974b58c45af2b04a9c0fdd13, type: 2}
- {fileID: 2100000, guid: 11d1f3b10d91bf64494441fa6b2c753f, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

- component: {fileID: 1232831966}
- component: {fileID: 1232831965}
m_Layer: 0
m_Name: Sphere_LightProbe (1)
m_Name: Sphere_LightProbe 2
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0

m_LocalPosition: {x: 3.795, y: 0.428, z: -4.97}
m_LocalScale: {x: 0.34223, y: 0.34223, z: 0.34223}
m_Children: []
m_Father: {fileID: 1027688891}
m_RootOrder: 9
m_Father: {fileID: 434333376}
m_RootOrder: 4
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!23 &1232831965
MeshRenderer:

m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 6abcdf01974b58c45af2b04a9c0fdd13, type: 2}
- {fileID: 2100000, guid: 11d1f3b10d91bf64494441fa6b2c753f, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

m_LocalPosition: {x: 0.956, y: 0.428, z: -4.97}
m_LocalScale: {x: 0.34223, y: 0.34223, z: 0.34223}
m_Children: []
m_Father: {fileID: 1027688891}
m_Father: {fileID: 434333376}
m_RootOrder: 5
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!259 &1315831389

m_LightProbeUsage: 2
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 6abcdf01974b58c45af2b04a9c0fdd13, type: 2}
- {fileID: 2100000, guid: 11d1f3b10d91bf64494441fa6b2c753f, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

m_LocalPosition: {x: 0.077, y: 0.504, z: -5.45}
m_LocalScale: {x: 3.0300481, y: 1.0127295, z: 0.07943236}
m_Children: []
m_Father: {fileID: 1027688891}
m_Father: {fileID: 434333376}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!23 &1330031310

m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: c569253e641dc934db7c3595b31890da, type: 2}
- {fileID: 2100000, guid: 8503d063e677b304ab3aaeae30c8f482, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

m_LocalPosition: {x: -6.33, y: 0.428, z: -4.84}
m_LocalScale: {x: 1.6119599, y: 1.6119599, z: 1.6119599}
m_Children: []
m_Father: {fileID: 1027688891}
m_RootOrder: 10
m_Father: {fileID: 434333376}
m_RootOrder: 7
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!23 &1543726727
MeshRenderer:

m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 6abcdf01974b58c45af2b04a9c0fdd13, type: 2}
- {fileID: 2100000, guid: 11d1f3b10d91bf64494441fa6b2c753f, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

m_LocalPosition: {x: -0.486, y: 0.428, z: -4.97}
m_LocalScale: {x: 0.34223, y: 0.34223, z: 0.34223}
m_Children: []
m_Father: {fileID: 1027688891}
m_RootOrder: 4
m_Father: {fileID: 434333376}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!23 &1617519337
MeshRenderer:

m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 6abcdf01974b58c45af2b04a9c0fdd13, type: 2}
- {fileID: 2100000, guid: 11d1f3b10d91bf64494441fa6b2c753f, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1736468424}
m_Mesh: {fileID: 10207, guid: 0000000000000000e000000000000000, type: 0}
--- !u!1 &1790703652
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 1790703653}
m_Layer: 0
m_Name: Baked vs Realtime
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1790703653
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1790703652}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 371098952}
- {fileID: 1863610288}
- {fileID: 1157828762}
- {fileID: 213766585}
m_Father: {fileID: 1027688891}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1845946150
GameObject:
m_ObjectHideFlags: 0

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1845946150}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!1 &1863610287
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 1863610288}
- component: {fileID: 1863610291}
- component: {fileID: 1863610290}
- component: {fileID: 1863610289}
m_Layer: 0
m_Name: Wall
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!4 &1863610288
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1863610287}
m_LocalRotation: {x: -0.7071068, y: 0, z: 0, w: 0.7071068}
m_LocalPosition: {x: -15.94, y: 2.29, z: -0.67}
m_LocalScale: {x: 1.55949, y: 0.76537997, z: 0.48517287}
m_Children: []
m_Father: {fileID: 1790703653}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: -90, y: 0, z: 0}
--- !u!23 &1863610289
MeshRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1863610287}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 11d1f3b10d91bf64494441fa6b2c753f, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!64 &1863610290
MeshCollider:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1863610287}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Convex: 0
m_InflateMesh: 0
m_SkinWidth: 0.01
m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &1863610291
MeshFilter:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1863610287}
m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0}
--- !u!1 &1879932837
GameObject:
m_ObjectHideFlags: 0

m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1879932837}
m_LocalRotation: {x: 0.120674305, y: -0, z: -0, w: 0.9926922}
m_LocalPosition: {x: -0.56, y: 2.81, z: -12.59}
m_LocalRotation: {x: -0.23712413, y: 0.55119413, z: -0.1670836, w: -0.78233004}
m_LocalPosition: {x: 7.422309, y: 6.824472, z: -9.642997}
m_LocalEulerAnglesHint: {x: 13.862, y: 0, z: 0}
m_LocalEulerAnglesHint: {x: 23.241001, y: -51.745003, z: 6.676}
--- !u!114 &1879932843
MonoBehaviour:
m_ObjectHideFlags: 0

exposure: 0
multiplier: 1
resolution: 256
updateMode: 1
updateMode: 0
skyHDRI: {fileID: 8900000, guid: 9b513842339ef704ca63ef696691bc34, type: 3}
skyHDRI: {fileID: 8900000, guid: de78f930088fc194290da7400c89bfb5, type: 3}
--- !u!114 &1944423447
MonoBehaviour:
m_ObjectHideFlags: 0

m_Script: {fileID: 11500000, guid: bc357c46587fc9d4cb8f311794d7d2f3, type: 3}
m_Name:
m_EditorClassIdentifier:
m_SkyRendererTypeName: UnityEngine.Experimental.ScriptableRenderLoop.HDRISkyRenderer
m_SkyRendererTypeName: UnityEngine.Experimental.Rendering.HDPipeline.HDRISkyRenderer
m_ShadowMaxDistance: 1000
m_ShadowCascadeCount: 4
m_ShadowCascadeSplit0: 0.05
m_ShadowCascadeSplit1: 0.2
m_ShadowCascadeSplit2: 0.3
--- !u!4 &1944423448
Transform:
m_ObjectHideFlags: 0

769
Assets/TestScenes/HDTest/HDRenderLoopTest.unity
文件差异内容过多而无法显示
查看文件

49
Assets/TestScenes/HDTest/LayeredLitTest/Material/Layered_BlendColor.mat


m_ShaderKeywords: _ALPHACUTOFFENABLE_OFF _DETAIL_MAP_WITH_NORMAL _DISTORTIONDEPTHTEST_OFF
_DISTORTIONONLY_OFF _EMISSION _EMISSIVE_COLOR _LAYEREDLIT_4_LAYER _LAYEREDLIT_4_LAYERS
_LAYERMASKMAP _LAYER_MAPPING_PLANAR0 _LAYER_MAPPING_PLANAR_0 _LAYER_MAPPING_PLANAR_1
_LAYER_MAPPING_PLANAR_2 _LAYER_MAPPING_PLANAR_3 _LAYER_MASK_VERTEX_COLOR _NORMALMAP_TANGENT_SPACE
_LAYER_MAPPING_PLANAR_2 _LAYER_MAPPING_PLANAR_3 _LAYER_MASK_VERTEX_COLOR _LAYER_MASK_VERTEX_COLOR_MUL
_NORMALMAP_TANGENT_SPACE
m_EnableInstancingVariants: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses:

- _BlendSize1: 0
- _BlendSize2: 0
- _BlendSize3: 0
- _BlendUsingHeight1: 0
- _BlendUsingHeight2: 0
- _BlendUsingHeight3: 0
- _BumpScale: 1
- _CullMode: 2
- _Cutoff: 0.5

- _EmissiveIntensity1: 0
- _EmissiveIntensity2: 0
- _EmissiveIntensity3: 0
- _EnablePerPixelDisplacement: 0
- _HeightAmplitude0: 1
- _HeightAmplitude1: 1
- _HeightAmplitude2: 1
- _HeightAmplitude3: 1
- _HeightCenter0: 0
- _HeightCenter1: 0
- _HeightCenter2: 0
- _HeightCenter3: 0
- _HeightCenterOffset1: 0
- _HeightCenterOffset2: 0
- _HeightCenterOffset3: 0
- _HeightFactor1: 1
- _HeightFactor2: 1
- _HeightFactor3: 1

- _HeightScale1: 1
- _HeightScale2: 1
- _HeightScale3: 1
- _InheritBaseColor1: 0
- _InheritBaseColor2: 0
- _InheritBaseColor3: 0
- _InheritBaseColorThreshold1: 1
- _InheritBaseColorThreshold2: 1
- _InheritBaseColorThreshold3: 1
- _InheritBaseHeight1: 0
- _InheritBaseHeight2: 0
- _InheritBaseHeight3: 0
- _InheritBaseLayer1: 0
- _InheritBaseLayer2: 0
- _InheritBaseLayer3: 0
- _InheritBaseNormal1: 0
- _InheritBaseNormal2: 0
- _InheritBaseNormal3: 0
- _LayerCount: 4
- _LayerMapping0: 2
- _LayerMapping1: 2

- _Metallic1: 0
- _Metallic2: 0
- _Metallic3: 0
- _MinimumOpacity1: 1
- _MinimumOpacity2: 1
- _MinimumOpacity3: 1
- _NormalScale0: 1
- _NormalScale1: 1
- _NormalScale2: 1
- _NormalScale3: 1
- _OpacityAsDensity1: 0
- _OpacityAsDensity2: 0
- _OpacityAsDensity3: 0
- _PPDMaxSamples: 15
- _PPDMinSamples: 5
- _Parallax: 0.02
- _Smoothness: 0.5
- _Smoothness0: 0.5

- _UVMappingPlanar2: 0
- _UVMappingPlanar3: 0
- _UVSec: 0
- _UseBaseLayerMode: 0
- _UseHeightBasedBlendV2: 0
- _VertexColorMode: 1
- _ZTestMode: 8
- _ZWrite: 1
m_Colors:

1
Assets/TestScenes/HDTest/LayeredLitTest/Material/Layered_BlendColor.mat.meta


timeCreated: 1480943223
licenseType: Pro
NativeFormatImporter:
mainObjectFileID: -1
userData: '{"GUIDArray":["fbea672215bd9944f8d9f98d5437e3cb","b91619c97bb14b64b82c0cdeaac0cc68","be6f395f0458348419faf76aca4cf856","000d0f1d5b188ed43a674de93e854997"]}'
assetBundleName:
assetBundleVariant:

45
Assets/TestScenes/HDTest/Material/HDRenderLoopMaterials/CubeTransparent.mat


m_PrefabInternal: {fileID: 0}
m_Name: CubeTransparent
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _ALPHACUTOFFENABLE_OFF _DISTORTIONDEPTHTEST_OFF _DISTORTIONONLY_OFF
_EMISSION _NORMALMAP_TANGENT_SPACE
m_ShaderKeywords: _ALPHACUTOFFENABLE_OFF _DETAIL_MAP_WITH_NORMAL _DISTORTIONDEPTHTEST_OFF
_DISTORTIONONLY_OFF _EMISSION _NORMALMAP_TANGENT_SPACE
m_EnableInstancingVariants: 0
disabledShaderPasses:
- DistortionVectors
- _AnisotropyMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BaseColorMap:
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}
- _DetailMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DiffuseLightingMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DistortionVectorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SubSurfaceRadiusMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _TangentMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}

- _Anisotropy: 0
- _DepthOffsetEnable: 0
- _DetailAOScale: 1
- _DetailAlbedoScale: 1
- _DetailHeightScale: 1
- _DetailMapMode: 0
- _DetailNormalScale: 1
- _DetailSmoothnessScale: 1
- _DistortionEnable: 0
- _EnablePerPixelDisplacement: 0
- _HeightAmplitude: 0.01
- _HeightCenter: 0.5
- _HeightMapMode: 0
- _HeightScale: 1
- _MaterialId: 0

- _Mode: 0
- _NormalMapSpace: 0
- _NormalScale: 1
- _PPDMaxSamples: 15
- _PPDMinSamples: 5
- _Parallax: 0.02
- _Smoothness: 0.5
- _SmoothnessTextureChannel: 0

- _SurfaceType: 1
- _TexWorldScale: 1
- _UVBase: 0
- _UVDetail: 0
- _UVMappingPlanar: 0
- _ZTestMode: 8
- _ZWrite: 0
m_Colors:
- _BaseColor: {r: 0.9117647, g: 0.1273789, b: 0.1273789, a: 0.566}

- _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}

291
Assets/TestScenes/HDTest/Material/HDRenderLoopMaterials/Terrain.mat


m_PrefabInternal: {fileID: 0}
m_Name: Terrain
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _ALPHACUTOFFENABLE_OFF _DISTORTIONDEPTHTEST_OFF _DISTORTIONONLY_OFF
_EMISSION _NORMALMAP_TANGENT_SPACE
m_ShaderKeywords: _ALPHACUTOFFENABLE_OFF _DETAIL_MAP_WITH_NORMAL _DISTORTIONDEPTHTEST_OFF
_DISTORTIONONLY_OFF _EMISSION _NORMALMAP_TANGENT_SPACE
m_EnableInstancingVariants: 0
disabledShaderPasses:
- DistortionVectors
serializedVersion: 2
serializedVersion: 3
- first:
name: _BaseColorMap
second:
- _AnisotropyMap:
- first:
name: _BumpMap
second:
- _BaseColorMap:
- first:
name: _DetailAlbedoMap
second:
- _BumpMap:
- first:
name: _DetailMask
second:
- _DetailAlbedoMap:
- first:
name: _DetailNormalMap
second:
- _DetailMap:
- first:
name: _DiffuseLightingMap
second:
- _DetailMask:
- first:
name: _DiffuseMap
second:
- _DetailNormalMap:
- first:
name: _EmissionMap
second:
- _DiffuseLightingMap:
- first:
name: _EmissiveColorMap
second:
- _DiffuseMap:
- first:
name: _HeightMap
second:
- _DistortionVectorMap:
- first:
name: _MainTex
second:
- _EmissionMap:
- first:
name: _MaskMap
second:
- _EmissiveColorMap:
- first:
name: _MetallicGlossMap
second:
- _HeightMap:
- first:
name: _NormalMap
second:
- _MainTex:
- first:
name: _OcclusionMap
second:
- _MaskMap:
- first:
name: _ParallaxMap
second:
- _MetallicGlossMap:
- first:
name: _SmoothnessMap
second:
- _NormalMap:
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_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SmoothnessMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecMap:
- first:
name: _SpecMap
second:
- _SpecularOcclusionMap:
- first:
name: _SpecularOcclusionMap
second:
- _SubSurfaceRadiusMap:
- first:
name: _SubSurfaceRadiusMap
second:
- _TangentMap:
- first:
name: _AlphaCutoff
second: 0.5
- first:
name: _AlphaCutoffEnable
second: 0
- first:
name: _BlendMode
second: 0
- first:
name: _BumpScale
second: 1
- first:
name: _CullMode
second: 2
- first:
name: _Cutoff
second: 0.5
- first:
name: _DetailNormalMapScale
second: 1
- first:
name: _DistortionDepthTest
second: 0
- first:
name: _DistortionOnly
second: 0
- first:
name: _DoubleSidedMode
second: 0
- first:
name: _DstBlend
second: 0
- first:
name: _EmissiveColorMode
second: 1
- first:
name: _EmissiveIntensity
second: 0
- first:
name: _GlossMapScale
second: 1
- first:
name: _Glossiness
second: 0.5
- first:
name: _GlossyReflections
second: 1
- first:
name: _HeightBias
second: 0
- first:
name: _HeightMapMode
second: 0
- first:
name: _HeightScale
second: 1
- first:
name: _MaterialId
second: 0
- first:
name: _Metalic
second: 0
- first:
name: _Metallic
second: 0
- first:
name: _Mettalic
second: 0
- first:
name: _Mode
second: 0
- first:
name: _NormalMapSpace
second: 0
- first:
name: _OcclusionStrength
second: 1
- first:
name: _Parallax
second: 0.02
- first:
name: _Smoothness
second: 0.5
- first:
name: _SmoothnessTextureChannel
second: 0
- first:
name: _SpecularHighlights
second: 1
- first:
name: _SrcBlend
second: 1
- first:
name: _SubSurfaceRadius
second: 0
- first:
name: _SurfaceType
second: 0
- first:
name: _UVSec
second: 0
- first:
name: _ZWrite
second: 1
- _AlphaCutoff: 0.5
- _AlphaCutoffEnable: 0
- _Anisotropy: 0
- _BlendMode: 0
- _BumpScale: 1
- _CullMode: 2
- _Cutoff: 0.5
- _DepthOffsetEnable: 0
- _DetailAOScale: 1
- _DetailAlbedoScale: 1
- _DetailHeightScale: 1
- _DetailMapMode: 0
- _DetailNormalMapScale: 1
- _DetailNormalScale: 1
- _DetailSmoothnessScale: 1
- _DistortionDepthTest: 0
- _DistortionEnable: 0
- _DistortionOnly: 0
- _DoubleSidedMode: 0
- _DstBlend: 0
- _EmissiveColorMode: 1
- _EmissiveIntensity: 0
- _EnablePerPixelDisplacement: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _HeightAmplitude: 0.01
- _HeightBias: 0
- _HeightCenter: 0.5
- _HeightMapMode: 0
- _HeightScale: 1
- _MaterialId: 0
- _Metalic: 0
- _Metallic: 0
- _Mettalic: 0
- _Mode: 0
- _NormalMapSpace: 0
- _NormalScale: 1
- _OcclusionStrength: 1
- _PPDMaxSamples: 15
- _PPDMinSamples: 5
- _Parallax: 0.02
- _Smoothness: 0.5
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _SubSurfaceRadius: 0
- _SurfaceType: 0
- _TexWorldScale: 1
- _UVBase: 0
- _UVDetail: 0
- _UVMappingPlanar: 0
- _UVSec: 0
- _ZTestMode: 8
- _ZWrite: 1
- first:
name: _BaseColor
second: {r: 1, g: 1, b: 1, a: 1}
- first:
name: _Color
second: {r: 0.5, g: 0.5, b: 0.5, a: 1}
- first:
name: _DiffuseColor
second: {r: 0.7176471, g: 0.7176471, b: 0.7176471, a: 1}
- first:
name: _EmissionColor
second: {r: 0, g: 0, b: 0, a: 1}
- first:
name: _EmissiveColor
second: {r: 0, g: 0, b: 0, a: 1}
- first:
name: _SpecColor
second: {r: 0.04, g: 0.04, b: 0.04, a: 1}
- _BaseColor: {r: 1, g: 1, b: 1, a: 1}
- _Color: {r: 0.5, g: 0.5, b: 0.5, a: 1}
- _DiffuseColor: {r: 0.7176471, g: 0.7176471, b: 0.7176471, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _SpecColor: {r: 0.04, g: 0.04, b: 0.04, a: 1}
- _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}

25
Assets/TestScenes/HDTest/Material/HDRenderLoopMaterials/test details.mat


m_PrefabInternal: {fileID: 0}
m_Name: test details
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _ALPHACUTOFFENABLE_OFF _DETAIL_MAP _DETAIL_MAP_WITH_NORMAL _DISTORTIONDEPTHTEST_OFF
_DISTORTIONONLY_OFF _EMISSION _NORMALMAP _NORMALMAP_TANGENT_SPACE
m_ShaderKeywords: _ALPHACUTOFFENABLE_OFF _DETAIL_MAP_WITH_NORMAL _DISTORTIONDEPTHTEST_OFF
_DISTORTIONONLY_OFF _EMISSION _NORMALMAP_TANGENT_SPACE
m_EnableInstancingVariants: 0
disabledShaderPasses:
- DistortionVectors
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:

m_Offset: {x: 0, y: 0}
- _DiffuseMap:
m_Texture: {fileID: 2800000, guid: d734753529ca78148a43944515a64bc5, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DistortionVectorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:

- _CoatRoughness: 0
- _CullMode: 2
- _Cutoff: 0.5
- _DepthOffsetEnable: 0
- _DetailAOScale: 1
- _DetailAlbedoScale: 1
- _DetailHeightScale: 1

- _DetailSmoothnessScale: 1
- _DistortionDepthTest: 0
- _DistortionEnable: 0
- _DistortionOnly: 0
- _DoubleSided: 1
- _DoubleSidedLigthing: 1

- _EmissiveIntensity: 0
- _EnablePerPixelDisplacement: 0
- _HeightAmplitude: 0.01
- _HeightCenter: 0.5
- _HeightMapMode: 0
- _HeightScale: 1
- _MaterialID: 0

- _Mettalic: 0
- _Mode: 0
- _NormalMapSpace: 0
- _NormalScale: 1
- _PPDMaxSamples: 15
- _PPDMinSamples: 5
- _Parallax: 0.02
- _Smoothness: 0.524
- _SmoothnessTextureChannel: 0

- _SubSurfaceRadius: 0
- _SurfaceType: 0
- _TexWorldScale: 1
- _UVBase: 0
- _UVMappingPlanar: 0
- _ZTestMode: 8
- _ZWrite: 1
m_Colors:
- _BaseColor: {r: 0.5588235, g: 0.5588235, b: 0.5588235, a: 1}

- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _SpecColor: {r: 0.04, g: 0.04, b: 0.04, a: 1}
- _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}

45
Assets/TestScenes/HDTest/Material/HDRenderLoopMaterials/test-transparent.mat


m_PrefabInternal: {fileID: 0}
m_Name: test-transparent
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _ALPHACUTOFFENABLE_OFF _DISTORTIONDEPTHTEST_OFF _DISTORTIONONLY_OFF
_EMISSION _NORMALMAP _NORMALMAP_TANGENT_SPACE
m_ShaderKeywords: _ALPHACUTOFFENABLE_OFF _DETAIL_MAP_WITH_NORMAL _DISTORTIONDEPTHTEST_OFF
_DISTORTIONONLY_OFF _EMISSION _NORMALMAP _NORMALMAP_TANGENT_SPACE
m_EnableInstancingVariants: 0
disabledShaderPasses:
- DistortionVectors
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _AnisotropyMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}

m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}

m_Offset: {x: 0, y: 0}
- _DiffuseMap:
m_Texture: {fileID: 2800000, guid: d734753529ca78148a43944515a64bc5, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DistortionVectorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SubSurfaceRadiusMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _TangentMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}

m_Floats:
- _AlphaCutoff: 0.5
- _AlphaCutoffEnable: 0
- _Anisotropy: 0
- _BlendMode: 0
- _BumpScale: 1
- _CoatCoverage: 0

- _DepthOffsetEnable: 0
- _DetailAOScale: 1
- _DetailAlbedoScale: 1
- _DetailHeightScale: 1
- _DetailMapMode: 0
- _DetailNormalScale: 1
- _DetailSmoothnessScale: 1
- _DistortionEnable: 0
- _DistortionOnly: 0
- _DoubleSided: 1
- _DoubleSidedLigthing: 1

- _EmissiveIntensity: 0
- _EnablePerPixelDisplacement: 0
- _HeightAmplitude: 0.01
- _HeightCenter: 0.5
- _HeightMapMode: 0
- _HeightScale: 1
- _MaterialID: 0

- _Mettalic: 0
- _Mode: 0
- _NormalMapSpace: 0
- _NormalScale: 1
- _PPDMaxSamples: 15
- _PPDMinSamples: 5
- _Parallax: 0.02
- _Smoothness: 0.524
- _SmoothnessTextureChannel: 0

- _SubSurfaceRadius: 0
- _SurfaceType: 1
- _TexWorldScale: 1
- _UVBase: 0
- _UVDetail: 0
- _UVMappingPlanar: 0
- _ZTestMode: 8
- _ZWrite: 0
m_Colors:
- _BaseColor: {r: 1, g: 1, b: 1, a: 0.397}

- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _SpecColor: {r: 0.04, g: 0.04, b: 0.04, a: 1}
- _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}

6
ProjectSettings/GraphicsSettings.asset


- {fileID: 15106, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 10770, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 10782, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 4800000, guid: 36c23fe83f8e7a54d8fb168fa6cf2a3d, type: 3}
- {fileID: 4800000, guid: 595434cc3b6405246b6cd3086d0b6f7d, type: 3}
- {fileID: 16001, guid: 0000000000000000f000000000000000, type: 0}
m_PreloadedShaders: []
m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000,
type: 0}

m_Automatic: 0
m_LightmapStripping: 0
m_FogStripping: 0
m_InstancingStripping: 0
m_LightmapKeepPlain: 1
m_LightmapKeepDirCombined: 1
m_LightmapKeepDynamicPlain: 1

m_FogKeepExp2: 1
m_AlbedoSwatchInfos: []
m_LightsUseLinearIntensity: 1
m_LightsUseCCT: 1
m_LightsUseColorTemperature: 1

158
ProjectSettings/ProjectSettings.asset


defaultScreenHeight: 768
defaultScreenWidthWeb: 960
defaultScreenHeightWeb: 600
m_StereoRenderingPath: 0
m_ActiveColorSpace: 1
m_MTRendering: 1
m_MobileMTRendering: 0

n3dsDisableStereoscopicView: 0
n3dsEnableSharedListOpt: 1
n3dsEnableVSync: 0
uiUse16BitDepthBuffer: 0
ignoreAlphaClear: 0
xboxOneResolution: 0
xboxOneMonoLoggingLevel: 0

metroInputSource: 0
m_HolographicPauseOnTrackingLoss: 1
xboxOneDisableKinectGpuReservation: 0
singlePassStereoRendering: 0
xboxOneEnable7thCore: 0
vrSettings:
cardboard:
depthFormat: 0
enableTransitionView: 0
daydream:
depthFormat: 0
useSustainedPerformanceMode: 0
hololens:
depthFormat: 1
useHDRDisplay: 0
AndroidMinSdkVersion: 9
AndroidMinSdkVersion: 16
AndroidTargetSdkVersion: 0
apiCompatibilityLevel: 2
stripEngineCode: 1
iPhoneStrippingLevel: 0
iPhoneScriptCallOptimization: 0

serializedVersion: 2
m_Bits: 238
iPhoneSdkVersion: 988
iOSTargetOSVersionString: 6.0
iOSTargetOSVersionString: 8.0
tvOSSdkVersion: 0
tvOSRequireExtendedGameController: 0
tvOSTargetOSVersionString: 9.0

tvOSSmallIconLayers: []
tvOSLargeIconLayers: []
tvOSTopShelfImageLayers: []
tvOSTopShelfImageWideLayers: []
iOSLaunchScreenType: 0
iOSLaunchScreenPortrait: {fileID: 0}
iOSLaunchScreenLandscape: {fileID: 0}

iOSURLSchemes: []
iOSBackgroundModes: 0
iOSMetalForceHardShadows: 0
metalEditorSupport: 1
metalAPIValidation: 1
iOSManualSigningProvisioningProfileID:
tvOSManualSigningProvisioningProfileID:
appleEnableAutomaticSigning: 0
AndroidTargetDevice: 0
AndroidSplashScreenScale: 0
androidSplashScreen: {fileID: 0}

- m_BuildTarget: Standalone
m_StaticBatching: 0
m_DynamicBatching: 0
- m_BuildTarget: iPhone
m_StaticBatching: 0
m_DynamicBatching: 0
m_APIs: 11000000
m_APIs: 1000000011000000
m_Automatic: 1
- m_BuildTarget: iOSSupport
m_APIs: 10000000
m_Automatic: 0
m_BuildTargetVRSettings:
- m_BuildTarget: Android

cameraUsageDescription:
locationUsageDescription:
microphoneUsageDescription:
switchNetLibKey:
switchSocketMemoryPoolSize: 6144
switchSocketAllocatorPoolSize: 128
switchSocketConcurrencyLimit: 14
switchUseCPUProfiler: 0
switchApplicationID: 0x0005000C10000001
switchNSODependencies:
switchTitleNames_0:
switchTitleNames_1:
switchTitleNames_2:
switchTitleNames_3:
switchTitleNames_4:
switchTitleNames_5:
switchTitleNames_6:
switchTitleNames_7:
switchTitleNames_8:
switchTitleNames_9:
switchTitleNames_10:
switchTitleNames_11:
switchTitleNames_12:
switchTitleNames_13:
switchTitleNames_14:
switchPublisherNames_0:
switchPublisherNames_1:
switchPublisherNames_2:
switchPublisherNames_3:
switchPublisherNames_4:
switchPublisherNames_5:
switchPublisherNames_6:
switchPublisherNames_7:
switchPublisherNames_8:
switchPublisherNames_9:
switchPublisherNames_10:
switchPublisherNames_11:
switchPublisherNames_12:
switchPublisherNames_13:
switchPublisherNames_14:
switchIcons_0: {fileID: 0}
switchIcons_1: {fileID: 0}
switchIcons_2: {fileID: 0}
switchIcons_3: {fileID: 0}
switchIcons_4: {fileID: 0}
switchIcons_5: {fileID: 0}
switchIcons_6: {fileID: 0}
switchIcons_7: {fileID: 0}
switchIcons_8: {fileID: 0}
switchIcons_9: {fileID: 0}
switchIcons_10: {fileID: 0}
switchIcons_11: {fileID: 0}
switchIcons_12: {fileID: 0}
switchIcons_13: {fileID: 0}
switchIcons_14: {fileID: 0}
switchSmallIcons_0: {fileID: 0}
switchSmallIcons_1: {fileID: 0}
switchSmallIcons_2: {fileID: 0}
switchSmallIcons_3: {fileID: 0}
switchSmallIcons_4: {fileID: 0}
switchSmallIcons_5: {fileID: 0}
switchSmallIcons_6: {fileID: 0}
switchSmallIcons_7: {fileID: 0}
switchSmallIcons_8: {fileID: 0}
switchSmallIcons_9: {fileID: 0}
switchSmallIcons_10: {fileID: 0}
switchSmallIcons_11: {fileID: 0}
switchSmallIcons_12: {fileID: 0}
switchSmallIcons_13: {fileID: 0}
switchSmallIcons_14: {fileID: 0}
switchManualHTML:
switchAccessibleURLs:
switchLegalInformation:
switchMainThreadStackSize: 1048576
switchPresenceGroupId: 0x0005000C10000001
switchLogoHandling: 0
switchReleaseVersion: 0
switchDisplayVersion: 1.0.0
switchStartupUserAccount: 0
switchTouchScreenUsage: 0
switchSupportedLanguagesMask: 0
switchLogoType: 0
switchApplicationErrorCodeCategory:
switchUserAccountSaveDataSize: 0
switchUserAccountSaveDataJournalSize: 0
switchAttribute: 0
switchCardSpecSize: 4
switchCardSpecClock: 25
switchRatingsMask: 0
switchRatingsInt_0: 0
switchRatingsInt_1: 0
switchRatingsInt_2: 0
switchRatingsInt_3: 0
switchRatingsInt_4: 0
switchRatingsInt_5: 0
switchRatingsInt_6: 0
switchRatingsInt_7: 0
switchRatingsInt_8: 0
switchRatingsInt_9: 0
switchRatingsInt_10: 0
switchRatingsInt_11: 0
switchLocalCommunicationIds_0: 0x0005000C10000001
switchLocalCommunicationIds_1:
switchLocalCommunicationIds_2:
switchLocalCommunicationIds_3:
switchLocalCommunicationIds_4:
switchLocalCommunicationIds_5:
switchLocalCommunicationIds_6:
switchLocalCommunicationIds_7:
switchParentalControl: 0
switchAllowsScreenshot: 1
switchDataLossConfirmation: 0
XboxTitleId:
XboxImageXexPath:
XboxSpaPath:

ps4ParamSfxPath:
ps4VideoOutPixelFormat: 0
ps4VideoOutInitialWidth: 1920
ps4VideoOutBaseModeInitialWidth: 1920
ps4VideoOutReprojectionRate: 120
ps4PronunciationXMLPath:
ps4PronunciationSIGPath:

ps4ApplicationParam4: 0
ps4DownloadDataSize: 0
ps4GarlicHeapSize: 2048
ps4ProGarlicHeapSize: 2560
ps4Passcode: frAQBc8Wsa1xVPfvJcrgRYwTiizs2trQ
ps4UseDebugIl2cppLibs: 0
ps4pnSessions: 1

ps4attribShareSupport: 0
ps4attribExclusiveVR: 0
ps4disableAutoHideSplash: 0
ps4videoRecordingFeaturesUsed: 0
ps4contentSearchFeaturesUsed: 0
ps4attribEyeToEyeDistanceSettingVR: 0
ps4IncludedModules: []
monoEnv:
psp2Splashimage: {fileID: 0}

spritePackerPolicy:
webGLMemorySize: 256
webGLExceptionSupport: 1
webGLNameFilesAsHashes: 0
webGLDataCaching: 0
webGLDebugSymbols: 0
webGLEmscriptenArgs:

incrementalIl2cppBuild:
iOS: 0
additionalIl2CppArgs:
apiCompatibilityLevelPerPlatform: {}
m_RenderingPath: 1
m_MobileRenderingPath: 1
metroPackageName: dev

XboxOneSplashScreen: {fileID: 0}
XboxOneAllowedProductIds: []
XboxOnePersistentLocalStorageSize: 0
vrEditorSettings: {}
xboxOneScriptCompiler: 0
vrEditorSettings:
daydream:
daydreamIconForeground: {fileID: 0}
daydreamIconBackground: {fileID: 0}
cloudServicesEnabled:
Analytics: 0
Build: 0

UNet: 0
Unity_Ads: 0
facebookSdkVersion: 7.8.2
apiCompatibilityLevel: 2
enableNewInputSystem: 0

2
ProjectSettings/ProjectVersion.txt


m_EditorVersion: 5.6.0b3
m_EditorVersion: 5.6.0b6

26
Assets/ScriptableRenderLoop/HDRenderPipeline/ShaderPass/FragInputs.hlsl


float2 texCoord2;
float2 texCoord3;
float3 tangentToWorld[3];
float4 vertexColor;
// CAUTION: Only use with velocity currently, null else
// Note: Z component is not use currently
// This is the clip space position. Warning, do not confuse with the value of positionCS in PackedVarying which is SV_POSITION and store in unPositionSS
float4 positionCS;
float4 previousPositionCS;
// end velocity specific
float4 color; // vertex color
void ApplyDepthOffsetAttribute(float depthOffsetVS, inout FragInputs fragInput)
// FragInputs use dir vector that are normalized in the code even if not used
// so we initialize them to a valid != 0 to shutdown compiler warning
FragInputs InitializeFragInputs()
fragInput.positionCS.w += depthOffsetVS;
fragInput.previousPositionCS.w += depthOffsetVS;
FragInputs output;
ZERO_INITIALIZE(FragInputs, output);
output.tangentToWorld[0] = float3(0.0, 0.0, 1.0);
output.tangentToWorld[2] = float3(0.0, 0.0, 1.0);
return output;
}
void GetVaryingsDataDebug(uint paramId, FragInputs input, inout float3 result, inout bool needLinearToSRGB)

result = input.tangentToWorld[2].xyz * 0.5 + 0.5;
break;
case DEBUGVIEWVARYING_VERTEX_COLOR:
result = input.vertexColor.rgb; needLinearToSRGB = true;
result = input.color.rgb; needLinearToSRGB = true;
result = input.vertexColor.aaa;
result = input.color.aaa;
break;
}
}

64
Assets/TestScenes/HDTest/GraphicTest/Two Sided/Material/GroundLeaf_DoubleSidedFlip.mat


m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: GroundLeaf_Albedo
m_Name: GroundLeaf_DoubleSidedFlip
m_ShaderKeywords: _ALPHACUTOFFENABLE_OFF _DISTORTIONDEPTHTEST_OFF _DISTORTIONONLY_OFF
_DOUBLESIDED_LIGHTING_FLIP _EMISSION _MASKMAP _METALLICGLOSSMAP _NORMALMAP _NORMALMAP_TANGENT_SPACE
m_ShaderKeywords: _ALPHATEST_ON _DEPTHOFFSETENABLE_OFF _DETAIL_MAP_WITH_NORMAL _DISTORTIONDEPTHTEST_OFF
_DISTORTIONENABLE_OFF _DISTORTIONONLY_OFF _DOUBLESIDED_LIGHTING_FLIP _EMISSION
_ENABLEPERPIXELDISPLACEMENT_OFF _MASKMAP _METALLICGLOSSMAP _NORMALMAP _NORMALMAP_TANGENT_SPACE
_TESSELLATIONOBJECTSCALE_OFF _TESSELLATION_DISPLACEMENT
m_CustomRenderQueue: -1
stringTagMap: {}
m_EnableInstancingVariants: 0
m_CustomRenderQueue: 2450
stringTagMap:
RenderType: TransparentCutout
disabledShaderPasses:
- DistortionVectors
- _AnisotropyMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BaseColorMap:
m_Texture: {fileID: 2800000, guid: 00447c5eeb984f54d92c80818840a36b, type: 3}
m_Scale: {x: 1, y: 1}

m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DiffuseLightingMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DistortionVectorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SubSurfaceRadiusMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _TangentMap:
- _AlphaCutoffEnable: 0
- _AlphaCutoffEnable: 1
- _Anisotropy: 0
- _DepthOffsetEnable: 0
- _DetailAOScale: 1
- _DetailAlbedoScale: 1
- _DetailHeightScale: 1
- _DetailMapMode: 0
- _DetailNormalScale: 1
- _DetailSmoothnessScale: 1
- _DistortionEnable: 0
- _EnablePerPixelDisplacement: 0
- _HeightAmplitude: 0.32
- _HeightCenter: 0.68
- _HeightMapMode: 0
- _HeightScale: 1
- _MaterialId: 0

- _Mode: 1
- _NormalMapSpace: 0
- _NormalScale: 1
- _PPDMaxSamples: 15
- _PPDMinSamples: 5
- _Parallax: 0.02
- _Smoothness: 0.5
- _SmoothnessTextureChannel: 0

- _SurfaceType: 0
- _TessellationBackFaceCullEpsilon: -0.375
- _TessellationFactor: 4
- _TessellationFactorMaxDistance: 50
- _TessellationFactorMinDistance: 20
- _TessellationFactorTriangleSize: 100
- _TessellationMode: 1
- _TessellationObjectScale: 0
- _TessellationShapeFactor: 0.75
- _TexWorldScale: 1
- _UVBase: 0
- _UVDetail: 0
- _UVMappingPlanar: 0
- _ZTestMode: 8
- _ZWrite: 1
m_Colors:
- _BaseColor: {r: 1, g: 1, b: 1, a: 1}

- _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}

25
Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipelineSetup.asset


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 8b6f86e1523e69a4282e92d393be89a4, type: 3}
m_Name: HDRenderPipelineSetup
m_EditorClassIdentifier:
buildScreenAABBShader: {fileID: 7200000, guid: 728dce960f8a9c44bbc3abb3b851d8f6,
type: 3}
buildPerTileLightListShader: {fileID: 7200000, guid: 65af3444cbf4b3747a4dead7ee00cfee,
type: 3}
buildPerBigTileLightListShader: {fileID: 7200000, guid: 5ee1f9d6e09abe045b2f5e0b784b9072,
type: 3}
buildPerVoxelLightListShader: {fileID: 7200000, guid: 0bb1b7e0ddcd5c44baf3ddc7456eb196,
type: 3}
shadeOpaqueShader: {fileID: 7200000, guid: 0b64f79746d2daf4198eaf6eab9af259, type: 3}
m_DebugViewMaterialGBuffer: {fileID: 4800000, guid: 439949ea1bfa91b4ba0d04269fcde33d,
type: 3}
m_InitPreFGD: {fileID: 4800000, guid: 123f13d52852ef547b2962de4bd9eaad, type: 3}

9
Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipelineSetup.asset.meta


fileFormatVersion: 2
guid: c90ada6c2ed7b4e4b85a303678826111
timeCreated: 1484737584
licenseType: Pro
NativeFormatImporter:
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

34
Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipelineSetup.cs


using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class HDRenderPipelineSetup : ScriptableObject
{
#if UNITY_EDITOR
[UnityEditor.MenuItem("RenderPipeline/CreateHDPipelineSetup")]
static void CreateHDRenderPipelineSetup()
{
var instance = ScriptableObject.CreateInstance<HDRenderPipelineSetup>();
UnityEditor.AssetDatabase.CreateAsset(instance, "Assets/HDRenderPipelineSetup.asset");
}
#endif
public ComputeShader buildScreenAABBShader = null;
public ComputeShader buildPerTileLightListShader = null; // FPTL
public ComputeShader buildPerBigTileLightListShader = null;
public ComputeShader buildPerVoxelLightListShader = null; // clustered
public ComputeShader shadeOpaqueShader = null;
// Various set of material use in render loop
public Shader m_DebugViewMaterialGBuffer;
// For image based lighting
public Shader m_InitPreFGD;
}
}

12
Assets/ScriptableRenderLoop/HDRenderPipeline/HDRenderPipelineSetup.cs.meta


fileFormatVersion: 2
guid: 8b6f86e1523e69a4282e92d393be89a4
timeCreated: 1484737533
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

50
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/SampleLayer.hlsl


// Gather all kind of mapping in one struct, allow to improve code readability
struct LayerUV
{
float2 uv;
// triplanar
bool isTriplanar;
float2 uvYZ;
float2 uvZX;
float2 uvXY;
};
// Multiple includes of the file to handle all variations of textures sampling for regular, lod and bias
// Regular sampling functions
#define ADD_FUNC_SUFFIX(Name) Name
#define SAMPLE_TEXTURE_FUNC(layerTex, layerSampler, layerUV, unused) SAMPLE_TEXTURE2D(layerTex, layerSampler, layerUV)
#include "SampleLayerInternal.hlsl"
#undef ADD_FUNC_SUFFIX
#undef SAMPLE_TEXTURE_FUNC
// Lod sampling functions
#define ADD_FUNC_SUFFIX(Name) Name##Lod
#define SAMPLE_TEXTURE_FUNC(layerTex, layerSampler, layerUV, lod) SAMPLE_TEXTURE2D_LOD(layerTex, layerSampler, layerUV, lod)
#include "SampleLayerInternal.hlsl"
#undef ADD_FUNC_SUFFIX
#undef SAMPLE_TEXTURE_FUNC
// Bias sampling functions
#define ADD_FUNC_SUFFIX(Name) Name##Bias
#define SAMPLE_TEXTURE_FUNC(layerTex, layerSampler, layerUV, bias) SAMPLE_TEXTURE2D_BIAS(layerTex, layerSampler, layerUV, bias)
#include "SampleLayerInternal.hlsl"
#undef ADD_FUNC_SUFFIX
#undef SAMPLE_TEXTURE_FUNC
// Macro to improve readibility of surface data
#define SAMPLE_LAYER_TEXTURE2D(textureName, samplerName, coord) SampleLayer(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, 0.0) // Last 0.0 is unused
#define SAMPLE_LAYER_TEXTURE2D_LOD(textureName, samplerName, coord, lod) SampleLayerLod(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, lod)
#define SAMPLE_LAYER_TEXTURE2D_BIAS(textureName, samplerName, coord, bias) SampleLayerBias(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, bias)
#define SAMPLE_LAYER_NORMALMAP(textureName, samplerName, coord, scale) SampleLayerNormal(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, scale, 0.0)
#define SAMPLE_LAYER_NORMALMAP_LOD(textureName, samplerName, coord, scale, lod) SampleLayerNormalLod(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, scale, lod)
#define SAMPLE_LAYER_NORMALMAP_BIAS(textureName, samplerName, coord, scale, bias) SampleLayerNormalBias(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, scale, bias)
#define SAMPLE_LAYER_NORMALMAP_AG(textureName, samplerName, coord, scale) SampleLayerNormalAG(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, scale, 0.0)
#define SAMPLE_LAYER_NORMALMAP_AG_LOD(textureName, samplerName, coord, scale, lod) SampleLayerNormalAGLod(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, scale, lod)
#define SAMPLE_LAYER_NORMALMAP_AG_BIAS(textureName, samplerName, coord, scale, bias) SampleLayerNormalAGBias(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, scale, bias)
#define SAMPLE_LAYER_NORMALMAP_RGB(textureName, samplerName, coord, scale) SampleLayerNormalRGB(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, scale, 0.0)
#define SAMPLE_LAYER_NORMALMAP_RGB_LOD(textureName, samplerName, coord, scale, lod) SampleLayerNormalRGBLod(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, scale, lod)
#define SAMPLE_LAYER_NORMALMAP_RGB_BIAS(textureName, samplerName, coord, scale, bias) SampleLayerNormalRGBBias(TEXTURE2D_PARAM(textureName, samplerName), coord, layerTexCoord.weights, scale, bias)

9
Assets/ScriptableRenderLoop/HDRenderPipeline/Material/SampleLayer.hlsl.meta


fileFormatVersion: 2
guid: f3e4d64dcf820e040a738f576d8d1f79
timeCreated: 1485260584
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

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

正在加载...
取消
保存