浏览代码

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

/main
Arnaud Carre 7 年前
当前提交
074f76bb
共有 165 个文件被更改,包括 8437 次插入3004 次删除
  1. 272
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3002_ObjectMotionVector.unity.png
  2. 1001
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Common.hlsl
  3. 80
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/CommonLighting.hlsl
  4. 406
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Debug.hlsl
  5. 14
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Shadow/Shadow.hlsl
  6. 44
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Shadow/ShadowAlgorithms.hlsl
  7. 2
      ScriptableRenderPipeline/Core/package.json
  8. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCamera.cs
  9. 616
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/MaterialDebug.cs
  10. 35
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/LayeredLit/LayeredLitUI.cs
  11. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/BaseLitUI.cs
  12. 41
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/LitUI.cs
  13. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs
  14. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Deferred.shader
  15. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/HDAdditionalLightData.cs
  16. 76
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightEvaluation.hlsl
  17. 25
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/Deferred.compute
  18. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs
  19. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopDef.hlsl
  20. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/Shadow.hlsl
  21. 22
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/Resources/VolumetricLighting.compute
  22. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLit.shader
  23. 1001
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitData.hlsl
  24. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitTessellation.shader
  25. 290
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl
  26. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.shader
  27. 540
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitData.hlsl
  28. 520
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitProperties.hlsl
  29. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitReference.hlsl
  30. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitTessellation.shader
  31. 19
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.compute
  32. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Unlit/Unlit.shader
  33. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/DefaultHDMaterial.mat
  34. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPass.cs
  35. 17
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPass.cs.hlsl
  36. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassForward.hlsl
  37. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassLightTransport.hlsl
  38. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/TessellationShare.hlsl
  39. 23
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/VaryingMesh.hlsl
  40. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/VertMesh.hlsl
  41. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariables.hlsl
  42. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/OpaqueAtmosphericScattering.shader
  43. 4
      ScriptableRenderPipeline/HDRenderPipeline/package.json
  44. 18
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Data/LightweightPipelineAsset.cs
  45. 37
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/LightweightAssetEditor.cs
  46. 2
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/LightweightShaderIncludePaths.cs
  47. 120
      ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs
  48. 2
      ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipelineUtils.cs
  49. 2
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightBlit.shader
  50. 2
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightCopyDepth.shader
  51. 18
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandard.shader
  52. 6
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardParticles.shader
  53. 4
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardParticlesUnlit.shader
  54. 8
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardSimpleLighting.shader
  55. 6
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardTerrain.shader
  56. 4
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightUnlit.shader
  57. 4
      ScriptableRenderPipeline/LightweightPipeline/package.json
  58. 2
      ScriptableRenderPipeline/master-package.json
  59. 4
      TestbedPipelines/OnTileDeferredPipeline/Shaders/LightingTemplate.hlsl
  60. 9
      TestbedPipelines/OnTileDeferredPipeline/Shaders/ShadowContext.hlsl
  61. 29
      TestbedPipelines/OnTileDeferredPipeline/Shaders/Standard.shader
  62. 29
      TestbedPipelines/OnTileDeferredPipeline/Shaders/StandardSpecular.shader
  63. 3
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/3DObjects/CornelBox/Cornell Box.fbx.meta
  64. 3
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/3DObjects/Sphere/Sphere.fbx.meta
  65. 3
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Materials/HDRP_Default_Material.mat
  66. 3
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1210_Lit_BentNormal/BentNormal_Tangent.mat
  67. 3
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1210_Lit_BentNormal/Green_Emissive.mat
  68. 3
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1210_Lit_BentNormal/Red_Emissive.mat
  69. 192
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/3xxx_DebugView/3002_ObjectMotionVector.unity
  70. 9
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/EditorPlayModeTests.asset
  71. 6
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Assets/CommonAssets/Cornell Box.fbx.meta
  72. 5
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset
  73. 4
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/040_UpgradeScene/Models/Environment/Floor.fbx.meta
  74. 11
      Tests/Scripts/Editor.meta
  75. 14
      Tests/Scripts/Editor/GraphicTests/Framework/EditorPlayModeTests_Editor.cs
  76. 11
      Tests/Scripts/Editor/GraphicTests/Framework/TestFramework.cs
  77. 14
      Tests/Scripts/GraphicTests/Framework/SetupSceneForRenderPipelineTest.cs
  78. 34
      Tests/Scripts/GraphicTests/Framework/TestFrameworkPlayMode.cs
  79. 35
      Tests/Scripts/GraphicTests/Framework/TestFrameworkTools.cs
  80. 24
      Tests/Scripts/GraphicTests/HDRenderPipeline/DebugViewController.cs
  81. 9
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassLit.hlsl
  82. 4
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMeta.hlsl
  83. 2
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassShadow.hlsl
  84. 5
      Tests/Scripts/GraphicTests/HDRenderPipeline/SinMove.cs
  85. 2
      Tests/Scripts/GraphicTests/HDRenderPipeline/SinMove.cs.meta
  86. 43
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/CoreFunctions.hlsl
  87. 33
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Shadows.hlsl
  88. 5
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Input.hlsl
  89. 4
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputBuiltin.hlsl
  90. 744
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3003_CameraMotionVector_TranslateX.unity.png
  91. 83
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3003_CameraMotionVector_TranslateX.unity.png.meta
  92. 465
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3004_CameraMotionVector_TranslateY.unity.png
  93. 83
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3004_CameraMotionVector_TranslateY.unity.png.meta
  94. 1001
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3005_CameraMotionVector_TranslateZ.unity.png
  95. 83
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3005_CameraMotionVector_TranslateZ.unity.png.meta
  96. 902
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3006_CameraMotionVector_RotateX.unity.png
  97. 83
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3006_CameraMotionVector_RotateX.unity.png.meta
  98. 956
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3007_CameraMotionVector_RotateY.unity.png
  99. 83
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3007_CameraMotionVector_RotateY.unity.png.meta
  100. 1001
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3008_CameraMotionVector_RotateZ.unity.png

272
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3002_ObjectMotionVector.unity.png
文件差异内容过多而无法显示
查看文件

1001
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Common.hlsl
文件差异内容过多而无法显示
查看文件

80
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/CommonLighting.hlsl


// Attenuation functions
//-----------------------------------------------------------------------------
// Ref: Moving Frostbite to PBR
real SmoothDistanceAttenuation(real squaredDistance, real invSqrAttenuationRadius)
// Ref: Moving Frostbite to PBR.
real QuadraticAttenuation(real attenuation)
{
return attenuation * attenuation;
}
// Non physically based hack to limit light influence to attenuationRadius.
real DistanceAttenuation(real squaredDistance, real invSqrAttenuationRadius)
real smoothFactor = saturate(1.0 - factor * factor);
return smoothFactor * smoothFactor;
return saturate(1.0 - factor * factor);
}
real SmoothDistanceAttenuation(real squaredDistance, real invSqrAttenuationRadius)
{
real smoothFactor = DistanceAttenuation(squaredDistance, invSqrAttenuationRadius);
return QuadraticAttenuation(smoothFactor);
real GetDistanceAttenuation(real sqrDist, real invSqrAttenuationRadius)
real SmoothQuadraticDistanceAttenuation(real distSq, real distRcp, real invSqrAttenuationRadius)
real 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);
return attenuation;
// Becomes quadratic after the call to QuadraticAttenuation().
real attenuation = min(distRcp, 1.0 / PUNCTUAL_LIGHT_THRESHOLD);
attenuation *= DistanceAttenuation(distSq, invSqrAttenuationRadius);
return QuadraticAttenuation(attenuation);
real GetDistanceAttenuation(real3 unL, real invSqrAttenuationRadius)
real SmoothQuadraticDistanceAttenuation(real3 unL, real invSqrAttenuationRadius)
real sqrDist = dot(unL, unL);
return GetDistanceAttenuation(sqrDist, invSqrAttenuationRadius);
real distSq = dot(unL, unL);
real distRcp = rsqrt(distSq);
return SmoothQuadraticDistanceAttenuation(distSq, distRcp, invSqrAttenuationRadius);
real GetAngleAttenuation(real3 L, real3 lightDir, real lightAngleScale, real lightAngleOffset)
real AngleAttenuation(real cosFwd, real lightAngleScale, real lightAngleOffset)
real cd = dot(lightDir, L);
real attenuation = saturate(cd * lightAngleScale + lightAngleOffset);
// smooth the transition
attenuation *= attenuation;
return saturate(cosFwd * lightAngleScale + lightAngleOffset);
}
return attenuation;
real SmoothAngleAttenuation(real cosFwd, real lightAngleScale, real lightAngleOffset)
{
real attenuation = AngleAttenuation(cosFwd, lightAngleScale, lightAngleOffset);
return QuadraticAttenuation(attenuation);
}
real SmoothAngleAttenuation(real3 L, real3 lightFwdDir, real lightAngleScale, real lightAngleOffset)
{
real cosFwd = dot(-L, lightFwdDir);
return SmoothAngleAttenuation(cosFwd, lightAngleScale, lightAngleOffset);
}
// Combines SmoothQuadraticDistanceAttenuation() and SmoothAngleAttenuation() in an efficient manner.
// distances = {d, d^2, 1/d, d_proj}, where d_proj = dot(lightToSample, lightData.forward).
real SmoothPunctualLightAttenuation(real4 distances, real invSqrAttenuationRadius,
real lightAngleScale, real lightAngleOffset)
{
real distSq = distances.y;
real distRcp = distances.z;
real distProj = distances.w;
real cosFwd = distProj * distRcp;
real attenuation = min(distRcp, 1.0 / PUNCTUAL_LIGHT_THRESHOLD);
attenuation *= DistanceAttenuation(distSq, invSqrAttenuationRadius);
attenuation *= AngleAttenuation(cosFwd, lightAngleScale, lightAngleOffset);
return QuadraticAttenuation(attenuation);
}
// Applies SmoothDistanceAttenuation() after transforming the attenuation ellipsoid into a sphere.

// 'unL' should be computed from the center of the ellipsoid.
real GetEllipsoidalDistanceAttenuation(real3 unL, real invSqRadius,
real3 axis, real invAspectRatio)
real EllipsoidalDistanceAttenuation(real3 unL, real invSqRadius,
real3 axis, real invAspectRatio)
{
// Project the unnormalized light vector onto the axis.
real projL = dot(unL, axis);

// Applies SmoothDistanceAttenuation() using the axis-aligned ellipsoid of the given dimensions.
// Both the ellipsoid and 'unL' should be in the same coordinate system.
// 'unL' should be computed from the center of the ellipsoid.
real GetEllipsoidalDistanceAttenuation(real3 unL, real3 invHalfDim)
real EllipsoidalDistanceAttenuation(real3 unL, real3 invHalfDim)
{
// Transform the light vector so that we can work with
// with the ellipsoid as if it was a unit sphere.

// If the diagonal of the box is 'd', invHalfDim = rcp(0.5 * d).
// Both the box and 'unL' should be in the same coordinate system.
// 'unL' should be computed from the center of the box.
real GetBoxDistanceAttenuation(real3 unL, real3 invHalfDim)
real BoxDistanceAttenuation(real3 unL, real3 invHalfDim)
{
// Transform the light vector so that we can work with
// with the box as if it was a [-1, 1]^2 cube.

406
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Debug.hlsl


#ifndef UNITY_DEBUG_INCLUDED
#define UNITY_DEBUG_INCLUDED
// Given an enum (represented by an int here), return a color.
// Use for DebugView of enum
real3 GetIndexColor(int index)
{
real3 outColor = real3(1.0, 0.0, 0.0);
if (index == 0)
outColor = real3(1.0, 0.5, 0.5);
else if (index == 1)
outColor = real3(0.5, 1.0, 0.5);
else if (index == 2)
outColor = real3(0.5, 0.5, 1.0);
else if (index == 3)
outColor = real3(1.0, 1.0, 0.5);
else if (index == 4)
outColor = real3(1.0, 0.5, 1.0);
else if (index == 5)
outColor = real3(0.5, 1.0, 1.0);
else if (index == 6)
outColor = real3(0.25, 0.75, 1.0);
else if (index == 7)
outColor = real3(1.0, 0.75, 0.25);
else if (index == 8)
outColor = real3(0.75, 1.0, 0.25);
else if (index == 9)
outColor = real3(0.75, 0.25, 1.0);
return outColor;
}
bool SampleDebugFont(int2 pixCoord, uint digit)
{
if (pixCoord.x < 0 || pixCoord.y < 0 || pixCoord.x >= 5 || pixCoord.y >= 9 || digit > 9)
return false;
#define PACK_BITS25(_x0,_x1,_x2,_x3,_x4,_x5,_x6,_x7,_x8,_x9,_x10,_x11,_x12,_x13,_x14,_x15,_x16,_x17,_x18,_x19,_x20,_x21,_x22,_x23,_x24) (_x0|(_x1<<1)|(_x2<<2)|(_x3<<3)|(_x4<<4)|(_x5<<5)|(_x6<<6)|(_x7<<7)|(_x8<<8)|(_x9<<9)|(_x10<<10)|(_x11<<11)|(_x12<<12)|(_x13<<13)|(_x14<<14)|(_x15<<15)|(_x16<<16)|(_x17<<17)|(_x18<<18)|(_x19<<19)|(_x20<<20)|(_x21<<21)|(_x22<<22)|(_x23<<23)|(_x24<<24))
#define _ 0
#define x 1
uint fontData[9][2] = {
{ PACK_BITS25(_,_,x,_,_, _,_,x,_,_, _,x,x,x,_, x,x,x,x,x, _,_,_,x,_), PACK_BITS25(x,x,x,x,x, _,x,x,x,_, x,x,x,x,x, _,x,x,x,_, _,x,x,x,_) },
{ PACK_BITS25(_,x,_,x,_, _,x,x,_,_, x,_,_,_,x, _,_,_,_,x, _,_,_,x,_), PACK_BITS25(x,_,_,_,_, x,_,_,_,x, _,_,_,_,x, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, x,_,x,_,_, x,_,_,_,x, _,_,_,x,_, _,_,x,x,_), PACK_BITS25(x,_,_,_,_, x,_,_,_,_, _,_,_,x,_, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,_,_,_,x, _,_,x,_,_, _,x,_,x,_), PACK_BITS25(x,_,x,x,_, x,_,_,_,_, _,_,_,x,_, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,_,_,x,_, _,x,x,x,_, _,x,_,x,_), PACK_BITS25(x,x,_,_,x, x,x,x,x,_, _,_,x,_,_, _,x,x,x,_, _,x,x,x,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,_,x,_,_, _,_,_,_,x, x,_,_,x,_), PACK_BITS25(_,_,_,_,x, x,_,_,_,x, _,_,x,_,_, x,_,_,_,x, _,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,x,_,_,_, _,_,_,_,x, x,x,x,x,x), PACK_BITS25(_,_,_,_,x, x,_,_,_,x, _,x,_,_,_, x,_,_,_,x, _,_,_,_,x) },
{ PACK_BITS25(_,x,_,x,_, _,_,x,_,_, x,_,_,_,_, x,_,_,_,x, _,_,_,x,_), PACK_BITS25(x,_,_,_,x, x,_,_,_,x, _,x,_,_,_, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(_,_,x,_,_, x,x,x,x,x, x,x,x,x,x, _,x,x,x,_, _,_,_,x,_), PACK_BITS25(_,x,x,x,_, _,x,x,x,_, _,x,_,_,_, _,x,x,x,_, _,x,x,x,_) }
};
#undef _
#undef x
#undef PACK_BITS25
return (fontData[8 - pixCoord.y][digit >= 5] >> ((digit % 5) * 5 + pixCoord.x)) & 1;
}
bool SampleDebugFontNumber(int2 pixCoord, uint number)
{
pixCoord.y -= 4;
if (number <= 9)
{
return SampleDebugFont(pixCoord - int2(6, 0), number);
}
else
{
return (SampleDebugFont(pixCoord, number / 10) | SampleDebugFont(pixCoord - int2(6, 0), number % 10));
}
}
#ifndef UNITY_DEBUG_INCLUDED
#define UNITY_DEBUG_INCLUDED
// Given an enum (represented by an int here), return a color.
// Use for DebugView of enum
real3 GetIndexColor(int index)
{
real3 outColor = real3(1.0, 0.0, 0.0);
if (index == 0)
outColor = real3(1.0, 0.5, 0.5);
else if (index == 1)
outColor = real3(0.5, 1.0, 0.5);
else if (index == 2)
outColor = real3(0.5, 0.5, 1.0);
else if (index == 3)
outColor = real3(1.0, 1.0, 0.5);
else if (index == 4)
outColor = real3(1.0, 0.5, 1.0);
else if (index == 5)
outColor = real3(0.5, 1.0, 1.0);
else if (index == 6)
outColor = real3(0.25, 0.75, 1.0);
else if (index == 7)
outColor = real3(1.0, 0.75, 0.25);
else if (index == 8)
outColor = real3(0.75, 1.0, 0.25);
else if (index == 9)
outColor = real3(0.75, 0.25, 1.0);
return outColor;
}
bool SampleDebugFont(int2 pixCoord, uint digit)
{
if (pixCoord.x < 0 || pixCoord.y < 0 || pixCoord.x >= 5 || pixCoord.y >= 9 || digit > 9)
return false;
#define PACK_BITS25(_x0,_x1,_x2,_x3,_x4,_x5,_x6,_x7,_x8,_x9,_x10,_x11,_x12,_x13,_x14,_x15,_x16,_x17,_x18,_x19,_x20,_x21,_x22,_x23,_x24) (_x0|(_x1<<1)|(_x2<<2)|(_x3<<3)|(_x4<<4)|(_x5<<5)|(_x6<<6)|(_x7<<7)|(_x8<<8)|(_x9<<9)|(_x10<<10)|(_x11<<11)|(_x12<<12)|(_x13<<13)|(_x14<<14)|(_x15<<15)|(_x16<<16)|(_x17<<17)|(_x18<<18)|(_x19<<19)|(_x20<<20)|(_x21<<21)|(_x22<<22)|(_x23<<23)|(_x24<<24))
#define _ 0
#define x 1
uint fontData[9][2] = {
{ PACK_BITS25(_,_,x,_,_, _,_,x,_,_, _,x,x,x,_, x,x,x,x,x, _,_,_,x,_), PACK_BITS25(x,x,x,x,x, _,x,x,x,_, x,x,x,x,x, _,x,x,x,_, _,x,x,x,_) },
{ PACK_BITS25(_,x,_,x,_, _,x,x,_,_, x,_,_,_,x, _,_,_,_,x, _,_,_,x,_), PACK_BITS25(x,_,_,_,_, x,_,_,_,x, _,_,_,_,x, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, x,_,x,_,_, x,_,_,_,x, _,_,_,x,_, _,_,x,x,_), PACK_BITS25(x,_,_,_,_, x,_,_,_,_, _,_,_,x,_, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,_,_,_,x, _,_,x,_,_, _,x,_,x,_), PACK_BITS25(x,_,x,x,_, x,_,_,_,_, _,_,_,x,_, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,_,_,x,_, _,x,x,x,_, _,x,_,x,_), PACK_BITS25(x,x,_,_,x, x,x,x,x,_, _,_,x,_,_, _,x,x,x,_, _,x,x,x,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,_,x,_,_, _,_,_,_,x, x,_,_,x,_), PACK_BITS25(_,_,_,_,x, x,_,_,_,x, _,_,x,_,_, x,_,_,_,x, _,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,x,_,_,_, _,_,_,_,x, x,x,x,x,x), PACK_BITS25(_,_,_,_,x, x,_,_,_,x, _,x,_,_,_, x,_,_,_,x, _,_,_,_,x) },
{ PACK_BITS25(_,x,_,x,_, _,_,x,_,_, x,_,_,_,_, x,_,_,_,x, _,_,_,x,_), PACK_BITS25(x,_,_,_,x, x,_,_,_,x, _,x,_,_,_, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(_,_,x,_,_, x,x,x,x,x, x,x,x,x,x, _,x,x,x,_, _,_,_,x,_), PACK_BITS25(_,x,x,x,_, _,x,x,x,_, _,x,_,_,_, _,x,x,x,_, _,x,x,x,_) }
};
#undef _
#undef x
#undef PACK_BITS25
return (fontData[8 - pixCoord.y][digit >= 5] >> ((digit % 5) * 5 + pixCoord.x)) & 1;
}
bool SampleDebugFontNumber(int2 pixCoord, uint number)
{
pixCoord.y -= 4;
if (number <= 9)
{
return SampleDebugFont(pixCoord - int2(6, 0), number);
}
else
{
return (SampleDebugFont(pixCoord, number / 10) | SampleDebugFont(pixCoord - int2(6, 0), number % 10));
}
}
{
// alpha is amount to blend with source color (0.0 = use original, 1.0 = use new color)
{
// alpha is amount to blend with source color (0.0 = use original, 1.0 = use new color)
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
// If material/shader mip info (original mip level) has not been set its not a streamed texture
if (originalTextureMipCount == 0)
return float4(1.0, 1.0, 1.0, 0.0);
// If material/shader mip info (original mip level) has not been set its not a streamed texture
if (originalTextureMipCount == 0)
return float4(1.0, 1.0, 1.0, 0.0);
uint mipCountDesired = uint(originalTextureMipCount)-uint(desiredMipLevel);
if (mipCount == 0)
{
// Magenta if mip count invalid
return float4(1.0, 0.0, 1.0, 1.0);
}
else if (mipCount < mipCountDesired)
{
// red tones when not at the desired mip level (reduction due to budget). Brighter is further from original, alpha 0 when at desired
float ratioToDesired = float(mipCount) / float(mipCountDesired);
return float4(1.0, 0.0, 0.0, 1.0 - ratioToDesired);
}
else if (mipCount >= originalTextureMipCount)
{
// original color when at (or beyond) original mip count
return float4(1.0, 1.0, 1.0, 0.0);
}
else
{
// green tones when not at the original mip level. Brighter is closer to original, alpha 0 when at original
float ratioToOriginal = float(mipCount) / float(originalTextureMipCount);
return float4(0.0, 1.0, 0.0, 1.0 - ratioToOriginal);
}
uint mipCountDesired = uint(originalTextureMipCount)-uint(desiredMipLevel);
if (mipCount == 0)
{
// Magenta if mip count invalid
return float4(1.0, 0.0, 1.0, 1.0);
}
else if (mipCount < mipCountDesired)
{
// red tones when not at the desired mip level (reduction due to budget). Brighter is further from original, alpha 0 when at desired
float ratioToDesired = float(mipCount) / float(mipCountDesired);
return float4(1.0, 0.0, 0.0, 1.0 - ratioToDesired);
}
else if (mipCount >= originalTextureMipCount)
{
// original color when at (or beyond) original mip count
return float4(1.0, 1.0, 1.0, 0.0);
}
else
{
// green tones when not at the original mip level. Brighter is closer to original, alpha 0 when at original
float ratioToOriginal = float(mipCount) / float(originalTextureMipCount);
return float4(0.0, 1.0, 0.0, 1.0 - ratioToOriginal);
}
{
// Grey scale for mip counts where mip count of 12 = white
float mipCountColor = float(mipCount) / 12.0;
float4 color = float4(mipCountColor, mipCountColor, mipCountColor, 1.0f);
// alpha is amount to blend with source color (0.0 = use original, 1.0 = use new color)
// Magenta is no valid mip count
// Original colour if greater than 12
return mipCount==0 ? float4(1.0, 0.0, 1.0, 1.0) : (mipCount > 12 ? float4(1.0, 1.0, 1.0, 0.0) : color );
{
// Grey scale for mip counts where mip count of 12 = white
float mipCountColor = float(mipCount) / 12.0;
float4 color = float4(mipCountColor, mipCountColor, mipCountColor, 1.0f);
// alpha is amount to blend with source color (0.0 = use original, 1.0 = use new color)
// Magenta is no valid mip count
// Original colour if greater than 12
return mipCount==0 ? float4(1.0, 0.0, 1.0, 1.0) : (mipCount > 12 ? float4(1.0, 1.0, 1.0, 0.0) : color );
// Push down into colors list to "optimal level" in following table.
// .zw is texture width,height so *2 is down one mip, *4 is down two mips
texelSize.zw *= 4.0;
// Push down into colors list to "optimal level" in following table.
// .zw is texture width,height so *2 is down one mip, *4 is down two mips
texelSize.zw *= 4.0;
float mipLevel = ComputeTextureLOD(uv, texelSize.wz);
float mipLevel = ComputeTextureLOD(uv, texelSize.wz);
float4 colors[6] = {
float4 colors[6] = {
float4(0.0, 0.0, 1.0, 0.8), // 0 BLUE = too little texture detail
float4(0.0, 0.5, 1.0, 0.4), // 1
float4(1.0, 1.0, 1.0, 0.0), // 2 = optimal level

float4 color = lerp(a, b, t);
return color;
}
float3 GetDebugMipColor(float3 originalColor, Texture2D tex, float4 texelSize, float2 uv)
}
float3 GetDebugMipColor(float3 originalColor, Texture2D tex, float4 texelSize, float2 uv)
return lerp(originalColor, mipColor.rgb, mipColor.a);
}
float3 GetDebugMipCountColor(float3 originalColor, Texture2D tex)
return lerp(originalColor, mipColor.rgb, mipColor.a);
}
float3 GetDebugMipCountColor(float3 originalColor, Texture2D tex)
uint mipCount = GetMipCount(tex);
uint mipCount = GetMipCount(tex);
return lerp(originalColor, mipColor.rgb, mipColor.a);
}
float3 GetDebugStreamingMipColor(Texture2D tex, float4 mipInfo)
return lerp(originalColor, mipColor.rgb, mipColor.a);
}
float3 GetDebugStreamingMipColor(Texture2D tex, float4 mipInfo)
uint mipCount = GetMipCount(tex);
uint mipCount = GetMipCount(tex);
}
float3 GetDebugStreamingMipColorBlended(float3 originalColor, Texture2D tex, float4 mipInfo)
}
float3 GetDebugStreamingMipColorBlended(float3 originalColor, Texture2D tex, float4 mipInfo)
uint mipCount = GetMipCount(tex);
uint mipCount = GetMipCount(tex);
return lerp(originalColor, mipColor.rgb, mipColor.a);
}
float3 GetDebugMipColorIncludingMipReduction(float3 originalColor, Texture2D tex, float4 texelSize, float2 uv, float4 mipInfo)
return lerp(originalColor, mipColor.rgb, mipColor.a);
}
float3 GetDebugMipColorIncludingMipReduction(float3 originalColor, Texture2D tex, float4 texelSize, float2 uv, float4 mipInfo)
uint originalTextureMipCount = uint(mipInfo.y);
if (originalTextureMipCount != 0)
{
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
// Mip count has been reduced but the texelSize was not updated to take that into account
uint mipCount = GetMipCount(tex);
uint mipReductionLevel = originalTextureMipCount - mipCount;
uint mipReductionFactor = 1 << mipReductionLevel;
if (mipReductionFactor)
{
float oneOverMipReductionFactor = 1.0 / mipReductionFactor;
// texelSize.xy *= mipReductionRatio; // Unused in GetDebugMipColor so lets not re-calculate it
texelSize.zw *= oneOverMipReductionFactor;
}
}
return GetDebugMipColor(originalColor, tex, texelSize, uv);
}
float3 GetDebugMipReductionColor(Texture2D tex, float4 mipInfo)
uint originalTextureMipCount = uint(mipInfo.y);
if (originalTextureMipCount != 0)
{
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
// Mip count has been reduced but the texelSize was not updated to take that into account
uint mipCount = GetMipCount(tex);
uint mipReductionLevel = originalTextureMipCount - mipCount;
uint mipReductionFactor = 1 << mipReductionLevel;
if (mipReductionFactor)
{
float oneOverMipReductionFactor = 1.0 / mipReductionFactor;
// texelSize.xy *= mipReductionRatio; // Unused in GetDebugMipColor so lets not re-calculate it
texelSize.zw *= oneOverMipReductionFactor;
}
}
return GetDebugMipColor(originalColor, tex, texelSize, uv);
}
float3 GetDebugMipReductionColor(Texture2D tex, float4 mipInfo)
uint originalTextureMipCount = uint(mipInfo.y);
if (originalTextureMipCount != 0)
{
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
// Mip count has been reduced but the texelSize was not updated to take that into account
uint mipCount = GetMipCount(tex);
uint mipReductionLevel = originalTextureMipCount - mipCount;
float mipCol = float(mipReductionLevel) / 12.0;
return float3(0, mipCol, 0);
}
// Can't calculate without original mip count - return magenta
return float3(1.0, 0.0, 1.0);
}
#ifdef DEBUG_DISPLAY
uint originalTextureMipCount = uint(mipInfo.y);
if (originalTextureMipCount != 0)
{
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
// Mip count has been reduced but the texelSize was not updated to take that into account
uint mipCount = GetMipCount(tex);
uint mipReductionLevel = originalTextureMipCount - mipCount;
float mipCol = float(mipReductionLevel) / 12.0;
return float3(0, mipCol, 0);
}
// Can't calculate without original mip count - return magenta
return float3(1.0, 0.0, 1.0);
}
#ifdef DEBUG_DISPLAY
case DEBUGMIPMAPMODE_MIP_RATIO:
return GetDebugMipColorIncludingMipReduction(originalColor, tex, texelSize, uv, mipInfo);
case DEBUGMIPMAPMODE_MIP_COUNT:
return GetDebugMipCountColor(originalColor, tex);
case DEBUGMIPMAPMODE_MIP_COUNT_REDUCTION:
return GetDebugMipReductionColor(tex, mipInfo);
case DEBUGMIPMAPMODE_STREAMING_MIP_BUDGET:
return GetDebugStreamingMipColor(tex, mipInfo);
case DEBUGMIPMAPMODE_STREAMING_MIP:
return GetDebugStreamingMipColorBlended(originalColor, tex, mipInfo);
}
case DEBUGMIPMAPMODE_MIP_RATIO:
return GetDebugMipColorIncludingMipReduction(originalColor, tex, texelSize, uv, mipInfo);
case DEBUGMIPMAPMODE_MIP_COUNT:
return GetDebugMipCountColor(originalColor, tex);
case DEBUGMIPMAPMODE_MIP_COUNT_REDUCTION:
return GetDebugMipReductionColor(tex, mipInfo);
case DEBUGMIPMAPMODE_STREAMING_MIP_BUDGET:
return GetDebugStreamingMipColor(tex, mipInfo);
case DEBUGMIPMAPMODE_STREAMING_MIP:
return GetDebugStreamingMipColorBlended(originalColor, tex, mipInfo);
}
}
}
#endif // UNITY_DEBUG_INCLUDED
#endif // UNITY_DEBUG_INCLUDED

14
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Shadow/Shadow.hlsl


}
// shadow sampling prototypes
real GetPunctualShadowAttenuation( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int shadowDataIndex, real4 L );
real GetPunctualShadowAttenuation( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int shadowDataIndex, real4 L, real2 positionSS );
real GetPunctualShadowAttenuation( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int shadowDataIndex, real3 lightPositionWS, real3 L );
real GetPunctualShadowAttenuation( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int shadowDataIndex, real3 lightPositionWS, real3 L, real2 positionSS );
// shadow sampling prototypes with screenspace info
real GetDirectionalShadowAttenuation( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int shadowDataIndex, real3 L );

#include "ShadowAlgorithms.hlsl" // engine default algorithms (don't modify)
#ifndef SHADOW_DISPATCH_USE_CUSTOM_PUNCTUAL
real GetPunctualShadowAttenuation( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int shadowDataIndex, real4 L )
real GetPunctualShadowAttenuation( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int shadowDataIndex, real3 lightPositionWS, real3 L )
return EvalShadow_PunctualDepth(shadowContext, positionWS, normalWS, shadowDataIndex, L);
return EvalShadow_PunctualDepth(shadowContext, positionWS, normalWS, shadowDataIndex, lightPositionWS, L);
real GetPunctualShadowAttenuation( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int shadowDataIndex, real4 L, real2 positionSS )
real GetPunctualShadowAttenuation( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int shadowDataIndex, real3 lightPositionWS, real3 L, real2 positionSS )
return GetPunctualShadowAttenuation( shadowContext, positionWS, normalWS, shadowDataIndex, L );
return GetPunctualShadowAttenuation( shadowContext, positionWS, normalWS, shadowDataIndex, lightPositionWS, L );
}
#endif

real GetDirectionalShadowAttenuation( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int shadowDataIndex, real3 L, real2 positionSS )
{
return GetDirectionalShadowAttenuation( shadowContext, positionWS, normalWS, shadowDataIndex, L );
return GetDirectionalShadowAttenuation( shadowContext, positionWS, normalWS, shadowDataIndex, lightPositionWS, L );
}
#endif

44
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Shadow/ShadowAlgorithms.hlsl


//
// Point shadows
//
real EvalShadow_PointDepth( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int index, real4 L )
real EvalShadow_PointDepth( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int index, real3 lightPositionWS, real3 L )
real3 biased_posWS = positionWS + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L.xyz ) ), sd.texelSizeRcp.zw, sd.normalBias );
real3 lpos = positionWS + L.xyz * L.w;
real3 biased_posWS = positionWS + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), sd.texelSizeRcp.zw, sd.normalBias );
real3 lpos = lightPositionWS;
positionWS = biased_posWS;
int faceIndex = EvalShadow_GetCubeFaceID( lpos - biased_posWS ) + 1;
// load the right shadow data for the current face

positionWS += EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L.xyz ) ), sd.texelSizeRcp.zw, sd.normalBias );
positionWS += EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), sd.texelSizeRcp.zw, sd.normalBias );
// get shadowmap texcoords
real3 posTC = EvalShadow_GetTexcoords( sd, positionWS );
// get the algorithm

}
#define EvalShadow_PointDepth_( _samplerType ) \
real EvalShadow_PointDepth( ShadowContext shadowContext, uint shadowAlgorithm, Texture2DArray tex, _samplerType samp, real3 positionWS, real3 normalWS, int index, real4 L ) \
real EvalShadow_PointDepth( ShadowContext shadowContext, uint shadowAlgorithm, Texture2DArray tex, _samplerType samp, real3 positionWS, real3 normalWS, int index, real3 lightPositionWS, real3 L ) \
real3 biased_posWS = positionWS + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L.xyz ) ), sd.texelSizeRcp.zw, sd.normalBias ); \
real3 lpos = positionWS + L.xyz * L.w; \
real3 biased_posWS = positionWS + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), sd.texelSizeRcp.zw, sd.normalBias ); \
real3 lpos = lightPositionWS; \
positionWS = biased_posWS; \
int faceIndex = EvalShadow_GetCubeFaceID( lpos - biased_posWS ) + 1; \
/* load the right shadow data for the current face */ \

positionWS += EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L.xyz ) ), sd.texelSizeRcp.zw, sd.normalBias ); \
positionWS += EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), sd.texelSizeRcp.zw, sd.normalBias ); \
/* get shadowmap texcoords */ \
real3 posTC = EvalShadow_GetTexcoords( sd, positionWS ); \
/* sample the texture */ \

//
// Punctual shadows for Point and Spot
//
real EvalShadow_PunctualDepth( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int index, real4 L )
real EvalShadow_PunctualDepth( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int index, real3 lightPositionWS, real3 L )
{
// load the right shadow data for the current face
int faceIndex = 0;

[branch]
if( shadowType == GPUSHADOWTYPE_POINT )
{
real3 biased_posWS = positionWS + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L.xyz ) ), sd.texelSizeRcp.zw, sd.normalBias );
real3 lpos = positionWS + L.xyz * L.w;
positionWS = biased_posWS;
faceIndex = EvalShadow_GetCubeFaceID( lpos - biased_posWS ) + 1;
real3 biased_posWS = positionWS + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), sd.texelSizeRcp.zw, sd.normalBias );
real3 lpos = lightPositionWS;
positionWS = biased_posWS;
faceIndex = EvalShadow_GetCubeFaceID( lpos - biased_posWS ) + 1;
positionWS += EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L.xyz ) ), sd.texelSizeRcp.zw, sd.normalBias );
positionWS += EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), sd.texelSizeRcp.zw, sd.normalBias );
sd = shadowContext.shadowDatas[index + faceIndex];
uint payloadOffset = GetPayloadOffset( sd );

}
#define EvalShadow_PunctualDepth_( _samplerType ) \
real EvalShadow_PunctualDepth( ShadowContext shadowContext, uint shadowAlgorithm, Texture2DArray tex, _samplerType samp, real3 positionWS, real3 normalWS, int index, real4 L ) \
real EvalShadow_PunctualDepth( ShadowContext shadowContext, uint shadowAlgorithm, Texture2DArray tex, _samplerType samp, real3 positionWS, real3 normalWS, int index, real3 lightPositionWS, real3 L ) \
{ \
/* load the right shadow data for the current face */ \
int faceIndex = 0; \

[branch] \
if( shadowType == GPUSHADOWTYPE_POINT ) \
{ \
real3 biased_posWS = positionWS + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L.xyz ) ), sd.texelSizeRcp.zw, sd.normalBias ); \
real3 lpos = positionWS + L.xyz * L.w; \
positionWS = biased_posWS; \
faceIndex = EvalShadow_GetCubeFaceID( lpos - biased_posWS ) + 1; \
real3 biased_posWS = positionWS + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), sd.texelSizeRcp.zw, sd.normalBias ); \
real3 lpos = lightPositionWS; \
positionWS = biased_posWS; \
faceIndex = EvalShadow_GetCubeFaceID( lpos - biased_posWS ) + 1; \
positionWS += EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L.xyz ) ), sd.texelSizeRcp.zw, sd.normalBias ); \
positionWS += EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), sd.texelSizeRcp.zw, sd.normalBias ); \
\
sd = shadowContext.shadowDatas[index + faceIndex]; \
uint payloadOffset = GetPayloadOffset( sd ); \

return closestWS.xyz / closestWS.w;
}
real3 EvalShadow_GetClosestSample_Cascade( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int index, real4 L )
real3 EvalShadow_GetClosestSample_Cascade( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int index, real3 lightPositionWS, real3 L )
{
// load the right shadow data for the current face
real4 dirShadowSplitSpheres[4];

return closestWS.xyz / closestWS.w;
}
real3 EvalShadow_GetClosestSample_Cascade( ShadowContext shadowContext, Texture2DArray tex, real3 positionWS, real3 normalWS, int index, real4 L )
real3 EvalShadow_GetClosestSample_Cascade( ShadowContext shadowContext, Texture2DArray tex, real3 positionWS, real3 normalWS, int index, real3 lightPositionWS, real3 L )
{
// load the right shadow data for the current face
real4 dirShadowSplitSpheres[4];

2
ScriptableRenderPipeline/Core/package.json


{
"name": "com.unity.render-pipelines.core",
"description": "Core library for Unity render pipelines.",
"version": "0.1.23",
"version": "0.1.24",
"unity": "2018.1",
"dependencies": {
"com.unity.postprocessing": "0.1.7"

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCamera.cs


public Vector4[] frustumPlaneEquations;
public Camera camera;
public uint taaFrameIndex;
public Vector2 taaFrameRotation;
public Vector4 viewParam;
public PostProcessRenderContext postprocessRenderContext;

const uint taaFrameCount = 8;
taaFrameIndex = taaEnabled ? (uint)Time.renderedFrameCount % taaFrameCount : 0;
taaFrameRotation = new Vector2(Mathf.Sin(taaFrameIndex * (0.5f * Mathf.PI)),
Mathf.Cos(taaFrameIndex * (0.5f * Mathf.PI)));
viewMatrix = gpuView;
projMatrix = gpuProj;

cmd.SetGlobalMatrix(HDShaderIDs._PrevViewProjMatrix, prevViewProjMatrix);
cmd.SetGlobalVectorArray(HDShaderIDs._FrustumPlanes, frustumPlaneEquations);
cmd.SetGlobalInt(HDShaderIDs._TaaFrameIndex, (int)taaFrameIndex);
cmd.SetGlobalVector(HDShaderIDs._TaaFrameRotation, taaFrameRotation);
}
// TODO: We should set all the value below globally and not let it under the control of Unity,

616
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/MaterialDebug.cs


using System.Collections.Generic;
using UnityEngine;
using System;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
namespace Attributes
{
// 0 is reserved!
[GenerateHLSL]
public enum DebugViewVarying
{
None = 0,
Texcoord0 = 1,
Texcoord1,
Texcoord2,
Texcoord3,
VertexTangentWS,
VertexBitangentWS,
VertexNormalWS,
VertexColor,
VertexColorAlpha,
Last,
};
// Number must be contiguous
[GenerateHLSL]
public enum DebugViewGbuffer
{
None = 0,
Depth = DebugViewVarying.Last,
BakeDiffuseLightingWithAlbedoPlusEmissive,
BakeShadowMask0,
BakeShadowMask1,
BakeShadowMask2,
BakeShadowMask3,
Last,
}
// Number must be contiguous
[GenerateHLSL]
public enum DebugViewProperties
{
None = 0,
Tessellation = DebugViewGbuffer.Last,
PixelDisplacement,
VertexDisplacement,
TessellationDisplacement,
DepthOffset,
Lightmap,
Last,
}
}
[Serializable]
public class MaterialDebugSettings
{
private static bool isDebugViewMaterialInit = false;
public static GUIContent[] debugViewMaterialStrings = null;
public static int[] debugViewMaterialValues = null;
public static GUIContent[] debugViewEngineStrings = null;
public static int[] debugViewEngineValues = null;
public static GUIContent[] debugViewMaterialVaryingStrings = null;
public static int[] debugViewMaterialVaryingValues = null;
public static GUIContent[] debugViewMaterialPropertiesStrings = null;
public static int[] debugViewMaterialPropertiesValues = null;
public static GUIContent[] debugViewMaterialTextureStrings = null;
using System.Collections.Generic;
using UnityEngine;
using System;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
namespace Attributes
{
// 0 is reserved!
[GenerateHLSL]
public enum DebugViewVarying
{
None = 0,
Texcoord0 = 1,
Texcoord1,
Texcoord2,
Texcoord3,
VertexTangentWS,
VertexBitangentWS,
VertexNormalWS,
VertexColor,
VertexColorAlpha,
Last,
};
// Number must be contiguous
[GenerateHLSL]
public enum DebugViewGbuffer
{
None = 0,
Depth = DebugViewVarying.Last,
BakeDiffuseLightingWithAlbedoPlusEmissive,
BakeShadowMask0,
BakeShadowMask1,
BakeShadowMask2,
BakeShadowMask3,
Last,
}
// Number must be contiguous
[GenerateHLSL]
public enum DebugViewProperties
{
None = 0,
Tessellation = DebugViewGbuffer.Last,
PixelDisplacement,
VertexDisplacement,
TessellationDisplacement,
DepthOffset,
Lightmap,
Last,
}
}
[Serializable]
public class MaterialDebugSettings
{
private static bool isDebugViewMaterialInit = false;
public static GUIContent[] debugViewMaterialStrings = null;
public static int[] debugViewMaterialValues = null;
public static GUIContent[] debugViewEngineStrings = null;
public static int[] debugViewEngineValues = null;
public static GUIContent[] debugViewMaterialVaryingStrings = null;
public static int[] debugViewMaterialVaryingValues = null;
public static GUIContent[] debugViewMaterialPropertiesStrings = null;
public static int[] debugViewMaterialPropertiesValues = null;
public static GUIContent[] debugViewMaterialTextureStrings = null;
public static GUIContent[] debugViewMaterialGBufferStrings = null;
public static int[] debugViewMaterialGBufferValues = null;
public MaterialDebugSettings()
{
BuildDebugRepresentation();
}
// className include the additional "/"
void FillWithProperties(Type type, GUIContent[] debugViewMaterialStrings, int[] debugViewMaterialValues, string className, ref int index)
{
var attributes = type.GetCustomAttributes(true);
// Get attribute to get the start number of the value for the enum
var attr = attributes[0] as GenerateHLSL;
if (!attr.needParamDebug)
{
return;
}
var fields = type.GetFields();
var localIndex = 0;
foreach (var field in fields)
{
var fieldName = field.Name;
// Check if the display name have been override by the users
if (Attribute.IsDefined(field, typeof(SurfaceDataAttributes)))
{
var propertyAttr = (SurfaceDataAttributes[])field.GetCustomAttributes(typeof(SurfaceDataAttributes), false);
if (propertyAttr[0].displayName != "")
{
fieldName = propertyAttr[0].displayName;
}
}
fieldName = className + fieldName;
debugViewMaterialStrings[index] = new GUIContent(fieldName);
debugViewMaterialValues[index] = attr.paramDefinesStart + (int)localIndex;
index++;
localIndex++;
}
}
void FillWithPropertiesEnum(Type type, GUIContent[] debugViewMaterialStrings, int[] debugViewMaterialValues, string prefix, ref int index)
{
var names = Enum.GetNames(type);
var localIndex = 0;
foreach (var value in Enum.GetValues(type))
{
var valueName = prefix + names[localIndex];
debugViewMaterialStrings[index] = new GUIContent(valueName);
debugViewMaterialValues[index] = (int)value;
index++;
localIndex++;
}
}
public class MaterialItem
{
public String className;
public Type surfaceDataType;
public Type bsdfDataType;
};
void BuildDebugRepresentation()
{
if (!isDebugViewMaterialInit)
{
List<RenderPipelineMaterial> materialList = HDUtils.GetRenderPipelineMaterialList();
// TODO: Share this code to retrieve deferred material with HDRenderPipeline
// Find first material that have non 0 Gbuffer count and assign it as deferredMaterial
Type bsdfDataDeferredType = null;
foreach (RenderPipelineMaterial material in materialList)
{
if (material.GetMaterialGBufferCount() > 0)
{
bsdfDataDeferredType = material.GetType().GetNestedType("BSDFData");
}
}
// TODO: Handle the case of no Gbuffer material
Debug.Assert(bsdfDataDeferredType != null);
List<MaterialItem> materialItems = new List<MaterialItem>();
int numSurfaceDataFields = 0;
int numBSDFDataFields = 0;
foreach (RenderPipelineMaterial material in materialList)
{
MaterialItem item = new MaterialItem();
item.className = material.GetType().Name + "/";
item.surfaceDataType = material.GetType().GetNestedType("SurfaceData");
numSurfaceDataFields += item.surfaceDataType.GetFields().Length;
item.bsdfDataType = material.GetType().GetNestedType("BSDFData");
numBSDFDataFields += item.bsdfDataType.GetFields().Length;
materialItems.Add(item);
}
// Material properties debug
var num = typeof(Builtin.BuiltinData).GetFields().Length * materialList.Count // BuildtinData are duplicated for each material
+ numSurfaceDataFields + 1; // +1 for None case
debugViewMaterialStrings = new GUIContent[num];
debugViewMaterialValues = new int[num];
// Special case for None since it cannot be inferred from SurfaceData/BuiltinData
debugViewMaterialStrings[0] = new GUIContent("None");
debugViewMaterialValues[0] = 0;
var index = 1;
// 0 is a reserved number and should not be used (allow to track error)
foreach (MaterialItem item in materialItems)
{
// BuiltinData are duplicated for each material
FillWithProperties(typeof(Builtin.BuiltinData), debugViewMaterialStrings, debugViewMaterialValues, item.className, ref index);
FillWithProperties(item.surfaceDataType, debugViewMaterialStrings, debugViewMaterialValues, item.className, ref index);
}
// Engine properties debug
num = numBSDFDataFields + 1; // +1 for None case
debugViewEngineStrings = new GUIContent[num];
debugViewEngineValues = new int[num];
// 0 is a reserved number and should not be used (allow to track error)
debugViewEngineStrings[0] = new GUIContent("None");
debugViewEngineValues[0] = 0;
index = 1;
foreach (MaterialItem item in materialItems)
{
FillWithProperties(item.bsdfDataType, debugViewEngineStrings, debugViewEngineValues, item.className, ref index);
}
// Attributes debug
var varyingNames = Enum.GetNames(typeof(Attributes.DebugViewVarying));
debugViewMaterialVaryingStrings = new GUIContent[varyingNames.Length];
debugViewMaterialVaryingValues = new int[varyingNames.Length];
index = 0;
FillWithPropertiesEnum(typeof(Attributes.DebugViewVarying), debugViewMaterialVaryingStrings, debugViewMaterialVaryingValues, "", ref index);
// Properties debug
var propertiesNames = Enum.GetNames(typeof(Attributes.DebugViewProperties));
debugViewMaterialPropertiesStrings = new GUIContent[propertiesNames.Length];
debugViewMaterialPropertiesValues = new int[propertiesNames.Length];
index = 0;
FillWithPropertiesEnum(typeof(Attributes.DebugViewProperties), debugViewMaterialPropertiesStrings, debugViewMaterialPropertiesValues, "", ref index);
// Gbuffer debug
var gbufferNames = Enum.GetNames(typeof(Attributes.DebugViewGbuffer));
debugViewMaterialGBufferStrings = new GUIContent[gbufferNames.Length + bsdfDataDeferredType.GetFields().Length];
debugViewMaterialGBufferValues = new int[gbufferNames.Length + bsdfDataDeferredType.GetFields().Length];
index = 0;
FillWithPropertiesEnum(typeof(Attributes.DebugViewGbuffer), debugViewMaterialGBufferStrings, debugViewMaterialGBufferValues, "", ref index);
FillWithProperties(typeof(Lit.BSDFData), debugViewMaterialGBufferStrings, debugViewMaterialGBufferValues, "", ref index);
isDebugViewMaterialInit = true;
}
}
public int debugViewMaterial { get { return m_DebugViewMaterial; } }
public int debugViewEngine { get { return m_DebugViewEngine; } }
public Attributes.DebugViewVarying debugViewVarying { get { return m_DebugViewVarying; } }
public Attributes.DebugViewProperties debugViewProperties { get { return m_DebugViewProperties; } }
public int debugViewGBuffer { get { return m_DebugViewGBuffer; } }
int m_DebugViewMaterial = 0; // No enum there because everything is generated from materials.
int m_DebugViewEngine = 0; // No enum there because everything is generated from BSDFData
Attributes.DebugViewVarying m_DebugViewVarying = Attributes.DebugViewVarying.None;
Attributes.DebugViewProperties m_DebugViewProperties = Attributes.DebugViewProperties.None;
int m_DebugViewGBuffer = 0; // Can't use GBuffer enum here because the values are actually split between this enum and values from Lit.BSDFData
public int GetDebugMaterialIndex()
{
// This value is used in the shader for the actual debug display.
// There is only one uniform parameter for that so we just add all of them
// They are all mutually exclusive so return the sum will return the right index.
return m_DebugViewGBuffer + m_DebugViewMaterial + m_DebugViewEngine + (int)m_DebugViewVarying + (int)m_DebugViewProperties;
}
public void DisableMaterialDebug()
{
m_DebugViewMaterial = 0;
m_DebugViewEngine = 0;
m_DebugViewVarying = Attributes.DebugViewVarying.None;
m_DebugViewProperties = Attributes.DebugViewProperties.None;
m_DebugViewGBuffer = 0;
}
public void SetDebugViewMaterial(int value)
{
if (value != 0)
DisableMaterialDebug();
m_DebugViewMaterial = value;
}
public void SetDebugViewEngine(int value)
{
if (value != 0)
DisableMaterialDebug();
m_DebugViewEngine = value;
}
public void SetDebugViewVarying(Attributes.DebugViewVarying value)
{
if (value != 0)
DisableMaterialDebug();
m_DebugViewVarying = value;
}
public void SetDebugViewProperties(Attributes.DebugViewProperties value)
{
if (value != 0)
DisableMaterialDebug();
m_DebugViewProperties = value;
}
public void SetDebugViewGBuffer(int value)
{
if (value != 0)
DisableMaterialDebug();
m_DebugViewGBuffer = value;
}
public bool IsDebugGBufferEnabled()
{
return m_DebugViewGBuffer != 0;
}
public bool IsDebugDisplayEnabled()
{
return (m_DebugViewEngine != 0 || m_DebugViewMaterial != 0 || m_DebugViewVarying != Attributes.DebugViewVarying.None || m_DebugViewProperties != Attributes.DebugViewProperties.None || m_DebugViewGBuffer != 0);
}
}
}
public static GUIContent[] debugViewMaterialGBufferStrings = null;
public static int[] debugViewMaterialGBufferValues = null;
public MaterialDebugSettings()
{
BuildDebugRepresentation();
}
// className include the additional "/"
void FillWithProperties(Type type, GUIContent[] debugViewMaterialStrings, int[] debugViewMaterialValues, string className, ref int index)
{
var attributes = type.GetCustomAttributes(true);
// Get attribute to get the start number of the value for the enum
var attr = attributes[0] as GenerateHLSL;
if (!attr.needParamDebug)
{
return;
}
var fields = type.GetFields();
var localIndex = 0;
foreach (var field in fields)
{
var fieldName = field.Name;
// Check if the display name have been override by the users
if (Attribute.IsDefined(field, typeof(SurfaceDataAttributes)))
{
var propertyAttr = (SurfaceDataAttributes[])field.GetCustomAttributes(typeof(SurfaceDataAttributes), false);
if (propertyAttr[0].displayName != "")
{
fieldName = propertyAttr[0].displayName;
}
}
fieldName = className + fieldName;
debugViewMaterialStrings[index] = new GUIContent(fieldName);
debugViewMaterialValues[index] = attr.paramDefinesStart + (int)localIndex;
index++;
localIndex++;
}
}
void FillWithPropertiesEnum(Type type, GUIContent[] debugViewMaterialStrings, int[] debugViewMaterialValues, string prefix, ref int index)
{
var names = Enum.GetNames(type);
var localIndex = 0;
foreach (var value in Enum.GetValues(type))
{
var valueName = prefix + names[localIndex];
debugViewMaterialStrings[index] = new GUIContent(valueName);
debugViewMaterialValues[index] = (int)value;
index++;
localIndex++;
}
}
public class MaterialItem
{
public String className;
public Type surfaceDataType;
public Type bsdfDataType;
};
void BuildDebugRepresentation()
{
if (!isDebugViewMaterialInit)
{
List<RenderPipelineMaterial> materialList = HDUtils.GetRenderPipelineMaterialList();
// TODO: Share this code to retrieve deferred material with HDRenderPipeline
// Find first material that have non 0 Gbuffer count and assign it as deferredMaterial
Type bsdfDataDeferredType = null;
foreach (RenderPipelineMaterial material in materialList)
{
if (material.GetMaterialGBufferCount() > 0)
{
bsdfDataDeferredType = material.GetType().GetNestedType("BSDFData");
}
}
// TODO: Handle the case of no Gbuffer material
Debug.Assert(bsdfDataDeferredType != null);
List<MaterialItem> materialItems = new List<MaterialItem>();
int numSurfaceDataFields = 0;
int numBSDFDataFields = 0;
foreach (RenderPipelineMaterial material in materialList)
{
MaterialItem item = new MaterialItem();
item.className = material.GetType().Name + "/";
item.surfaceDataType = material.GetType().GetNestedType("SurfaceData");
numSurfaceDataFields += item.surfaceDataType.GetFields().Length;
item.bsdfDataType = material.GetType().GetNestedType("BSDFData");
numBSDFDataFields += item.bsdfDataType.GetFields().Length;
materialItems.Add(item);
}
// Material properties debug
var num = typeof(Builtin.BuiltinData).GetFields().Length * materialList.Count // BuildtinData are duplicated for each material
+ numSurfaceDataFields + 1; // +1 for None case
debugViewMaterialStrings = new GUIContent[num];
debugViewMaterialValues = new int[num];
// Special case for None since it cannot be inferred from SurfaceData/BuiltinData
debugViewMaterialStrings[0] = new GUIContent("None");
debugViewMaterialValues[0] = 0;
var index = 1;
// 0 is a reserved number and should not be used (allow to track error)
foreach (MaterialItem item in materialItems)
{
// BuiltinData are duplicated for each material
FillWithProperties(typeof(Builtin.BuiltinData), debugViewMaterialStrings, debugViewMaterialValues, item.className, ref index);
FillWithProperties(item.surfaceDataType, debugViewMaterialStrings, debugViewMaterialValues, item.className, ref index);
}
// Engine properties debug
num = numBSDFDataFields + 1; // +1 for None case
debugViewEngineStrings = new GUIContent[num];
debugViewEngineValues = new int[num];
// 0 is a reserved number and should not be used (allow to track error)
debugViewEngineStrings[0] = new GUIContent("None");
debugViewEngineValues[0] = 0;
index = 1;
foreach (MaterialItem item in materialItems)
{
FillWithProperties(item.bsdfDataType, debugViewEngineStrings, debugViewEngineValues, item.className, ref index);
}
// Attributes debug
var varyingNames = Enum.GetNames(typeof(Attributes.DebugViewVarying));
debugViewMaterialVaryingStrings = new GUIContent[varyingNames.Length];
debugViewMaterialVaryingValues = new int[varyingNames.Length];
index = 0;
FillWithPropertiesEnum(typeof(Attributes.DebugViewVarying), debugViewMaterialVaryingStrings, debugViewMaterialVaryingValues, "", ref index);
// Properties debug
var propertiesNames = Enum.GetNames(typeof(Attributes.DebugViewProperties));
debugViewMaterialPropertiesStrings = new GUIContent[propertiesNames.Length];
debugViewMaterialPropertiesValues = new int[propertiesNames.Length];
index = 0;
FillWithPropertiesEnum(typeof(Attributes.DebugViewProperties), debugViewMaterialPropertiesStrings, debugViewMaterialPropertiesValues, "", ref index);
// Gbuffer debug
var gbufferNames = Enum.GetNames(typeof(Attributes.DebugViewGbuffer));
debugViewMaterialGBufferStrings = new GUIContent[gbufferNames.Length + bsdfDataDeferredType.GetFields().Length];
debugViewMaterialGBufferValues = new int[gbufferNames.Length + bsdfDataDeferredType.GetFields().Length];
index = 0;
FillWithPropertiesEnum(typeof(Attributes.DebugViewGbuffer), debugViewMaterialGBufferStrings, debugViewMaterialGBufferValues, "", ref index);
FillWithProperties(typeof(Lit.BSDFData), debugViewMaterialGBufferStrings, debugViewMaterialGBufferValues, "", ref index);
isDebugViewMaterialInit = true;
}
}
public int debugViewMaterial { get { return m_DebugViewMaterial; } }
public int debugViewEngine { get { return m_DebugViewEngine; } }
public Attributes.DebugViewVarying debugViewVarying { get { return m_DebugViewVarying; } }
public Attributes.DebugViewProperties debugViewProperties { get { return m_DebugViewProperties; } }
public int debugViewGBuffer { get { return m_DebugViewGBuffer; } }
int m_DebugViewMaterial = 0; // No enum there because everything is generated from materials.
int m_DebugViewEngine = 0; // No enum there because everything is generated from BSDFData
Attributes.DebugViewVarying m_DebugViewVarying = Attributes.DebugViewVarying.None;
Attributes.DebugViewProperties m_DebugViewProperties = Attributes.DebugViewProperties.None;
int m_DebugViewGBuffer = 0; // Can't use GBuffer enum here because the values are actually split between this enum and values from Lit.BSDFData
public int GetDebugMaterialIndex()
{
// This value is used in the shader for the actual debug display.
// There is only one uniform parameter for that so we just add all of them
// They are all mutually exclusive so return the sum will return the right index.
return m_DebugViewGBuffer + m_DebugViewMaterial + m_DebugViewEngine + (int)m_DebugViewVarying + (int)m_DebugViewProperties;
}
public void DisableMaterialDebug()
{
m_DebugViewMaterial = 0;
m_DebugViewEngine = 0;
m_DebugViewVarying = Attributes.DebugViewVarying.None;
m_DebugViewProperties = Attributes.DebugViewProperties.None;
m_DebugViewGBuffer = 0;
}
public void SetDebugViewMaterial(int value)
{
if (value != 0)
DisableMaterialDebug();
m_DebugViewMaterial = value;
}
public void SetDebugViewEngine(int value)
{
if (value != 0)
DisableMaterialDebug();
m_DebugViewEngine = value;
}
public void SetDebugViewVarying(Attributes.DebugViewVarying value)
{
if (value != 0)
DisableMaterialDebug();
m_DebugViewVarying = value;
}
public void SetDebugViewProperties(Attributes.DebugViewProperties value)
{
if (value != 0)
DisableMaterialDebug();
m_DebugViewProperties = value;
}
public void SetDebugViewGBuffer(int value)
{
if (value != 0)
DisableMaterialDebug();
m_DebugViewGBuffer = value;
}
public bool IsDebugGBufferEnabled()
{
return m_DebugViewGBuffer != 0;
}
public bool IsDebugDisplayEnabled()
{
return (m_DebugViewEngine != 0 || m_DebugViewMaterial != 0 || m_DebugViewVarying != Attributes.DebugViewVarying.None || m_DebugViewProperties != Attributes.DebugViewProperties.None || m_DebugViewGBuffer != 0);
}
}
}

35
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/LayeredLit/LayeredLitUI.cs


CoreUtils.SetKeyword(material, "_INFLUENCEMASK_MAP", material.GetTexture(kLayerInfluenceMaskMap) && material.GetFloat(kkUseMainLayerInfluence) != 0.0f);
CoreUtils.SetKeyword(material, "_EMISSIVE_MAPPING_PLANAR", ((UVBaseMapping)material.GetFloat(kUVEmissive)) == UVBaseMapping.Planar && material.GetTexture(kEmissiveColorMap));
CoreUtils.SetKeyword(material, "_EMISSIVE_MAPPING_TRIPLANAR", ((UVBaseMapping)material.GetFloat(kUVEmissive)) == UVBaseMapping.Triplanar && material.GetTexture(kEmissiveColorMap));
CoreUtils.SetKeyword(material, "_EMISSIVE_COLOR_MAP", material.GetTexture(kEmissiveColorMap));
CoreUtils.SetKeyword(material, "_ENABLESPECULAROCCLUSION", material.GetFloat(kEnableSpecularOcclusion) > 0.0f);

CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SUBSURFACE_SCATTERING", materialId == BaseLitGUI.MaterialId.LitSSS);
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_TRANSMISSION", materialId == BaseLitGUI.MaterialId.LitSSS);
}
private void DoEmissiveGUI(Material material)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField(Styles.lightingText, EditorStyles.boldLabel);
m_MaterialEditor.ShaderProperty(enableSpecularOcclusion, Styles.enableSpecularOcclusionText);
// TODO: display warning if we don't have bent normal (either OS or TS) and ambient occlusion
//if (enableSpecularOcclusion.floatValue > 0.0f)
{
// EditorGUILayout.HelpBox(Styles.specularOcclusionWarning.text, MessageType.Error);
}
EditorGUI.indentLevel++;
m_MaterialEditor.TexturePropertySingleLine(Styles.emissiveText, emissiveColorMap, emissiveColor);
m_MaterialEditor.ShaderProperty(emissiveIntensity, Styles.emissiveIntensityText);
m_MaterialEditor.ShaderProperty(albedoAffectEmissive, Styles.albedoAffectEmissiveText);
EditorGUI.indentLevel--;
}
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props)

bool layerChanged = DoLayersGUI(materialImporter);
DoEmissiveGUI(material);
EditorGUI.BeginChangeCheck();
{
DoEmissiveGUI(material);
}
if (EditorGUI.EndChangeCheck())
{
optionsChanged = true;
}
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUILayout.LabelField(StylesBaseUnlit.advancedText, EditorStyles.boldLabel);
// NB RenderQueue editor is not shown on purpose: we want to override it based on blend mode
EditorGUI.indentLevel++;
EditorGUI.indentLevel--;
if (layerChanged || optionsChanged)
{

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/BaseLitUI.cs


public static readonly string[] tessellationModeNames = Enum.GetNames(typeof(TessellationMode));
public static GUIContent tessellationText = new GUIContent("Tessellation options", "Tessellation options");
public static GUIContent tessellationFactorText = new GUIContent("Tessellation factor", "This value is the tessellation factor use for tessellation, higher mean more tessellated");
public static GUIContent tessellationFactorText = new GUIContent("Tessellation factor", "This value is the tessellation factor use for tessellation, higher mean more tessellated. Above 15 is costly. Maximum tessellation factor is 15 on XBone / PS4");
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.");

41
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/LitUI.cs


protected const string kEmissiveIntensity = "_EmissiveIntensity";
protected MaterialProperty albedoAffectEmissive = null;
protected const string kAlbedoAffectEmissive = "_AlbedoAffectEmissive";
protected MaterialProperty UVEmissive = null;
protected const string kUVEmissive = "_UVEmissive";
protected MaterialProperty TexWorldScaleEmissive = null;
protected const string kTexWorldScaleEmissive = "_TexWorldScaleEmissive";
protected MaterialProperty UVMappingMaskEmissive = null;
protected const string kUVMappingMaskEmissive = "_UVMappingMaskEmissive";
protected MaterialProperty enableSpecularOcclusion = null;
protected const string kEnableSpecularOcclusion = "_EnableSpecularOcclusion";

emissiveColorMap = FindProperty(kEmissiveColorMap, props);
emissiveIntensity = FindProperty(kEmissiveIntensity, props);
albedoAffectEmissive = FindProperty(kAlbedoAffectEmissive, props);
UVEmissive = FindProperty(kUVEmissive, props);
TexWorldScaleEmissive = FindProperty(kTexWorldScaleEmissive, props);
UVMappingMaskEmissive = FindProperty(kUVMappingMaskEmissive, props);
enableSpecularOcclusion = FindProperty(kEnableSpecularOcclusion, props);
}

if (EditorGUI.EndChangeCheck())
{
UpdateDisplacement(layerIndex);
}
}
}
switch ((BaseLitGUI.MaterialId)materialID.floatValue)

}
}
private void DoEmissiveGUI(Material material)
protected void DoEmissiveGUI(Material material)
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(enableSpecularOcclusion, Styles.enableSpecularOcclusionText);
// TODO: display warning if we don't have bent normal (either OS or TS) and ambient occlusion
//if (enableSpecularOcclusion.floatValue > 0.0f)

EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(UVEmissive, Styles.UVBaseMappingText);
UVBaseMapping uvEmissiveMapping = (UVBaseMapping)UVEmissive.floatValue;
float X, Y, Z, W;
X = (uvEmissiveMapping == UVBaseMapping.UV0) ? 1.0f : 0.0f;
Y = (uvEmissiveMapping == UVBaseMapping.UV1) ? 1.0f : 0.0f;
Z = (uvEmissiveMapping == UVBaseMapping.UV2) ? 1.0f : 0.0f;
W = (uvEmissiveMapping == UVBaseMapping.UV3) ? 1.0f : 0.0f;
UVMappingMaskEmissive.colorValue = new Color(X, Y, Z, W);
if ((uvEmissiveMapping == UVBaseMapping.Planar) || (uvEmissiveMapping == UVBaseMapping.Triplanar))
{
m_MaterialEditor.ShaderProperty(TexWorldScaleEmissive, Styles.texWorldScaleText);
}
m_MaterialEditor.ShaderProperty(emissiveIntensity, Styles.emissiveIntensityText);
m_MaterialEditor.ShaderProperty(albedoAffectEmissive, Styles.albedoAffectEmissiveText);
EditorGUI.indentLevel--;

// (MaterialProperty value might come from renderer material property block)
CoreUtils.SetKeyword(material, "_MAPPING_PLANAR", ((UVBaseMapping)material.GetFloat(kUVBase)) == UVBaseMapping.Planar);
CoreUtils.SetKeyword(material, "_MAPPING_TRIPLANAR", ((UVBaseMapping)material.GetFloat(kUVBase)) == UVBaseMapping.Triplanar);
CoreUtils.SetKeyword(material, "_NORMALMAP_TANGENT_SPACE", (normalMapSpace == NormalMapSpace.TangentSpace));
if (normalMapSpace == NormalMapSpace.TangentSpace)

CoreUtils.SetKeyword(material, "_BENTNORMALMAP", material.GetTexture(kBentNormalMapOS));
}
CoreUtils.SetKeyword(material, "_MASKMAP", material.GetTexture(kMaskMap));
CoreUtils.SetKeyword(material, "_EMISSIVE_MAPPING_PLANAR", ((UVBaseMapping)material.GetFloat(kUVEmissive)) == UVBaseMapping.Planar && material.GetTexture(kEmissiveColorMap));
CoreUtils.SetKeyword(material, "_EMISSIVE_MAPPING_TRIPLANAR", ((UVBaseMapping)material.GetFloat(kUVEmissive)) == UVBaseMapping.Triplanar && material.GetTexture(kEmissiveColorMap));
CoreUtils.SetKeyword(material, "_ENABLESPECULAROCCLUSION", material.GetFloat(kEnableSpecularOcclusion) > 0.0f);
CoreUtils.SetKeyword(material, "_HEIGHTMAP", material.GetTexture(kHeightMap));
CoreUtils.SetKeyword(material, "_ANISOTROPYMAP", material.GetTexture(kAnisotropyMap));

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs


public static readonly int _ScreenSize = Shader.PropertyToID("_ScreenSize");
public static readonly int _PrevViewProjMatrix = Shader.PropertyToID("_PrevViewProjMatrix");
public static readonly int _FrustumPlanes = Shader.PropertyToID("_FrustumPlanes");
public static readonly int _TaaFrameIndex = Shader.PropertyToID("_TaaFrameIndex");
public static readonly int _TaaFrameIndex = Shader.PropertyToID("_TaaFrameIndex");
public static readonly int _TaaFrameRotation = Shader.PropertyToID("_TaaFrameRotation");
public static readonly int _DepthTexture = Shader.PropertyToID("_DepthTexture");
public static readonly int _CameraColorTexture = Shader.PropertyToID("_CameraColorTexture");

7
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Deferred.shader


// Include
//-------------------------------------------------------------------------------------
#include "../ShaderPass/ShaderPass.cs.hlsl"
#define SHADERPASS SHADERPASS_DEFERRED_LIGHTING
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "../Debug/DebugDisplay.hlsl"

BSDFData bsdfData;
BakeLightingData bakeLightingData;
DECODE_FROM_GBUFFER(posInput.positionSS, MATERIAL_FEATURE_MASK_FLAGS, bsdfData, bakeLightingData.bakeDiffuseLighting);
DECODE_FROM_GBUFFER(posInput.positionSS, UINT_MAX, bsdfData, bakeLightingData.bakeDiffuseLighting);
#ifdef SHADOWS_SHADOWMASK
DecodeShadowMask(LOAD_TEXTURE2D(_ShadowMaskTexture, posInput.positionSS), bakeLightingData.bakeShadowMask);
#endif

Outputs outputs;
#ifdef OUTPUT_SPLIT_LIGHTING
if ((_EnableSubsurfaceScattering != 0) && HaveSubsurfaceScattering(bsdfData))
if (_EnableSubsurfaceScattering != 0 && PixelHasSubsurfaceScattering(bsdfData))
{
outputs.specularLighting = float4(specularLighting, 1.0);
outputs.diffuseLighting = TagLightingForSSS(diffuseLighting);

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/HDAdditionalLightData.cs


[SerializeField]
float m_Version = 1.0f;
#pragma warning restore 414
[FormerlySerializedAs("m_innerSpotPercent")]
public float m_InnerSpotPercent = 0.0f; // To display this field in the UI this need to be public
public float GetInnerSpotPercent01()

public bool affectDiffuse = true;
public bool affectSpecular = true;
[FormerlySerializedAs("archetype")]
public LightTypeExtent lightTypeExtent = LightTypeExtent.Punctual;
// Only for Spotlight, should be hide for other light

[FormerlySerializedAs("lightWidth")]
[FormerlySerializedAs("lightHeight")]
public float shapeHeight = 0.5f;
// Only for pyramid projector

76
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightEvaluation.hlsl


//-----------------------------------------------------------------------------
float3 EvaluateCookie_Directional(LightLoopContext lightLoopContext, DirectionalLightData lightData,
float3 positionWS)
float3 lightToSample)
float3 lightToSample = positionWS - lightData.positionWS;
float3x3 lightToWorld = float3x3(lightData.right, lightData.up, lightData.forward);
float3 positionLS = mul(lightToSample, transpose(lightToWorld));

float shadowMask = 1.0;
color = lightData.color;
attenuation = 1.0;
attenuation = 1.0; // Note: no volumetric attenuation along shadow rays for directional lights
[branch] if (lightData.cookieIndex >= 0)
{
float3 lightToSample = positionWS - lightData.positionWS;
float3 cookie = EvaluateCookie_Directional(lightLoopContext, lightData, lightToSample);
color *= cookie;
}
#ifdef SHADOWS_SHADOWMASK
// shadowMaskSelector.x is -1 if there is no shadow mask

#endif
}
// Note: no volumetric attenuation along shadow rays for directional lights.
[branch] if (lightData.cookieIndex >= 0)
{
float3 cookie = EvaluateCookie_Directional(lightLoopContext, lightData, positionWS);
color *= cookie;
}
}
//-----------------------------------------------------------------------------

float4 EvaluateCookie_Punctual(LightLoopContext lightLoopContext, LightData lightData,
float3 positionWS)
float3 lightToSample)
float3 lightToSample = positionWS - lightData.positionWS;
float3x3 lightToWorld = float3x3(lightData.right, lightData.up, lightData.forward);
float3 positionLS = mul(lightToSample, transpose(lightToWorld));
float3x3 lightToWorld = float3x3(lightData.right, lightData.up, lightData.forward);
float3 positionLS = mul(lightToSample, transpose(lightToWorld));
float4 cookie;

return cookie;
}
float GetPunctualShapeAttenuation(LightData lightData, float3 L, float distSq)
{
// Note: lightData.invSqrAttenuationRadius is 0 when applyRangeAttenuation is false
float attenuation = GetDistanceAttenuation(distSq, lightData.invSqrAttenuationRadius);
// Reminder: lights are oriented backward (-Z)
return attenuation * GetAngleAttenuation(L, -lightData.forward, lightData.angleScale, lightData.angleOffset);
}
// distances = {d, d^2, 1/d, d_proj}, where d_proj = dot(lightToSample, lightData.forward).
float3 N, float3 L, float dist, float distSq,
float3 N, float3 L, float3 lightToSample, float4 distances,
out float3 color, out float attenuation)
{
float3 positionWS = posInput.positionWS;

color = lightData.color;
attenuation = GetPunctualShapeAttenuation(lightData, L, distSq);
attenuation = SmoothPunctualLightAttenuation(distances, lightData.invSqrAttenuationRadius,
lightData.angleScale, lightData.angleOffset);
#if (SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET != 0)
float distVol = (lightData.lightType == GPULIGHTTYPE_PROJECTOR_BOX) ? distances.w : distances.x;
attenuation *= TransmittanceHomogeneousMedium(_GlobalFog_Extinction, distVol);
#endif
// Projector lights always have cookies, so we can perform clipping inside the if().
[branch] if (lightData.cookieIndex >= 0)
{
float4 cookie = EvaluateCookie_Punctual(lightLoopContext, lightData, lightToSample);
color *= cookie.rgb;
attenuation *= cookie.a;
}
#ifdef SHADOWS_SHADOWMASK
// shadowMaskSelector.x is -1 if there is no shadow mask

{
// TODO: make projector lights cast shadows.
float3 offset = float3(0.0, 0.0, 0.0); // GetShadowPosOffset(nDotL, normal);
float4 L_dist = float4(L, dist);
shadow = GetPunctualShadowAttenuation(lightLoopContext.shadowContext, positionWS + offset, N, lightData.shadowIndex, L_dist, posInput.positionSS);
shadow = GetPunctualShadowAttenuation(lightLoopContext.shadowContext, positionWS + offset, N, lightData.shadowIndex, lightData.positionWS, L, posInput.positionSS);
#ifdef SHADOWS_SHADOWMASK
// Note: Legacy Unity have two shadow mask mode. ShadowMask (ShadowMask contain static objects shadow and ShadowMap contain only dynamic objects shadow, final result is the minimun of both value)
// and ShadowMask_Distance (ShadowMask contain static objects shadow and ShadowMap contain everything and is blend with ShadowMask based on distance (Global distance setup in QualitySettigns)).

#endif
}
#if (SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET != 0)
[flatten] if (lightData.lightType == GPULIGHTTYPE_PROJECTOR_BOX)
{
float3 lightToSample = positionWS - lightData.positionWS;
dist = dot(-lightToSample, L);
}
shadow *= TransmittanceHomogeneousMedium(_GlobalFog_Extinction, dist);
#endif
// Projector lights always have cookies, so we can perform clipping inside the if().
[branch] if (lightData.cookieIndex >= 0)
{
float4 cookie = EvaluateCookie_Punctual(lightLoopContext, lightData, positionWS);
color *= cookie.rgb;
attenuation *= cookie.a;
}
}

25
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/Deferred.compute


// Include
//-------------------------------------------------------------------------------------
#include "../../ShaderPass/ShaderPass.cs.hlsl"
#define SHADERPASS SHADERPASS_DEFERRED_LIGHTING
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "../../Debug/DebugDisplay.hlsl"

StructuredBuffer<uint> g_TileList;
// Indirect
[numthreads(16, 16, 1)]
[numthreads(TILE_SIZE_FPTL, TILE_SIZE_FPTL, 1)]
uint tileIndex = g_TileList[g_TileListOffset + groupId];
uint2 tileCoord = uint2(tileIndex & 0xFFFF, tileIndex >> 16);
uint2 pixelCoord = tileCoord * GetTileSize() + groupThreadId;
uint tileIndex = g_TileList[g_TileListOffset + groupId];
uint2 tileCoord = uint2(tileIndex & ((1 << TILE_SIZE_FPTL) - 1), tileIndex >> TILE_SIZE_FPTL);
uint2 pixelCoord = tileCoord * GetTileSize() + groupThreadId;
uint featureFlags = TileVariantToFeatureFlags(VARIANT);
uint screenWidth = (uint)_ScreenSize.x;
uint numTilesX = (screenWidth + (TILE_SIZE_FPTL) - 1) / TILE_SIZE_FPTL;
uint featureFlags = TileVariantToFeatureFlags(VARIANT, tileCoord.x + tileCoord.y * numTilesX);
[numthreads(16, 16, 1)]
[numthreads(TILE_SIZE_FPTL, TILE_SIZE_FPTL, 1)]
uint2 tileCoord = (16 * groupId) / GetTileSize();
uint2 pixelCoord = dispatchThreadId;
uint featureFlags = LIGHT_FEATURE_MASK_FLAGS_OPAQUE | MATERIAL_FEATURE_MASK_FLAGS;
uint2 tileCoord = (TILE_SIZE_FPTL * groupId) / GetTileSize();
uint2 pixelCoord = dispatchThreadId;
uint featureFlags = UINT_MAX;
#endif

float3 specularLighting;
LightLoop(V, posInput, preLightData, bsdfData, bakeLightingData, featureFlags, diffuseLighting, specularLighting);
if ((_EnableSubsurfaceScattering != 0) && HaveSubsurfaceScattering(bsdfData))
if (_EnableSubsurfaceScattering != 0 && PixelHasSubsurfaceScattering(bsdfData))
{
specularLightingUAV[pixelCoord] = float4(specularLighting, 1.0);
diffuseLightingUAV[pixelCoord] = TagLightingForSSS(diffuseLighting);

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


lightData.positionWS = light.light.transform.position;
// Setting 0 for invSqrAttenuationRadius mean we have no range attenuation, but still have inverse square attenuation.
lightData.invSqrAttenuationRadius = additionalLightData.applyRangeAttenuation ? 1.0f / (light.range * light.range) : 0.0f;
bool applyRangeAttenuation = additionalLightData.applyRangeAttenuation && (gpuLightType != GPULightType.ProjectorBox);
lightData.invSqrAttenuationRadius = applyRangeAttenuation ? 1.0f / (light.range * light.range) : 0.0f;
lightData.color = GetLightColor(light);
lightData.forward = light.light.transform.forward; // Note: Light direction is oriented backward (-Z)

if (enableFeatureVariants)
{
cmd.SetComputeBufferParam(deferredComputeShader, kernel, HDShaderIDs.g_TileFeatureFlags, s_TileFeatureFlags);
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs.g_TileListOffset, variant * numTiles);
cmd.SetComputeBufferParam(deferredComputeShader, kernel, HDShaderIDs.g_TileList, s_TileList);
cmd.DispatchCompute(deferredComputeShader, kernel, s_DispatchIndirectBuffer, (uint)variant * 3 * sizeof(uint));

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


StructuredBuffer<float> g_logBaseBuffer; // don't support Buffer yet in unity
//#endif
#ifdef USE_INDIRECT
StructuredBuffer<uint> g_TileFeatureFlags;
#endif
StructuredBuffer<DirectionalLightData> _DirectionalLightDatas;
StructuredBuffer<LightData> _LightDatas;
StructuredBuffer<EnvLightData> _EnvLightDatas;

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/Shadow.hlsl


// example of overriding punctual lights
#ifdef SHADOW_DISPATCH_USE_CUSTOM_PUNCTUAL
float GetPunctualShadowAttenuation( ShadowContext shadowContext, float3 positionWS, float3 normalWS, int shadowDataIndex, float4 L )
float GetPunctualShadowAttenuation( ShadowContext shadowContext, float3 positionWS, float3 normalWS, int shadowDataIndex, float3 lightPositionWS, float3 L)
{
#ifdef SHADOW_DISPATCH_USE_SEPARATE_PUNC_ALGOS
// example for choosing different algos for point and spot lights

Texture2DArray tex = shadowContext.tex2DArray[SHADOW_DISPATCH_POINT_TEX];
SamplerComparisonState compSamp = shadowContext.compSamplers[SHADOW_DISPATCH_POINT_SMP];
uint algo = SHADOW_DISPATCH_POINT_ALG;
return EvalShadow_PointDepth( shadowContext, algo, tex, compSamp, positionWS, normalWS, shadowDataIndex, L );
return EvalShadow_PointDepth( shadowContext, algo, tex, compSamp, positionWS, normalWS, shadowDataIndex, lightPositionWS, L );
}
else
{

return EvalShadow_SpotDepth( shadowContext, algo, tex, compSamp, positionWS, normalWS, shadowDataIndex, L );
return EvalShadow_SpotDepth( shadowContext, algo, tex, compSamp, positionWS, normalWS, shadowDataIndex, lightPositionWS, L );
}
#else
// example for choosing the same algo

return EvalShadow_PunctualDepth( shadowContext, algo, tex, compSamp, positionWS, normalWS, shadowDataIndex, L );
return EvalShadow_PunctualDepth( shadowContext, algo, tex, compSamp, positionWS, normalWS, shadowDataIndex, lightPositionWS, L );
float GetPunctualShadowAttenuation( ShadowContext shadowContext, float3 positionWS, float3 normalWS, int shadowDataIndex, float4 L, float2 positionSS )
float GetPunctualShadowAttenuation( ShadowContext shadowContext, float3 positionWS, float3 normalWS, int shadowDataIndex, float3 lightPositionWS, float3 L, float2 positionSS )
return GetPunctualShadowAttenuation( shadowContext, positionWS, normalWS, shadowDataIndex, L );
return GetPunctualShadowAttenuation( shadowContext, positionWS, normalWS, shadowDataIndex, lightPositionWS, L );
}
#endif

22
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/Resources/VolumetricLighting.compute


#pragma kernel VolumetricLightingClustered VolumetricLighting=VolumetricLightingClustered ENABLE_REPROJECTION=0 LIGHTLOOP_TILE_PASS USE_CLUSTERED_LIGHTLIST
#pragma kernel VolumetricLightingClusteredReproj VolumetricLighting=VolumetricLightingClusteredReproj ENABLE_REPROJECTION=1 LIGHTLOOP_TILE_PASS USE_CLUSTERED_LIGHTLIST
#pragma enable_d3d11_debug_symbols
// #pragma debug
#define DEBUG_REPROJECTION 0

posInput.positionWS = GetPointAtDistance(ray, t);
float3 lightToSample = posInput.positionWS - light.positionWS;
float dist = sqrt(distSq);
float3 L = -lightToSample * rsqrt(distSq);
float distRcp = rsqrt(distSq);
float dist = distSq * distRcp;
float distProj = dot(lightToSample, light.forward);
float4 distances = float4(dist, distSq, distRcp, distProj);
float3 L = -lightToSample * distRcp;
EvaluateLight_Punctual(context, posInput, light, unused, 0, L, dist, distSq,
color, attenuation);
EvaluateLight_Punctual(context, posInput, light, unused, 0, L, lightToSample,
distances, color, attenuation);
float intensity = attenuation * rcpPdf;

float t = tEntr + tOffset;
posInput.positionWS = GetPointAtDistance(ray, t);
float3 L = -light.forward;
float3 L = -light.forward;
float3 lightToSample = posInput.positionWS - light.positionWS;
float distProj = dot(lightToSample, light.forward);
float4 distances = float4(1, 1, 1, distProj);
EvaluateLight_Punctual(context, posInput, light, unused, 0, L, 1, 1,
color, attenuation);
EvaluateLight_Punctual(context, posInput, light, unused, 0, L, lightToSample,
distances, color, attenuation);
// Note: the 'weight' accounts for transmittance from 'tEntr' to 't'.
float intensity = attenuation * weight;

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


[HideInInspector] _InvPrimScale("Inverse primitive scale for non-planar POM", Vector) = (1, 1, 0, 0)
[Enum(Use Emissive Color, 0, Use Emissive Mask, 1)] _EmissiveColorMode("Emissive color mode", Float) = 1
[Enum(UV0, 0, Planar, 4, TriPlanar, 5)] _UVEmissive("UV Set for emissive", Float) = 0
_TexWorldScaleEmissive("Scale to apply on world coordinate", Float) = 1.0
[HideInInspector] _UVMappingMaskEmissive("_UVMappingMaskEmissive", Color) = (1, 0, 0, 0)
// Wind
[ToggleOff] _EnableWind("Enable Wind", Float) = 0.0

#pragma shader_feature _PIXEL_DISPLACEMENT_LOCK_OBJECT_SCALE
#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _ _EMISSIVE_MAPPING_PLANAR _EMISSIVE_MAPPING_TRIPLANAR
#pragma shader_feature _LAYER_TILING_COUPLED_WITH_UNIFORM_OBJECT_SCALE
#pragma shader_feature _ _LAYER_MAPPING_PLANAR_BLENDMASK _LAYER_MAPPING_TRIPLANAR_BLENDMASK
#pragma shader_feature _ _LAYER_MAPPING_PLANAR0 _LAYER_MAPPING_TRIPLANAR0

// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
//enable GPU instancing support
#pragma multi_compile_instancing
//-------------------------------------------------------------------------------------
// Define

1001
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitData.hlsl
文件差异内容过多而无法显示
查看文件

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


[HideInInspector] _InvPrimScale("Inverse primitive scale for non-planar POM", Vector) = (1, 1, 0, 0)
[Enum(Use Emissive Color, 0, Use Emissive Mask, 1)] _EmissiveColorMode("Emissive color mode", Float) = 1
[Enum(UV0, 0, UV1, 1, UV2, 2, UV3, 3, Planar, 4, Triplanar, 5)] _UVEmissive("UV Set for emissive", Float) = 0
_TexWorldScaleEmissive("Scale to apply on world coordinate", Float) = 1.0
[HideInInspector] _UVMappingMaskEmissive("_UVMappingMaskEmissive", Color) = (1, 0, 0, 0)
// Wind
[ToggleOff] _EnableWind("Enable Wind", Float) = 0.0

// Tessellation specific
[Enum(None, 0, Phong, 1)] _TessellationMode("Tessellation mode", Float) = 0
_TessellationFactor("Tessellation Factor", Range(0.0, 15.0)) = 4.0
_TessellationFactor("Tessellation Factor", Range(0.0, 64.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

#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _TESSELLATION_PHONG
#pragma shader_feature _ _EMISSIVE_MAPPING_PLANAR _EMISSIVE_MAPPING_TRIPLANAR
#pragma shader_feature _LAYER_TILING_COUPLED_WITH_UNIFORM_OBJECT_SCALE
#pragma shader_feature _ _LAYER_MAPPING_PLANAR_BLENDMASK _LAYER_MAPPING_TRIPLANAR_BLENDMASK
#pragma shader_feature _ _LAYER_MAPPING_PLANAR0 _LAYER_MAPPING_TRIPLANAR0

// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
// enable GPU instancing
#pragma multi_compile_instancing
//-------------------------------------------------------------------------------------
// Define

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


return NUM_FEATURE_VARIANTS - 1;
}
// This function need to return a compile time value, else there is no optimization
uint TileVariantToFeatureFlags(uint variant)
#ifdef USE_INDIRECT
uint TileVariantToFeatureFlags(uint variant, uint tileIndex)
return kFeatureVariantFlags[variant];
if (variant == NUM_FEATURE_VARIANTS - 1)
{
// We don't have any compile-time feature information.
// Therefore, we load the feature classification data at runtime to avoid
// entering every single branch based on feature flags.
return g_TileFeatureFlags[tileIndex];
}
else
{
// Return the compile-time feature flags.
return kFeatureVariantFlags[variant];
}
#endif // USE_INDIRECT
//-----------------------------------------------------------------------------
// Helper functions/variable specific to this material
//-----------------------------------------------------------------------------

// This method allows us to know at compile time what material features should be removed from the code by Tile (Indepenently of the value of material feature flag per pixel).
// This is only useful for classification during lighting, so it's not needed in EncodeIntoGBuffer and ConvertSurfaceDataToBSDFData (where we always know exactly what the material feature is)
bool HasMaterialFeatureFlag(uint featureFlags, uint flag)
bool HasFeatureFlag(uint featureFlags, uint flag)
{
return ((featureFlags & flag) != 0);
}

bsdfData.thickness = _ThicknessRemaps[diffusionProfile].x + _ThicknessRemaps[diffusionProfile].y * thickness;
uint transmissionMode = BitFieldExtract(asuint(_TransmissionFlags), 2u * diffusionProfile, 2u);
bsdfData.useThickObjectMode = transmissionMode != TRANSMISSION_MODE_THIN;
#if SHADEROPTIONS_USE_DISNEY_SSS
bsdfData.transmittance = ComputeTransmittanceDisney( _ShapeParams[diffusionProfile].rgb,

_TransmissionTintsAndFresnel0[diffusionProfile].rgb,
bsdfData.thickness);
#endif
// Apply the transmission mode. Only the thick object mode performs the thickness displacement.
bsdfData.useThickObjectMode = transmissionMode != TRANSMISSION_MODE_THIN;
if (bsdfData.useThickObjectMode)
{
// Compute the thickness in world units along the normal.
float thicknessInMeters = bsdfData.thickness * METERS_PER_MILLIMETER;
float thicknessInUnits = thicknessInMeters * _WorldScales[bsdfData.diffusionProfile].y;
bsdfData.thickness = thicknessInUnits;
}
else
{
// Apply no displacement.
bsdfData.thickness = 0;
}
}
// Assume bsdfData.normalWS is init

bsdfData.materialFeatures = surfaceData.materialFeatures | MATERIALFEATUREFLAGS_LIT_STANDARD; // Not really needed but for consistency with deferred path
// Standard material
bsdfData.specularOcclusion = surfaceData.specularOcclusion;
bsdfData.normalWS = surfaceData.normalWS;
bsdfData.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness);
bsdfData.specularOcclusion = surfaceData.specularOcclusion;
bsdfData.normalWS = surfaceData.normalWS;
bsdfData.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness);
float metallic = HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR | MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION | MATERIALFEATUREFLAGS_LIT_IRIDESCENCE) ?
0.0 : surfaceData.metallic;
float metallic = HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR | MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION) ? 0.0 : surfaceData.metallic;
bsdfData.diffuseColor = ComputeDiffuseColor(surfaceData.baseColor, metallic);
bsdfData.fresnel0 = HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR) ? surfaceData.specularColor : ComputeFresnel0(surfaceData.baseColor, surfaceData.metallic, DEFAULT_SPECULAR_VALUE);
bsdfData.diffuseColor = ComputeDiffuseColor(surfaceData.baseColor, metallic);
bsdfData.fresnel0 = HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR) ? surfaceData.specularColor : ComputeFresnel0(surfaceData.baseColor, surfaceData.metallic, DEFAULT_SPECULAR_VALUE);
bsdfData.diffusionProfile = surfaceData.diffusionProfile;
bsdfData.diffusionProfile = surfaceData.diffusionProfile;
// Note: we have ZERO_INITIALIZE the struct so bsdfData.anisotropy == 0.0
// In forward everything is statically know and we could theorically cumulate all the material features. So the code reflect it.

if (HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING))
if (HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING))
if (HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
if (HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
if (HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
if (HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
if (HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_IRIDESCENCE))
if (HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_IRIDESCENCE))
if (HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
if (HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
{
// Modify fresnel0 and perceptualRoughness
FillMaterialClearCoatData(surfaceData.coatMask, bsdfData);

// The priority of feature is handled in the code here and reflect in the UI (see LitUI.cs)
// Process SSS and Transmission together as they encode almost the same data, negligible cost
if (HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
if (HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
metallic15 = GBUFFER_LIT_SSS_OR_TRANSMISSION;
// Special case: For SSS we will store the profile id and the subsurface radius at the location of the specular occlusion (in alpha channel of GBuffer0)

outGBuffer2.rgb = float3(surfaceData.specularOcclusion, surfaceData.thickness, HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING) ? 1.0 : 0.0); // thickness for Transmission
outGBuffer2.rgb = float3(surfaceData.specularOcclusion, surfaceData.thickness, HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING) ? 1.0 : 0.0); // thickness for Transmission
if (HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR))
if (HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR))
else if (HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
else if (HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
else if (HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_IRIDESCENCE))
else if (HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_IRIDESCENCE))
{
metallic15 = GBUFFER_LIT_IRIDESCENCE;
outGBuffer2.rgb = float3(0.0, surfaceData.thicknessIrid, 0.0);

}
// Encode coatMask (4bit) / mettalic (4bit)
outGBuffer2.a = PackFloatInt8bit(HasMaterialFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT) ? surfaceData.coatMask : 0.0, metallic15, 16.0);
outGBuffer2.a = PackFloatInt8bit(HasFeatureFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT) ? surfaceData.coatMask : 0.0, metallic15, 16.0);
void DecodeFromGBuffer(uint2 positionSS, uint featureFlags, out BSDFData bsdfData, out float3 bakeDiffuseLighting, out uint outMaterialFeatures)
// Fills the BSDFData. Also returns the (per-pixel) material feature flags inferred
// from the contents of the G-buffer, which can be used by the feature classification system.
// 'tileFeatureFlags' are compile-time flags provided by the feature classification system.
// If you're not using the feature classification system, pass 0.
uint DecodeFromGBuffer(uint2 positionSS, uint tileFeatureFlags, out BSDFData bsdfData, out float3 bakeDiffuseLighting)
ZERO_INITIALIZE(BSDFData, bsdfData);
// Isolate material features.
tileFeatureFlags &= MATERIAL_FEATURE_MASK_FLAGS;
bsdfData.materialFeatures = tileFeatureFlags; // Only tile-uniform feature evaluation
ZERO_INITIALIZE(BSDFData, bsdfData);
// If any of the flags of featureFlags is not set, it mean we know statically that
// the material feature is not used, so the compiler can optimize related code.
// Else we don't know if the material feature will be use, it is a dynamic condition.
bool enableSpecularColor = (metallic15 == GBUFFER_LIT_SPECULAR_COLOR); // This is always a dynamic test as it is very cheap
outMaterialFeatures = MATERIALFEATUREFLAGS_LIT_STANDARD; // It is mandatory to identity ourselve as standard shader, else we are consider as sky/background element
outMaterialFeatures |= (metallic15 == GBUFFER_LIT_SSS_OR_TRANSMISSION && inGBuffer2.g > 0.0) ? featureFlags & MATERIALFEATUREFLAGS_LIT_TRANSMISSION : 0; // Thickness > 0
outMaterialFeatures |= (metallic15 == GBUFFER_LIT_SSS_OR_TRANSMISSION && inGBuffer2.b > 0.0) ? featureFlags & MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING : 0; // TagSSS > 0
outMaterialFeatures |= (metallic15 <= GBUFFER_LIT_ANISOTROPIC_UPPER_BOUND && abs(inGBuffer2.b - 0.5) > 0.01) ? featureFlags & MATERIALFEATUREFLAGS_LIT_ANISOTROPY : 0; // Anisotropy != 0 (small tolerrance as 0.5 can be correctly encoded)
outMaterialFeatures |= (metallic15 == GBUFFER_LIT_IRIDESCENCE) ? featureFlags & MATERIALFEATUREFLAGS_LIT_IRIDESCENCE : 0;
outMaterialFeatures |= coatMask > 0.0 ? featureFlags & MATERIALFEATUREFLAGS_LIT_CLEAR_COAT : 0;
uint pixelFeatureFlags = MATERIALFEATUREFLAGS_LIT_STANDARD; // Only sky/background do not have the Standard material flag
bool pixelHasSpecularColor = (metallic15 == GBUFFER_LIT_SPECULAR_COLOR); // This is always a dynamic test as it is very cheap
bool pixelHasTransmission = (metallic15 == GBUFFER_LIT_SSS_OR_TRANSMISSION && inGBuffer2.g > 0); // Thickness > 0
bool pixelHasSubsurface = (metallic15 == GBUFFER_LIT_SSS_OR_TRANSMISSION && inGBuffer2.b > 0); // TagSSS > 0
bool pixelHasAnisotropy = (metallic15 <= GBUFFER_LIT_ANISOTROPIC_UPPER_BOUND && abs(inGBuffer2.b - 0.5) >= 1.0/255.0); // Anisotropy > 0
bool pixelHasIridescence = (metallic15 == GBUFFER_LIT_IRIDESCENCE);
bool pixelHasClearCoat = (coatMask > 0);
// Save for material classification
bsdfData.materialFeatures = outMaterialFeatures;
// Disable pixel features disabled by the tile.
pixelFeatureFlags |= tileFeatureFlags & (pixelHasSpecularColor ? MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR : 0);
pixelFeatureFlags |= tileFeatureFlags & (pixelHasTransmission ? MATERIALFEATUREFLAGS_LIT_TRANSMISSION : 0);
pixelFeatureFlags |= tileFeatureFlags & (pixelHasSubsurface ? MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING : 0);
pixelFeatureFlags |= tileFeatureFlags & (pixelHasAnisotropy ? MATERIALFEATUREFLAGS_LIT_ANISOTROPY : 0);
pixelFeatureFlags |= tileFeatureFlags & (pixelHasIridescence ? MATERIALFEATUREFLAGS_LIT_IRIDESCENCE : 0);
pixelFeatureFlags |= tileFeatureFlags & (pixelHasClearCoat ? MATERIALFEATUREFLAGS_LIT_CLEAR_COAT : 0);
// Start decompressing GBuffer
float3 baseColor = inGBuffer0.rgb;

bsdfData.normalWS = UnpackNormalOctEncode(float2(inGBuffer1.r, inGBuffer1.g));
// metallic15 is range [0..12] if mettallic data is needed
float metallic = (metallic15 <= GBUFFER_LIT_ANISOTROPIC_UPPER_BOUND) ? metallic15 * (1.0 / GBUFFER_LIT_ANISOTROPIC_UPPER_BOUND) : 0.0;
// metallic15 is range [0..12] if metallic data is needed
bool pixelHasNoMetallic = HasFeatureFlag(pixelFeatureFlags, MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR | MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION);
float metallic = pixelHasNoMetallic ? 0 : metallic15 * (1.0 / GBUFFER_LIT_ANISOTROPIC_UPPER_BOUND);
bsdfData.fresnel0 = enableSpecularColor ? Gamma20ToLinear(inGBuffer2.rgb) : ComputeFresnel0(baseColor, metallic, DEFAULT_SPECULAR_VALUE);
bsdfData.fresnel0 = HasFeatureFlag(pixelFeatureFlags, MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR) ? Gamma20ToLinear(inGBuffer2.rgb) : ComputeFresnel0(baseColor, metallic, DEFAULT_SPECULAR_VALUE);
// Note: we have ZERO_INITIALIZE the struct, so bsdfData.diffusionProfile == DIFFUSION_PROFILE_NEUTRAL_ID, bsdfData.anisotropy == 0.0, bsdfData.SubsurfaceMask == 0.0 etc...
// Note: we have ZERO_INITIALIZE the struct, so bsdfData.diffusionProfile == DIFFUSION_PROFILE_NEUTRAL_ID, bsdfData.anisotropy == 0, bsdfData.subsurfaceMask == 0 etc...
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
if (HasFeatureFlag(pixelFeatureFlags, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
// First we must extract the diffusion profile

bsdfData.diffusionProfile = sssData.diffusionProfile;
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING))
// The neutral value of subsurfaceMask is 0 (handled by ZERO_INITIALIZE).
if (HasFeatureFlag(pixelFeatureFlags, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING))
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
// The neutral value of thickness and transmittance is 0 (handled by ZERO_INITIALIZE).
if (HasFeatureFlag(pixelFeatureFlags, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
FillMaterialTransmission(inGBuffer2.g, bsdfData);
}

// Note that it mean that when we have the worse case, we always use Anisotropy and shader like deferred.shader are always the worst case (but only used for debugging)
if (HasMaterialFeatureFlag(featureFlags, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
if (HasFeatureFlag(tileFeatureFlags, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
if (HasFeatureFlag(pixelFeatureFlags, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
{
anisotropy = inGBuffer2.b * 2.0 - 1.0;
tangentWS = UnpackNormalOctEncode(inGBuffer2.rg * 2.0 - 1.0);

}
FillMaterialAnisotropy(anisotropy, tangentWS, bsdfData);
// Force the compiler to use the anisotropy path all the time
bsdfData.materialFeatures |= MATERIALFEATUREFLAGS_LIT_ANISOTROPY;
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_IRIDESCENCE))
if (HasFeatureFlag(pixelFeatureFlags, MATERIALFEATUREFLAGS_LIT_IRIDESCENCE))
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
// The neutral value of coatMask is 0 (handled by ZERO_INITIALIZE).
if (HasFeatureFlag(pixelFeatureFlags, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
{
// Modify fresnel0 and perceptualRoughness
FillMaterialClearCoatData(coatMask, bsdfData);

ConvertAnisotropyToClampRoughness(bsdfData.perceptualRoughness, bsdfData.anisotropy, bsdfData.roughnessT, bsdfData.roughnessB);
bakeDiffuseLighting = inGBuffer3.rgb;
}
void DecodeFromGBuffer(uint2 positionSS, uint featureFlags, out BSDFData bsdfData, out float3 bakeDiffuseLighting)
{
uint unsused;
DecodeFromGBuffer(positionSS, featureFlags, bsdfData, bakeDiffuseLighting, unsused);
return pixelFeatureFlags;
}
// Function call from the material classification compute shader

float3 unused;
// Call the regular function, compiler will optimized out everything not used.
// Note that all material feature flag bellow are in the same GBuffer (inGBuffer2) and thus material classification only sample one Gbuffer
uint materialFeatures;
DecodeFromGBuffer(positionSS, MATERIAL_FEATURE_MASK_FLAGS, bsdfData, unused, materialFeatures);
return materialFeatures;
return DecodeFromGBuffer(positionSS, UINT_MAX, bsdfData, unused);
//-----------------------------------------------------------------------------
// Debug method (use to display values)

preLightData.clampNdotV = NdotV; // Caution: The handling of edge cases where N is directed away from the screen is handled during Gbuffer/forward pass, so here do nothing
preLightData.iblPerceptualRoughness = bsdfData.perceptualRoughness;
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
{
preLightData.coatPartLambdaV = GetSmithJointGGXPartLambdaV(NdotV, CLEAR_COAT_ROUGHNESS);
preLightData.coatIblR = reflect(-V, N);

// We avoid divergent evaluation of the GGX, as that nearly doubles the cost.
// If the tile has anisotropy, all the pixels within the tile are evaluated as anisotropic.
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
{
float TdotV = dot(bsdfData.tangentWS, V);
float BdotV = dot(bsdfData.bitangentWS, V);

// to match the reference for rough metals, but further darkens dielectrics.
preLightData.ltcMagnitudeFresnel = bsdfData.fresnel0 * ltcGGXFresnelMagnitudeDiff + (float3)ltcGGXFresnelMagnitude;
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
{
float2 uv = LTC_LUT_OFFSET + LTC_LUT_SCALE * float2(CLEAR_COAT_PERCEPTUAL_ROUGHNESS, theta * INV_HALF_PI);

// This function require the 3 structure surfaceData, builtinData, bsdfData because it may require both the engine side data, and data that will not be store inside the gbuffer.
float3 GetBakedDiffuseLigthing(SurfaceData surfaceData, BuiltinData builtinData, BSDFData bsdfData, PreLightData preLightData)
{
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING))
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING))
{
bsdfData.diffuseColor = ApplySubsurfaceScatteringTexturingMode(bsdfData.diffuseColor, bsdfData.diffusionProfile);
}

// Subsurface Scattering functions
//-----------------------------------------------------------------------------
bool HaveSubsurfaceScattering(BSDFData bsdfData)
bool PixelHasSubsurfaceScattering(BSDFData bsdfData)
return HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING);
return bsdfData.subsurfaceMask != 0 && HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING);
}
//-----------------------------------------------------------------------------

// BSDF share between directional light, punctual light and area light (reference)
//-----------------------------------------------------------------------------
// This function apply BSDF
void BSDF( float3 V, float3 L, float3 positionWS, PreLightData preLightData, BSDFData bsdfData,
// This function apply BSDF. Assumes that NdotL is positive.
void BSDF( float3 V, float3 L, float NdotL, float3 positionWS, PreLightData preLightData, BSDFData bsdfData,
out float3 diffuseLighting,
out float3 specularLighting)
{

// Optimized math. Ref: PBR Diffuse Lighting for GGX + Smith Microsurfaces (slide 114).
float NdotL = saturate(dot(N, L)); // Must have the same value without the clamp
float LdotV = dot(L, V);
float invLenLV = rsqrt(max(2.0 * LdotV + 2.0, FLT_EPS)); // invLenLV = rcp(length(L + V)) - caution about the case where V and L are opposite, it can happen, use max to avoid this

float3 F = F_Schlick(bsdfData.fresnel0, LdotH);
float DV;
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
{
float3 H = (L + V) * invLenLV;
// For anisotropy we must not saturate these values

// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
diffuseLighting = diffuseTerm;
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
{
// Apply isotropic GGX for clear coat
// Note: coat F is scalar as it is a dieletric

// Note: The modification of the base roughness and fresnel0 by the clear coat is already handled in FillMaterialClearCoatData
// Very coarse attempt at doing energy conservation for the diffuse layer based on NdotL. No science.
diffuseLighting *= F_Schlick(CLEAR_COAT_F0, NdotL);
diffuseLighting *= lerp(1, F_Schlick(CLEAR_COAT_F0, NdotL), bsdfData.coatMask);
}
}

// OR transmitted (back) lighting, never both at the same time. For transmitted lighting,
// we need to push the shading position back to avoid self-shadowing problems.
// Note: 'bsdfData.thickness' is in world units, and already accounts for the transmission mode.
float displacement = 0;
[flatten] if (bsdfData.useThickObjectMode && NdotL < 0)
{
// Compute the thickness in world units along the normal.
float thicknessInMeters = bsdfData.thickness * METERS_PER_MILLIMETER;
float thicknessInUnits = thicknessInMeters * _WorldScales[bsdfData.diffusionProfile].y;
// Compute the thickness in world units along the light vector.
displacement = thicknessInUnits / -NdotL;
}
// Compute the thickness in world units along the light vector.
// We need a max(x, 0) here, but the saturate() is free,
// and we don't expect the total displacement of over 1 meter.
float displacement = saturate(bsdfData.thickness / -NdotL);
return displacement * L;
}

float3 EvaluateTransmission(BSDFData bsdfData, float NdotL, float NdotV, float attenuation)
{
float wrappedNdotL = ComputeWrappedDiffuseLighting(-NdotL, SSS_WRAP_LIGHT);
float negatedNdotL = saturate(-NdotL);
float negatedNdotL = -NdotL;
// Apply wrapped lighting to better handle thin objects (cards) at grazing angles.
float backNdotL = bsdfData.useThickObjectMode ? negatedNdotL : wrappedNdotL;

#ifdef LIT_DIFFUSE_LAMBERT_BRDF
attenuation *= Lambert();
#else
attenuation *= INV_PI * F_Transm_Schlick(0, 0.5, NdotV) * F_Transm_Schlick(0, 0.5, backNdotL);
attenuation *= INV_PI * F_Transm_Schlick(0, 0.5, NdotV) * F_Transm_Schlick(0, 0.5, abs(backNdotL));
float intensity = attenuation * backNdotL;
float intensity = max(0, attenuation * backNdotL); // Warning: attenuation can be greater than 1
return intensity * bsdfData.transmittance;
}

float3 L = -lightData.forward; // Lights point backward in Unity
float NdotL = dot(N, L); // Note: Ideally this N here should be vertex normal - use for transmisison
// Compute displacement for fake thickObject transmission
posInput.positionWS += ComputeThicknessDisplacement(bsdfData, L, NdotL);
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
// Compute displacement for fake thickObject transmission
posInput.positionWS += ComputeThicknessDisplacement(bsdfData, L, NdotL);
}
float intensity = attenuation * saturate(NdotL);
float intensity = max(0, attenuation * NdotL); // Warning: attenuation can be greater than 1
BSDF(V, L, posInput.positionWS, preLightData, bsdfData, lighting.diffuse, lighting.specular);
BSDF(V, L, NdotL, posInput.positionWS, preLightData, bsdfData, lighting.diffuse, lighting.specular);
[branch] if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
[branch] if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
lighting.diffuse += EvaluateTransmission(bsdfData, NdotL, preLightData.clampNdotV, attenuation * lightData.diffuseScale);

float3 lightToSample = posInput.positionWS - lightData.positionWS;
int lightType = lightData.lightType;
float3 unL = (lightType != GPULIGHTTYPE_PROJECTOR_BOX) ? -lightToSample : -lightData.forward;
float distSq = dot(unL, unL);
float distRcp = rsqrt(distSq);
float dist = distSq * distRcp;
float3 N = bsdfData.normalWS;
float3 L = unL * distRcp;
float NdotL = dot(N, L);
float3 L;
float4 distances; // {d, d^2, 1/d, d_proj}
distances.w = dot(lightToSample, lightData.forward);
// Compute displacement for fake thickObject transmission
posInput.positionWS += ComputeThicknessDisplacement(bsdfData, L, NdotL);
if (lightType == GPULIGHTTYPE_PROJECTOR_BOX)
{
L = -lightData.forward;
distances.xyz = 1; // No distance or angle attenuation
}
else
{
float3 unL = -lightToSample;
float distSq = dot(unL, unL);
float distRcp = rsqrt(distSq);
float dist = distSq * distRcp;
L = unL * distRcp;
distances.xyz = float3(dist, distSq, distRcp);
}
float3 N = bsdfData.normalWS;
float NdotL = dot(N, L);
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
// Compute displacement for fake thickObject transmission
// Warning: distances computed above are NOT modified!
// This is not correct, of course, but is done for performance reasons.
posInput.positionWS += ComputeThicknessDisplacement(bsdfData, L, NdotL);
}
EvaluateLight_Punctual(lightLoopContext, posInput, lightData, bakeLightingData, N, L, dist, distSq, color, attenuation);
EvaluateLight_Punctual(lightLoopContext, posInput, lightData, bakeLightingData, N, L,
lightToSample, distances, color, attenuation);
float intensity = attenuation * saturate(NdotL);
float intensity = max(0, attenuation * NdotL); // Warning: attenuation can be greater than 1
// Note: We use NdotL here to early out, but in case of clear coat this is not correct. But we are ok with this
[branch] if (intensity > 0.0)

bsdfData.roughnessT = max(bsdfData.roughnessT, lightData.minRoughness);
bsdfData.roughnessB = max(bsdfData.roughnessB, lightData.minRoughness);
BSDF(V, L, posInput.positionWS, preLightData, bsdfData, lighting.diffuse, lighting.specular);
BSDF(V, L, NdotL, posInput.positionWS, preLightData, bsdfData, lighting.diffuse, lighting.specular);
[branch] if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
[branch] if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
lighting.diffuse += EvaluateTransmission(bsdfData, NdotL, preLightData.clampNdotV, attenuation * lightData.diffuseScale);

float invAspectRatio = radius / (radius + (0.5 * len));
// Compute the light attenuation.
float intensity = GetEllipsoidalDistanceAttenuation(unL, lightData.invSqrAttenuationRadius,
axis, invAspectRatio);
float intensity = EllipsoidalDistanceAttenuation(unL, lightData.invSqrAttenuationRadius,
axis, invAspectRatio);
// Terminate if the shaded point is too far away.
if (intensity == 0.0)

// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse = preLightData.ltcMagnitudeDiffuse * ltcValue;
[branch] if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
[branch] if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
// Flip the view vector and the normal. The bitangent stays the same.
float3x3 flipMatrix = float3x3(-1, 0, 0,

lighting.specular = preLightData.ltcMagnitudeFresnel * ltcValue;
// Evaluate the coat part
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
{
lighting.diffuse *= (1.0 - preLightData.ltcMagnitudeCoatFresnel);
lighting.specular *= (1.0 - preLightData.ltcMagnitudeCoatFresnel);

#ifdef ELLIPSOIDAL_ATTENUATION
// The attenuation volume is an axis-aligned ellipsoid s.t.
// r1 = (r + w / 2), r2 = (r + h / 2), r3 = r.
float intensity = GetEllipsoidalDistanceAttenuation(unL, invHalfDim);
float intensity = EllipsoidalDistanceAttenuation(unL, invHalfDim);
float intensity = GetBoxDistanceAttenuation(unL, invHalfDim);
float intensity = BoxDistanceAttenuation(unL, invHalfDim);
#endif
// Terminate if the shaded point is too far away.

// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse = preLightData.ltcMagnitudeDiffuse * ltcValue;
[branch] if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
[branch] if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
// Flip the view vector and the normal. The bitangent stays the same.
float3x3 flipMatrix = float3x3(-1, 0, 0,

lighting.specular += preLightData.ltcMagnitudeFresnel * ltcValue;
// Evaluate the coat part
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
{
lighting.diffuse *= (1.0 - preLightData.ltcMagnitudeCoatFresnel);
lighting.specular *= (1.0 - preLightData.ltcMagnitudeCoatFresnel);

R = (positionWS + projectionDistance * R) - lightData.positionWS;
// Test again for clear coat
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION && HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION && HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
{
dirLS = mul(coatR, worldToLocal);
projectionDistance = IntersectRaySphereSimple(positionLS, dirLS, sphereOuterDistance);

// TODO: add distance based roughness
// Test again for clear coat
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION && HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION && HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
{
dirLS = mul(coatR, worldToLocal);
projectionDistance = IntersectRayAABBSimple(positionLS, dirLS, -boxOuterDistance, boxOuterDistance);

envLighting = F * preLD.rgb;
// Evaluate the Clear Coat component if needed
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
{
// No correction needed for coatR as it is smooth
// Note: coat F is scalar as it is a dieletric

#endif
float3 modifiedDiffuseColor;
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING))
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING))
modifiedDiffuseColor = ApplySubsurfaceScatteringTexturingMode(bsdfData.diffuseColor, bsdfData.diffusionProfile);
else
modifiedDiffuseColor = bsdfData.diffuseColor;

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.shader


[Enum(UV0, 0, UV1, 1, UV2, 2, UV3, 3)] _UVDetail("UV Set for detail", Float) = 0
[HideInInspector] _UVDetailsMappingMask("_UVDetailsMappingMask", Color) = (1, 0, 0, 0)
[ToggleOff] _LinkDetailsWithBase("LinkDetailsWithBase", Float) = 1.0
[Enum(UV0, 0, Planar, 4, TriPlanar, 5)] _UVEmissive("UV Set for emissive", Float) = 0
_TexWorldScaleEmissive("Scale to apply on world coordinate", Float) = 1.0
[HideInInspector] _UVMappingMaskEmissive("_UVMappingMaskEmissive", Color) = (1, 0, 0, 0)
// Wind
[ToggleOff] _EnableWind("Enable Wind", Float) = 0.0

#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _ _REFRACTION_PLANE _REFRACTION_SPHERE
#pragma shader_feature _ _EMISSIVE_MAPPING_PLANAR _EMISSIVE_MAPPING_TRIPLANAR
#pragma shader_feature _ _MAPPING_PLANAR _MAPPING_TRIPLANAR
#pragma shader_feature _NORMALMAP_TANGENT_SPACE
#pragma shader_feature _ _REQUIRE_UV2 _REQUIRE_UV3

// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
//enable GPU instancing support
#pragma multi_compile_instancing
//-------------------------------------------------------------------------------------
// Define

540
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitData.hlsl


//-------------------------------------------------------------------------------------
// Fill SurfaceData/Builtin data function
//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/Sampling/SampleUVMapping.hlsl"
#include "../MaterialUtilities.hlsl"
#include "../Decal/DecalUtilities.hlsl"
// TODO: move this function to commonLighting.hlsl once validated it work correctly
float GetSpecularOcclusionFromBentAO(float3 V, float3 bentNormalWS, SurfaceData surfaceData)
{
// Retrieve cone angle
// Ambient occlusion is cosine weighted, thus use following equation. See slide 129
float cosAv = sqrt(1.0 - surfaceData.ambientOcclusion);
float roughness = max(PerceptualSmoothnessToRoughness(surfaceData.perceptualSmoothness), 0.01); // Clamp to 0.01 to avoid edge cases
float cosAs = exp2((-log(10.0)/log(2.0)) * Sq(roughness));
float cosB = dot(bentNormalWS, reflect(-V, surfaceData.normalWS));
return SphericalCapIntersectionSolidArea(cosAv, cosAs, cosB) / (TWO_PI * (1.0 - cosAs));
}
void GetBuiltinData(FragInputs input, SurfaceData surfaceData, float alpha, float3 bentNormalWS, float depthOffset, out BuiltinData builtinData)
{
// Builtin Data
builtinData.opacity = alpha;
// TODO: Sample lightmap/lightprobe/volume proxy
// This should also handle projective lightmap
builtinData.bakeDiffuseLighting = SampleBakedGI(input.positionWS, bentNormalWS, input.texCoord1, input.texCoord2);
// It is safe to call this function here as surfaceData have been filled
// We want to know if we must enable transmission on GI for SSS material, if the material have no SSS, this code will be remove by the compiler.
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{
// For now simply recall the function with inverted normal, the compiler should be able to optimize the lightmap case to not resample the directional lightmap
// however it will not optimize the lightprobe case due to the proxy volume relying on dynamic if (we rely must get right of this dynamic if), not a problem for SH9, but a problem for proxy volume.
// TODO: optimize more this code.
// Add GI transmission contribution by resampling the GI for inverted vertex normal
builtinData.bakeDiffuseLighting += SampleBakedGI(input.positionWS, -input.worldToTangent[2], input.texCoord1, input.texCoord2) * bsdfData.transmittance;
}
#ifdef SHADOWS_SHADOWMASK
float4 shadowMask = SampleShadowMask(input.positionWS, input.texCoord1);
builtinData.shadowMask0 = shadowMask.x;
builtinData.shadowMask1 = shadowMask.y;
builtinData.shadowMask2 = shadowMask.z;
builtinData.shadowMask3 = shadowMask.w;
#else
builtinData.shadowMask0 = 0.0;
builtinData.shadowMask1 = 0.0;
builtinData.shadowMask2 = 0.0;
builtinData.shadowMask3 = 0.0;
#endif
// Emissive Intensity is only use here, but is part of BuiltinData to enforce UI parameters as we want the users to fill one color and one intensity
builtinData.emissiveIntensity = _EmissiveIntensity; // We still store intensity here so we can reuse it with debug code
builtinData.emissiveColor = _EmissiveColor * builtinData.emissiveIntensity * lerp(float3(1.0, 1.0, 1.0), surfaceData.baseColor.rgb, _AlbedoAffectEmissive);
#ifdef _EMISSIVE_COLOR_MAP
builtinData.emissiveColor *= SAMPLE_TEXTURE2D(_EmissiveColorMap, sampler_EmissiveColorMap, TRANSFORM_TEX(input.texCoord0, _EmissiveColorMap)).rgb;
#endif
builtinData.velocity = float2(0.0, 0.0);
#if (SHADERPASS == SHADERPASS_DISTORTION) || defined(DEBUG_DISPLAY)
float3 distortion = SAMPLE_TEXTURE2D(_DistortionVectorMap, sampler_DistortionVectorMap, input.texCoord0).rgb;
distortion.rg = distortion.rg * _DistortionVectorScale.xx + _DistortionVectorBias.xx;
builtinData.distortion = distortion.rg * _DistortionScale;
builtinData.distortionBlur = clamp(distortion.b * _DistortionBlurScale, 0.0, 1.0) * (_DistortionBlurRemapMax - _DistortionBlurRemapMin) + _DistortionBlurRemapMin;
#else
builtinData.distortion = float2(0.0, 0.0);
builtinData.distortionBlur = 0.0;
#endif
builtinData.depthOffset = depthOffset;
}
// Struct that gather UVMapping info of all layers + common calculation
// This is use to abstract the mapping that can differ on layers
struct LayerTexCoord
{
#ifndef LAYERED_LIT_SHADER
UVMapping base;
UVMapping details;
#else
// Regular texcoord
UVMapping base0;
UVMapping base1;
UVMapping base2;
UVMapping base3;
UVMapping details0;
UVMapping details1;
UVMapping details2;
UVMapping details3;
// Dedicated for blend mask
UVMapping blendMask;
#endif
// Store information that will be share by all UVMapping
float3 vertexNormalWS; // TODO: store also object normal map for object triplanar
float3 triplanarWeights;
#ifdef SURFACE_GRADIENT
// tangent basis for each UVSet - up to 4 for now
float3 vertexTangentWS0, vertexBitangentWS0;
float3 vertexTangentWS1, vertexBitangentWS1;
float3 vertexTangentWS2, vertexBitangentWS2;
float3 vertexTangentWS3, vertexBitangentWS3;
#endif
};
#ifdef SURFACE_GRADIENT
void GenerateLayerTexCoordBasisTB(FragInputs input, inout LayerTexCoord layerTexCoord)
{
float3 vertexNormalWS = input.worldToTangent[2];
layerTexCoord.vertexTangentWS0 = input.worldToTangent[0];
layerTexCoord.vertexBitangentWS0 = input.worldToTangent[1];
// TODO: We should use relative camera position here - This will be automatic when we will move to camera relative space.
float3 dPdx = ddx_fine(input.positionWS);
float3 dPdy = ddy_fine(input.positionWS);
float3 sigmaX = dPdx - dot(dPdx, vertexNormalWS) * vertexNormalWS;
float3 sigmaY = dPdy - dot(dPdy, vertexNormalWS) * vertexNormalWS;
//float flipSign = dot(sigmaY, cross(vertexNormalWS, sigmaX) ) ? -1.0 : 1.0;
float flipSign = dot(dPdy, cross(vertexNormalWS, dPdx)) < 0.0 ? -1.0 : 1.0; // gives same as the commented out line above
// TODO: Optimize! The compiler will not be able to remove the tangent space that are not use because it can't know due to our UVMapping constant we use for both base and details
// To solve this we should track which UVSet is use for normal mapping... Maybe not as simple as it sounds
SurfaceGradientGenBasisTB(vertexNormalWS, sigmaX, sigmaY, flipSign, input.texCoord1, layerTexCoord.vertexTangentWS1, layerTexCoord.vertexBitangentWS1);
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
SurfaceGradientGenBasisTB(vertexNormalWS, sigmaX, sigmaY, flipSign, input.texCoord2, layerTexCoord.vertexTangentWS2, layerTexCoord.vertexBitangentWS2);
#endif
#if defined(_REQUIRE_UV3)
SurfaceGradientGenBasisTB(vertexNormalWS, sigmaX, sigmaY, flipSign, input.texCoord3, layerTexCoord.vertexTangentWS3, layerTexCoord.vertexBitangentWS3);
#endif
}
#endif
#ifndef LAYERED_LIT_SHADER
// Want to use only one sampler for normalmap/bentnormalmap either we use OS or TS. And either we have normal map or bent normal or both.
#ifdef _NORMALMAP_TANGENT_SPACE
#if defined(_NORMALMAP)
#define SAMPLER_NORMALMAP_IDX sampler_NormalMap
#elif defined(_BENTNORMALMAP)
#define SAMPLER_NORMALMAP_IDX sampler_BentNormalMap
#endif
#else
#if defined(_NORMALMAP)
#define SAMPLER_NORMALMAP_IDX sampler_NormalMapOS
#elif defined(_BENTNORMALMAP)
#define SAMPLER_NORMALMAP_IDX sampler_BentNormalMapOS
#endif
#endif
#define SAMPLER_DETAILMAP_IDX sampler_DetailMap
#define SAMPLER_MASKMAP_IDX sampler_MaskMap
#define SAMPLER_HEIGHTMAP_IDX sampler_HeightMap
#define SAMPLER_SUBSURFACE_MASKMAP_IDX sampler_SubsurfaceMaskMap
#define SAMPLER_THICKNESSMAP_IDX sampler_ThicknessMap
// include LitDataIndividualLayer to define GetSurfaceData
#define LAYER_INDEX 0
#define ADD_IDX(Name) Name
#define ADD_ZERO_IDX(Name) Name
#ifdef _NORMALMAP
#define _NORMALMAP_IDX
#endif
#ifdef _NORMALMAP_TANGENT_SPACE
#define _NORMALMAP_TANGENT_SPACE_IDX
#endif
#ifdef _DETAIL_MAP
#define _DETAIL_MAP_IDX
#endif
#ifdef _SUBSURFACE_MASK_MAP
#define _SUBSURFACE_MASK_MAP_IDX
#endif
#ifdef _THICKNESSMAP
#define _THICKNESSMAP_IDX
#endif
#ifdef _MASKMAP
#define _MASKMAP_IDX
#endif
#ifdef _BENTNORMALMAP
#define _BENTNORMALMAP_IDX
#endif
#include "LitDataIndividualLayer.hlsl"
// This maybe call directly by tessellation (domain) shader, thus all part regarding surface gradient must be done
// in function with FragInputs input as parameters
// layerTexCoord must have been initialize to 0 outside of this function
void GetLayerTexCoord(float2 texCoord0, float2 texCoord1, float2 texCoord2, float2 texCoord3,
float3 positionWS, float3 vertexNormalWS, inout LayerTexCoord layerTexCoord)
{
layerTexCoord.vertexNormalWS = vertexNormalWS;
layerTexCoord.triplanarWeights = ComputeTriplanarWeights(vertexNormalWS);
int mappingType = UV_MAPPING_UVSET;
#if defined(_MAPPING_PLANAR)
mappingType = UV_MAPPING_PLANAR;
#elif defined(_MAPPING_TRIPLANAR)
mappingType = UV_MAPPING_TRIPLANAR;
#endif
// Be sure that the compiler is aware that we don't use UV1 to UV3 for main layer so it can optimize code
ComputeLayerTexCoord( texCoord0, texCoord1, texCoord2, texCoord3, float4(1.0, 0.0, 0.0, 0.0), _UVDetailsMappingMask,
_BaseColorMap_ST.xy, _BaseColorMap_ST.zw, _DetailMap_ST.xy, _DetailMap_ST.zw, 1.0, _LinkDetailsWithBase,
positionWS, _TexWorldScale,
mappingType, layerTexCoord);
}
// This is call only in this file
// layerTexCoord must have been initialize to 0 outside of this function
void GetLayerTexCoord(FragInputs input, inout LayerTexCoord layerTexCoord)
{
#ifdef SURFACE_GRADIENT
GenerateLayerTexCoordBasisTB(input, layerTexCoord);
#endif
GetLayerTexCoord( input.texCoord0, input.texCoord1, input.texCoord2, input.texCoord3,
input.positionWS, input.worldToTangent[2].xyz, layerTexCoord);
}
#include "LitDataDisplacement.hlsl"
void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs posInput, out SurfaceData surfaceData, out BuiltinData builtinData)
{
#ifdef LOD_FADE_CROSSFADE // enable dithering LOD transition if user select CrossFade transition in LOD group
LODDitheringTransition(posInput.positionSS, unity_LODFade.x);
#endif
ApplyDoubleSidedFlipOrMirror(input); // Apply double sided flip on the vertex normal
LayerTexCoord layerTexCoord;
ZERO_INITIALIZE(LayerTexCoord, layerTexCoord);
GetLayerTexCoord(input, layerTexCoord);
float depthOffset = ApplyPerPixelDisplacement(input, V, layerTexCoord);
#ifdef _DEPTHOFFSET_ON
ApplyDepthOffsetPositionInput(V, depthOffset, GetWorldToHClipMatrix(), posInput);
#endif
// We perform the conversion to world of the normalTS outside of the GetSurfaceData
// so it allow us to correctly deal with detail normal map and optimize the code for the layered shaders
float3 normalTS;
float3 bentNormalTS;
float3 bentNormalWS;
float alpha = GetSurfaceData(input, layerTexCoord, surfaceData, normalTS, bentNormalTS);
GetNormalWS(input, V, normalTS, surfaceData.normalWS);
// Ensure that the normal is front-facing.
float NdotV;
surfaceData.normalWS = GetViewReflectedNormal(surfaceData.normalWS, V, NdotV);
// Use bent normal to sample GI if available
#ifdef _BENTNORMALMAP
GetNormalWS(input, V, bentNormalTS, bentNormalWS);
#else
bentNormalWS = surfaceData.normalWS;
#endif
// By default we use the ambient occlusion with Tri-ace trick (apply outside) for specular occlusion.
// If user provide bent normal then we process a better term
#if defined(_BENTNORMALMAP) && defined(_ENABLESPECULAROCCLUSION)
// If we have bent normal and ambient occlusion, process a specular occlusion
surfaceData.specularOcclusion = GetSpecularOcclusionFromBentAO(V, bentNormalWS, surfaceData);
#elif defined(_MASKMAP)
surfaceData.specularOcclusion = GetSpecularOcclusionFromAmbientOcclusion(NdotV, surfaceData.ambientOcclusion, PerceptualSmoothnessToRoughness(surfaceData.perceptualSmoothness));
#else
surfaceData.specularOcclusion = 1.0;
#endif
// This is use with anisotropic material
surfaceData.tangentWS = Orthonormalize(surfaceData.tangentWS, surfaceData.normalWS);
AddDecalContribution(posInput.positionSS, surfaceData);
#if defined(DEBUG_DISPLAY)
if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE)
{
surfaceData.baseColor = GetTextureDataDebug(_DebugMipMapMode, layerTexCoord.base.uv, _BaseColorMap, _BaseColorMap_TexelSize, _BaseColorMap_MipInfo, surfaceData.baseColor);
surfaceData.metallic = 0;
}
#endif
// Caution: surfaceData must be fully initialize before calling GetBuiltinData
GetBuiltinData(input, surfaceData, alpha, bentNormalWS, depthOffset, builtinData);
}
#include "LitDataMeshModification.hlsl"
#endif // #ifndef LAYERED_LIT_SHADER
//-------------------------------------------------------------------------------------
// Fill SurfaceData/Builtin data function
//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/Sampling/SampleUVMapping.hlsl"
#include "../MaterialUtilities.hlsl"
#include "../Decal/DecalUtilities.hlsl"
// TODO: move this function to commonLighting.hlsl once validated it work correctly
float GetSpecularOcclusionFromBentAO(float3 V, float3 bentNormalWS, SurfaceData surfaceData)
{
// Retrieve cone angle
// Ambient occlusion is cosine weighted, thus use following equation. See slide 129
float cosAv = sqrt(1.0 - surfaceData.ambientOcclusion);
float roughness = max(PerceptualSmoothnessToRoughness(surfaceData.perceptualSmoothness), 0.01); // Clamp to 0.01 to avoid edge cases
float cosAs = exp2((-log(10.0)/log(2.0)) * Sq(roughness));
float cosB = dot(bentNormalWS, reflect(-V, surfaceData.normalWS));
return SphericalCapIntersectionSolidArea(cosAv, cosAs, cosB) / (TWO_PI * (1.0 - cosAs));
}
// Struct that gather UVMapping info of all layers + common calculation
// This is use to abstract the mapping that can differ on layers
struct LayerTexCoord
{
#ifndef LAYERED_LIT_SHADER
UVMapping base;
UVMapping details;
#else
// Regular texcoord
UVMapping base0;
UVMapping base1;
UVMapping base2;
UVMapping base3;
UVMapping details0;
UVMapping details1;
UVMapping details2;
UVMapping details3;
// Dedicated for blend mask
UVMapping blendMask;
#endif
// Store information that will be share by all UVMapping
float3 vertexNormalWS; // TODO: store also object normal map for object triplanar
float3 triplanarWeights;
#ifdef SURFACE_GRADIENT
// tangent basis for each UVSet - up to 4 for now
float3 vertexTangentWS0, vertexBitangentWS0;
float3 vertexTangentWS1, vertexBitangentWS1;
float3 vertexTangentWS2, vertexBitangentWS2;
float3 vertexTangentWS3, vertexBitangentWS3;
#endif
};
#ifdef SURFACE_GRADIENT
void GenerateLayerTexCoordBasisTB(FragInputs input, inout LayerTexCoord layerTexCoord)
{
float3 vertexNormalWS = input.worldToTangent[2];
layerTexCoord.vertexTangentWS0 = input.worldToTangent[0];
layerTexCoord.vertexBitangentWS0 = input.worldToTangent[1];
// TODO: We should use relative camera position here - This will be automatic when we will move to camera relative space.
float3 dPdx = ddx_fine(input.positionWS);
float3 dPdy = ddy_fine(input.positionWS);
float3 sigmaX = dPdx - dot(dPdx, vertexNormalWS) * vertexNormalWS;
float3 sigmaY = dPdy - dot(dPdy, vertexNormalWS) * vertexNormalWS;
//float flipSign = dot(sigmaY, cross(vertexNormalWS, sigmaX) ) ? -1.0 : 1.0;
float flipSign = dot(dPdy, cross(vertexNormalWS, dPdx)) < 0.0 ? -1.0 : 1.0; // gives same as the commented out line above
// TODO: Optimize! The compiler will not be able to remove the tangent space that are not use because it can't know due to our UVMapping constant we use for both base and details
// To solve this we should track which UVSet is use for normal mapping... Maybe not as simple as it sounds
SurfaceGradientGenBasisTB(vertexNormalWS, sigmaX, sigmaY, flipSign, input.texCoord1, layerTexCoord.vertexTangentWS1, layerTexCoord.vertexBitangentWS1);
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
SurfaceGradientGenBasisTB(vertexNormalWS, sigmaX, sigmaY, flipSign, input.texCoord2, layerTexCoord.vertexTangentWS2, layerTexCoord.vertexBitangentWS2);
#endif
#if defined(_REQUIRE_UV3)
SurfaceGradientGenBasisTB(vertexNormalWS, sigmaX, sigmaY, flipSign, input.texCoord3, layerTexCoord.vertexTangentWS3, layerTexCoord.vertexBitangentWS3);
#endif
}
#endif
#ifndef LAYERED_LIT_SHADER
// Want to use only one sampler for normalmap/bentnormalmap either we use OS or TS. And either we have normal map or bent normal or both.
#ifdef _NORMALMAP_TANGENT_SPACE
#if defined(_NORMALMAP)
#define SAMPLER_NORMALMAP_IDX sampler_NormalMap
#elif defined(_BENTNORMALMAP)
#define SAMPLER_NORMALMAP_IDX sampler_BentNormalMap
#endif
#else
#if defined(_NORMALMAP)
#define SAMPLER_NORMALMAP_IDX sampler_NormalMapOS
#elif defined(_BENTNORMALMAP)
#define SAMPLER_NORMALMAP_IDX sampler_BentNormalMapOS
#endif
#endif
#define SAMPLER_DETAILMAP_IDX sampler_DetailMap
#define SAMPLER_MASKMAP_IDX sampler_MaskMap
#define SAMPLER_HEIGHTMAP_IDX sampler_HeightMap
#define SAMPLER_SUBSURFACE_MASKMAP_IDX sampler_SubsurfaceMaskMap
#define SAMPLER_THICKNESSMAP_IDX sampler_ThicknessMap
// include LitDataIndividualLayer to define GetSurfaceData
#define LAYER_INDEX 0
#define ADD_IDX(Name) Name
#define ADD_ZERO_IDX(Name) Name
#ifdef _NORMALMAP
#define _NORMALMAP_IDX
#endif
#ifdef _NORMALMAP_TANGENT_SPACE
#define _NORMALMAP_TANGENT_SPACE_IDX
#endif
#ifdef _DETAIL_MAP
#define _DETAIL_MAP_IDX
#endif
#ifdef _SUBSURFACE_MASK_MAP
#define _SUBSURFACE_MASK_MAP_IDX
#endif
#ifdef _THICKNESSMAP
#define _THICKNESSMAP_IDX
#endif
#ifdef _MASKMAP
#define _MASKMAP_IDX
#endif
#ifdef _BENTNORMALMAP
#define _BENTNORMALMAP_IDX
#endif
#include "LitDataIndividualLayer.hlsl"
// This maybe call directly by tessellation (domain) shader, thus all part regarding surface gradient must be done
// in function with FragInputs input as parameters
// layerTexCoord must have been initialize to 0 outside of this function
void GetLayerTexCoord(float2 texCoord0, float2 texCoord1, float2 texCoord2, float2 texCoord3,
float3 positionWS, float3 vertexNormalWS, inout LayerTexCoord layerTexCoord)
{
layerTexCoord.vertexNormalWS = vertexNormalWS;
layerTexCoord.triplanarWeights = ComputeTriplanarWeights(vertexNormalWS);
int mappingType = UV_MAPPING_UVSET;
#if defined(_MAPPING_PLANAR)
mappingType = UV_MAPPING_PLANAR;
#elif defined(_MAPPING_TRIPLANAR)
mappingType = UV_MAPPING_TRIPLANAR;
#endif
// Be sure that the compiler is aware that we don't use UV1 to UV3 for main layer so it can optimize code
ComputeLayerTexCoord( texCoord0, texCoord1, texCoord2, texCoord3, float4(1.0, 0.0, 0.0, 0.0), _UVDetailsMappingMask,
_BaseColorMap_ST.xy, _BaseColorMap_ST.zw, _DetailMap_ST.xy, _DetailMap_ST.zw, 1.0, _LinkDetailsWithBase,
positionWS, _TexWorldScale,
mappingType, layerTexCoord);
}
// This is call only in this file
// layerTexCoord must have been initialize to 0 outside of this function
void GetLayerTexCoord(FragInputs input, inout LayerTexCoord layerTexCoord)
{
#ifdef SURFACE_GRADIENT
GenerateLayerTexCoordBasisTB(input, layerTexCoord);
#endif
GetLayerTexCoord( input.texCoord0, input.texCoord1, input.texCoord2, input.texCoord3,
input.positionWS, input.worldToTangent[2].xyz, layerTexCoord);
}
#include "LitDataDisplacement.hlsl"
#include "LitBuiltinData.hlsl"
void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs posInput, out SurfaceData surfaceData, out BuiltinData builtinData)
{
#ifdef LOD_FADE_CROSSFADE // enable dithering LOD transition if user select CrossFade transition in LOD group
LODDitheringTransition(posInput.positionSS, unity_LODFade.x);
#endif
ApplyDoubleSidedFlipOrMirror(input); // Apply double sided flip on the vertex normal
LayerTexCoord layerTexCoord;
ZERO_INITIALIZE(LayerTexCoord, layerTexCoord);
GetLayerTexCoord(input, layerTexCoord);
float depthOffset = ApplyPerPixelDisplacement(input, V, layerTexCoord);
#ifdef _DEPTHOFFSET_ON
ApplyDepthOffsetPositionInput(V, depthOffset, GetWorldToHClipMatrix(), posInput);
#endif
// We perform the conversion to world of the normalTS outside of the GetSurfaceData
// so it allow us to correctly deal with detail normal map and optimize the code for the layered shaders
float3 normalTS;
float3 bentNormalTS;
float3 bentNormalWS;
float alpha = GetSurfaceData(input, layerTexCoord, surfaceData, normalTS, bentNormalTS);
GetNormalWS(input, V, normalTS, surfaceData.normalWS);
// Ensure that the normal is front-facing.
float NdotV;
surfaceData.normalWS = GetViewReflectedNormal(surfaceData.normalWS, V, NdotV);
// Use bent normal to sample GI if available
#ifdef _BENTNORMALMAP
GetNormalWS(input, V, bentNormalTS, bentNormalWS);
#else
bentNormalWS = surfaceData.normalWS;
#endif
// By default we use the ambient occlusion with Tri-ace trick (apply outside) for specular occlusion.
// If user provide bent normal then we process a better term
#if defined(_BENTNORMALMAP) && defined(_ENABLESPECULAROCCLUSION)
// If we have bent normal and ambient occlusion, process a specular occlusion
surfaceData.specularOcclusion = GetSpecularOcclusionFromBentAO(V, bentNormalWS, surfaceData);
#elif defined(_MASKMAP)
surfaceData.specularOcclusion = GetSpecularOcclusionFromAmbientOcclusion(NdotV, surfaceData.ambientOcclusion, PerceptualSmoothnessToRoughness(surfaceData.perceptualSmoothness));
#else
surfaceData.specularOcclusion = 1.0;
#endif
// This is use with anisotropic material
surfaceData.tangentWS = Orthonormalize(surfaceData.tangentWS, surfaceData.normalWS);
AddDecalContribution(posInput.positionSS, surfaceData);
#if defined(DEBUG_DISPLAY)
if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE)
{
surfaceData.baseColor = GetTextureDataDebug(_DebugMipMapMode, layerTexCoord.base.uv, _BaseColorMap, _BaseColorMap_TexelSize, _BaseColorMap_MipInfo, surfaceData.baseColor);
surfaceData.metallic = 0;
}
#endif
// Caution: surfaceData must be fully initialize before calling GetBuiltinData
GetBuiltinData(input, surfaceData, alpha, bentNormalWS, depthOffset, builtinData);
}
#include "LitDataMeshModification.hlsl"
#endif // #ifndef LAYERED_LIT_SHADER

520
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitProperties.hlsl


// ===========================================================================
// WARNING:
// On PS4, texture/sampler declarations need to be outside of CBuffers
// Otherwise those parameters are not bound correctly at runtime.
// ===========================================================================
TEXTURE2D(_DistortionVectorMap);
SAMPLER(sampler_DistortionVectorMap);
TEXTURE2D(_EmissiveColorMap);
SAMPLER(sampler_EmissiveColorMap);
#ifndef LAYERED_LIT_SHADER
TEXTURE2D(_DiffuseLightingMap);
SAMPLER(sampler_DiffuseLightingMap);
TEXTURE2D(_BaseColorMap);
SAMPLER(sampler_BaseColorMap);
TEXTURE2D(_MaskMap);
SAMPLER(sampler_MaskMap);
TEXTURE2D(_BentNormalMap); // Reuse sampler from normal map
SAMPLER(sampler_BentNormalMap);
TEXTURE2D(_NormalMap);
SAMPLER(sampler_NormalMap);
TEXTURE2D(_NormalMapOS);
SAMPLER(sampler_NormalMapOS);
TEXTURE2D(_DetailMap);
SAMPLER(sampler_DetailMap);
TEXTURE2D(_HeightMap);
SAMPLER(sampler_HeightMap);
TEXTURE2D(_TangentMap);
SAMPLER(sampler_TangentMap);
TEXTURE2D(_TangentMapOS);
SAMPLER(sampler_TangentMapOS);
TEXTURE2D(_AnisotropyMap);
SAMPLER(sampler_AnisotropyMap);
TEXTURE2D(_SubsurfaceMaskMap);
SAMPLER(sampler_SubsurfaceMaskMap);
TEXTURE2D(_ThicknessMap);
SAMPLER(sampler_ThicknessMap);
TEXTURE2D(_SpecularColorMap);
SAMPLER(sampler_SpecularColorMap);
TEXTURE2D(_TransmittanceColorMap);
SAMPLER(sampler_TransmittanceColorMap);
#else
// Set of users variables
#define PROP_DECL(type, name) type name##0, name##1, name##2, name##3
// sampler are share by texture type inside a layered material but we need to support that a particualr layer have no texture, so we take the first sampler of available texture as the share one
// mean we must declare all sampler
#define PROP_DECL_TEX2D(name)\
TEXTURE2D(MERGE_NAME(name, 0)); \
SAMPLER(MERGE_NAME(MERGE_NAME(sampler, name), 0)); \
TEXTURE2D(MERGE_NAME(name, 1)); \
SAMPLER(MERGE_NAME(MERGE_NAME(sampler, name), 1)); \
TEXTURE2D(MERGE_NAME(name, 2)); \
SAMPLER(MERGE_NAME(MERGE_NAME(sampler, name), 2)); \
TEXTURE2D(MERGE_NAME(name, 3)); \
SAMPLER(MERGE_NAME(MERGE_NAME(sampler, name), 3))
PROP_DECL_TEX2D(_BaseColorMap);
PROP_DECL_TEX2D(_MaskMap);
PROP_DECL_TEX2D(_BentNormalMap);
PROP_DECL_TEX2D(_NormalMap);
PROP_DECL_TEX2D(_NormalMapOS);
PROP_DECL_TEX2D(_DetailMap);
PROP_DECL_TEX2D(_HeightMap);
PROP_DECL_TEX2D(_SubsurfaceMaskMap);
PROP_DECL_TEX2D(_ThicknessMap);
TEXTURE2D(_LayerMaskMap);
SAMPLER(sampler_LayerMaskMap);
TEXTURE2D(_LayerInfluenceMaskMap);
SAMPLER(sampler_LayerInfluenceMaskMap);
#endif
CBUFFER_START(UnityPerMaterial)
// shared constant between lit and layered lit
float _AlphaCutoff;
float _AlphaCutoffPrepass;
float _AlphaCutoffPostpass;
float4 _DoubleSidedConstants;
float _DistortionScale;
float _DistortionVectorScale;
float _DistortionVectorBias;
float _DistortionBlurScale;
float _DistortionBlurRemapMin;
float _DistortionBlurRemapMax;
float _PPDMaxSamples;
float _PPDMinSamples;
float _PPDLodThreshold;
float3 _EmissiveColor;
float _EmissiveIntensity;
float _AlbedoAffectEmissive;
float _EnableSpecularOcclusion;
// Transparency
float3 _TransmittanceColor;
float _IOR;
float _ATDistance;
float _ThicknessMultiplier;
// Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor"
// value that exist to identify if the GI emission need to be enabled.
// In our case we don't use such a mechanism but need to keep the code quiet. We declare the value and always enable it.
// TODO: Fix the code in legacy unity so we can customize the beahvior for GI
float3 _EmissionColor;
float4 _EmissiveColorMap_ST;
float4 _InvPrimScale; // Only XY are used
// Wind
float _InitialBend;
float _Stiffness;
float _Drag;
float _ShiverDrag;
float _ShiverDirectionality;
#ifndef LAYERED_LIT_SHADER
// Set of users variables
float4 _BaseColor;
float4 _BaseColorMap_ST;
float4 _BaseColorMap_TexelSize;
// ===========================================================================
// WARNING:
// On PS4, texture/sampler declarations need to be outside of CBuffers
// Otherwise those parameters are not bound correctly at runtime.
// ===========================================================================
TEXTURE2D(_DistortionVectorMap);
SAMPLER(sampler_DistortionVectorMap);
TEXTURE2D(_EmissiveColorMap);
SAMPLER(sampler_EmissiveColorMap);
#ifndef LAYERED_LIT_SHADER
TEXTURE2D(_DiffuseLightingMap);
SAMPLER(sampler_DiffuseLightingMap);
TEXTURE2D(_BaseColorMap);
SAMPLER(sampler_BaseColorMap);
TEXTURE2D(_MaskMap);
SAMPLER(sampler_MaskMap);
TEXTURE2D(_BentNormalMap); // Reuse sampler from normal map
SAMPLER(sampler_BentNormalMap);
TEXTURE2D(_NormalMap);
SAMPLER(sampler_NormalMap);
TEXTURE2D(_NormalMapOS);
SAMPLER(sampler_NormalMapOS);
TEXTURE2D(_DetailMap);
SAMPLER(sampler_DetailMap);
TEXTURE2D(_HeightMap);
SAMPLER(sampler_HeightMap);
TEXTURE2D(_TangentMap);
SAMPLER(sampler_TangentMap);
TEXTURE2D(_TangentMapOS);
SAMPLER(sampler_TangentMapOS);
TEXTURE2D(_AnisotropyMap);
SAMPLER(sampler_AnisotropyMap);
TEXTURE2D(_SubsurfaceMaskMap);
SAMPLER(sampler_SubsurfaceMaskMap);
TEXTURE2D(_ThicknessMap);
SAMPLER(sampler_ThicknessMap);
TEXTURE2D(_SpecularColorMap);
SAMPLER(sampler_SpecularColorMap);
TEXTURE2D(_TransmittanceColorMap);
SAMPLER(sampler_TransmittanceColorMap);
#else
// Set of users variables
#define PROP_DECL(type, name) type name##0, name##1, name##2, name##3
// sampler are share by texture type inside a layered material but we need to support that a particualr layer have no texture, so we take the first sampler of available texture as the share one
// mean we must declare all sampler
#define PROP_DECL_TEX2D(name)\
TEXTURE2D(MERGE_NAME(name, 0)); \
SAMPLER(MERGE_NAME(MERGE_NAME(sampler, name), 0)); \
TEXTURE2D(MERGE_NAME(name, 1)); \
SAMPLER(MERGE_NAME(MERGE_NAME(sampler, name), 1)); \
TEXTURE2D(MERGE_NAME(name, 2)); \
SAMPLER(MERGE_NAME(MERGE_NAME(sampler, name), 2)); \
TEXTURE2D(MERGE_NAME(name, 3)); \
SAMPLER(MERGE_NAME(MERGE_NAME(sampler, name), 3))
PROP_DECL_TEX2D(_BaseColorMap);
PROP_DECL_TEX2D(_MaskMap);
PROP_DECL_TEX2D(_BentNormalMap);
PROP_DECL_TEX2D(_NormalMap);
PROP_DECL_TEX2D(_NormalMapOS);
PROP_DECL_TEX2D(_DetailMap);
PROP_DECL_TEX2D(_HeightMap);
PROP_DECL_TEX2D(_SubsurfaceMaskMap);
PROP_DECL_TEX2D(_ThicknessMap);
TEXTURE2D(_LayerMaskMap);
SAMPLER(sampler_LayerMaskMap);
TEXTURE2D(_LayerInfluenceMaskMap);
SAMPLER(sampler_LayerInfluenceMaskMap);
#endif
CBUFFER_START(UnityPerMaterial)
// shared constant between lit and layered lit
float _AlphaCutoff;
float _AlphaCutoffPrepass;
float _AlphaCutoffPostpass;
float4 _DoubleSidedConstants;
float _DistortionScale;
float _DistortionVectorScale;
float _DistortionVectorBias;
float _DistortionBlurScale;
float _DistortionBlurRemapMin;
float _DistortionBlurRemapMax;
float _PPDMaxSamples;
float _PPDMinSamples;
float _PPDLodThreshold;
float3 _EmissiveColor;
float _EmissiveIntensity;
float _AlbedoAffectEmissive;
float _EnableSpecularOcclusion;
// Transparency
float3 _TransmittanceColor;
float _IOR;
float _ATDistance;
float _ThicknessMultiplier;
// Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor"
// value that exist to identify if the GI emission need to be enabled.
// In our case we don't use such a mechanism but need to keep the code quiet. We declare the value and always enable it.
// TODO: Fix the code in legacy unity so we can customize the beahvior for GI
float3 _EmissionColor;
float4 _EmissiveColorMap_ST;
float _TexWorldScaleEmissive;
float4 _UVMappingMaskEmissive;
float4 _InvPrimScale; // Only XY are used
// Wind
float _InitialBend;
float _Stiffness;
float _Drag;
float _ShiverDrag;
float _ShiverDirectionality;
#ifndef LAYERED_LIT_SHADER
// Set of users variables
float4 _BaseColor;
float4 _BaseColorMap_ST;
float4 _BaseColorMap_TexelSize;
float _Metallic;
float _Smoothness;
float _SmoothnessRemapMin;
float _SmoothnessRemapMax;
float _AORemapMin;
float _AORemapMax;
float _NormalScale;
float4 _DetailMap_ST;
float _DetailAlbedoScale;
float _DetailNormalScale;
float _DetailSmoothnessScale;
float4 _HeightMap_TexelSize; // Unity facility. This will provide the size of the heightmap to the shader
float _HeightAmplitude;
float _HeightCenter;
float _Anisotropy;
int _DiffusionProfile;
float _SubsurfaceMask;
float _Thickness;
float4 _ThicknessRemap;
float _CoatMask;
float4 _SpecularColor;
float _TexWorldScale;
float _InvTilingScale;
float4 _UVMappingMask;
float4 _UVDetailsMappingMask;
float _LinkDetailsWithBase;
#else // LAYERED_LIT_SHADER
// Set of users variables
PROP_DECL(float4, _BaseColor);
float4 _BaseColorMap0_ST;
float4 _BaseColorMap1_ST;
float4 _BaseColorMap2_ST;
float4 _BaseColorMap3_ST;
float _Metallic;
float _Smoothness;
float _SmoothnessRemapMin;
float _SmoothnessRemapMax;
float _AORemapMin;
float _AORemapMax;
float _NormalScale;
float4 _DetailMap_ST;
float _DetailAlbedoScale;
float _DetailNormalScale;
float _DetailSmoothnessScale;
float4 _HeightMap_TexelSize; // Unity facility. This will provide the size of the heightmap to the shader
float _HeightAmplitude;
float _HeightCenter;
float _Anisotropy;
int _DiffusionProfile;
float _SubsurfaceMask;
float _Thickness;
float4 _ThicknessRemap;
float _CoatMask;
float4 _SpecularColor;
float _TexWorldScale;
float _InvTilingScale;
float4 _UVMappingMask;
float4 _UVDetailsMappingMask;
float _LinkDetailsWithBase;
#else // LAYERED_LIT_SHADER
// Set of users variables
PROP_DECL(float4, _BaseColor);
float4 _BaseColorMap0_ST;
float4 _BaseColorMap1_ST;
float4 _BaseColorMap2_ST;
float4 _BaseColorMap3_ST;
PROP_DECL(float, _Metallic);
PROP_DECL(float, _Smoothness);
PROP_DECL(float, _SmoothnessRemapMin);
PROP_DECL(float, _SmoothnessRemapMax);
PROP_DECL(float, _AORemapMin);
PROP_DECL(float, _AORemapMax);
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;
float4 _DetailMap0_ST;
float4 _DetailMap1_ST;
float4 _DetailMap2_ST;
float4 _DetailMap3_ST;
PROP_DECL(float, _UVDetail);
PROP_DECL(float, _DetailAlbedoScale);
PROP_DECL(float, _DetailNormalScale);
PROP_DECL(float, _DetailSmoothnessScale);
PROP_DECL(float, _HeightAmplitude);
PROP_DECL(float, _HeightCenter);
PROP_DECL(int, _DiffusionProfile);
PROP_DECL(float, _SubsurfaceMask);
PROP_DECL(float, _Thickness);
PROP_DECL(float4, _ThicknessRemap);
PROP_DECL(float, _OpacityAsDensity);
float _InheritBaseNormal1;
float _InheritBaseNormal2;
float _InheritBaseNormal3;
float _InheritBaseHeight1;
float _InheritBaseHeight2;
float _InheritBaseHeight3;
float _InheritBaseColor1;
float _InheritBaseColor2;
float _InheritBaseColor3;
PROP_DECL(float, _HeightOffset);
float _HeightTransition;
float4 _LayerMaskMap_ST;
float _TexWorldScaleBlendMask;
PROP_DECL(float, _TexWorldScale);
PROP_DECL(float, _InvTilingScale);
float4 _UVMappingMaskBlendMask;
PROP_DECL(float4, _UVMappingMask);
PROP_DECL(float4, _UVDetailsMappingMask);
PROP_DECL(float, _LinkDetailsWithBase);
#endif // LAYERED_LIT_SHADER
// Tessellation specific
#ifdef TESSELLATION_ON
float _TessellationFactor;
float _TessellationFactorMinDistance;
float _TessellationFactorMaxDistance;
float _TessellationFactorTriangleSize;
float _TessellationShapeFactor;
float _TessellationBackFaceCullEpsilon;
float _TessellationObjectScale;
float _TessellationTilingScale;
#endif
CBUFFER_END
PROP_DECL(float, _Metallic);
PROP_DECL(float, _Smoothness);
PROP_DECL(float, _SmoothnessRemapMin);
PROP_DECL(float, _SmoothnessRemapMax);
PROP_DECL(float, _AORemapMin);
PROP_DECL(float, _AORemapMax);
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;
float4 _DetailMap0_ST;
float4 _DetailMap1_ST;
float4 _DetailMap2_ST;
float4 _DetailMap3_ST;
PROP_DECL(float, _UVDetail);
PROP_DECL(float, _DetailAlbedoScale);
PROP_DECL(float, _DetailNormalScale);
PROP_DECL(float, _DetailSmoothnessScale);
PROP_DECL(float, _HeightAmplitude);
PROP_DECL(float, _HeightCenter);
PROP_DECL(int, _DiffusionProfile);
PROP_DECL(float, _SubsurfaceMask);
PROP_DECL(float, _Thickness);
PROP_DECL(float4, _ThicknessRemap);
PROP_DECL(float, _OpacityAsDensity);
float _InheritBaseNormal1;
float _InheritBaseNormal2;
float _InheritBaseNormal3;
float _InheritBaseHeight1;
float _InheritBaseHeight2;
float _InheritBaseHeight3;
float _InheritBaseColor1;
float _InheritBaseColor2;
float _InheritBaseColor3;
PROP_DECL(float, _HeightOffset);
float _HeightTransition;
float4 _LayerMaskMap_ST;
float _TexWorldScaleBlendMask;
PROP_DECL(float, _TexWorldScale);
PROP_DECL(float, _InvTilingScale);
float4 _UVMappingMaskBlendMask;
PROP_DECL(float4, _UVMappingMask);
PROP_DECL(float4, _UVDetailsMappingMask);
PROP_DECL(float, _LinkDetailsWithBase);
#endif // LAYERED_LIT_SHADER
// Tessellation specific
#ifdef TESSELLATION_ON
float _TessellationFactor;
float _TessellationFactorMinDistance;
float _TessellationFactorMaxDistance;
float _TessellationFactorTriangleSize;
float _TessellationShapeFactor;
float _TessellationBackFaceCullEpsilon;
float _TessellationObjectScale;
float _TessellationTilingScale;
#endif
CBUFFER_END

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitReference.hlsl


{
float3 lightDiff, lightSpec;
BSDF(V, L, positionWS, preLightData, bsdfData, lightDiff, lightSpec);
BSDF(V, L, NdotL, positionWS, preLightData, bsdfData, lightDiff, lightSpec);
diffuseLighting += lightDiff * (sinLT / dist2 * NdotL);
specularLighting += lightSpec * (sinLT / dist2 * NdotL);

float cosLNs = saturate(dot(-L, Ns));
// We calculate area reference light with the area integral rather than the solid angle one.
float illuminance = cosLNs * saturate(dot(bsdfData.normalWS, L)) / (sqrDist * lightPdf);
float NdotL = saturate(dot(bsdfData.normalWS, L));
float illuminance = cosLNs * NdotL / (sqrDist * lightPdf);
float3 localDiffuseLighting = float3(0.0, 0.0, 0.0);
float3 localSpecularLighting = float3(0.0, 0.0, 0.0);

BSDF(V, L, positionWS, preLightData, bsdfData, localDiffuseLighting, localSpecularLighting);
BSDF(V, L, NdotL, positionWS, preLightData, bsdfData, localDiffuseLighting, localSpecularLighting);
localDiffuseLighting *= lightData.color * illuminance * lightData.diffuseScale;
localSpecularLighting *= lightData.color * illuminance * lightData.specularScale;
}

{
float3x3 localToWorld;
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
{
localToWorld = float3x3(bsdfData.tangentWS, bsdfData.bitangentWS, bsdfData.normalWS);
}

float weightOverPdf;
// GGX BRDF
if (HasMaterialFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_ANISOTROPY))
{
ImportanceSampleAnisoGGX(u, V, localToWorld, bsdfData.roughnessT, bsdfData.roughnessB, NdotV, L, VdotH, NdotL, weightOverPdf);
}

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


[Enum(UV0, 0, UV1, 1, UV2, 2, UV3, 3)] _UVDetail("UV Set for detail", Float) = 0
[HideInInspector] _UVDetailsMappingMask("_UVDetailsMappingMask", Color) = (1, 0, 0, 0)
[ToggleOff] _LinkDetailsWithBase("LinkDetailsWithBase", Float) = 1.0
[Enum(UV0, 0, UV1, 1, UV2, 2, UV3, 3, Planar, 4, Triplanar, 5)] _UVEmissive("UV Set for emissive", Float) = 0
_TexWorldScaleEmissive("Scale to apply on world coordinate", Float) = 1.0
[HideInInspector] _UVMappingMaskEmissive("_UVMappingMaskEmissive", Color) = (1, 0, 0, 0)
// Wind
[ToggleOff] _EnableWind("Enable Wind", Float) = 0.0

// Tessellation specific
[Enum(None, 0, Phong, 1)] _TessellationMode("Tessellation mode", Float) = 0
_TessellationFactor("Tessellation Factor", Range(0.0, 15.0)) = 4.0
_TessellationFactor("Tessellation Factor", Range(0.0, 64.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

#pragma shader_feature _ _TESSELLATION_PHONG
#pragma shader_feature _ _REFRACTION_PLANE _REFRACTION_SPHERE
#pragma shader_feature _ _EMISSIVE_MAPPING_PLANAR _EMISSIVE_MAPPING_TRIPLANAR
#pragma shader_feature _ _MAPPING_PLANAR _MAPPING_TRIPLANAR
#pragma shader_feature _NORMALMAP_TANGENT_SPACE
#pragma shader_feature _ _REQUIRE_UV2 _REQUIRE_UV3

// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
//enable GPU instancing support
#pragma multi_compile_instancing
//-------------------------------------------------------------------------------------
// Define

19
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.compute


#define SSS_USE_LDS_CACHE 1
#define SSS_TAA_INTEGRATION 1 // Smoother results at the cost of a tiny amount of flickering in under-sampled areas
#define SSS_ENABLE_NEAR_FIELD 0 // Greatly increases the number of samples. Comes at a high cost.
#define SSS_SAMPLE_TEST_HTILE 0 // Potential optimization. YMMV.
#define SSS_USE_TANGENT_PLANE 0 // Improves the accuracy of the approximation(0 -> 1st order). High cost. Does not work with back-facing normals.
#define SSS_CLAMP_ARTIFACT 0 // Reduces bleeding. Use with SSS_USE_TANGENT_PLANE.
#define SSS_DEBUG_LOD 0

float3 tangentX, float3 tangentY, float4x4 projMatrix,
inout float3 totalIrradiance, inout float3 totalWeight)
{
float r = _FilterKernels[profileID][i][iR];
float r = _FilterKernels[profileID][i][iR];
float phi = SampleDiskFibonacci(i, n).y;
float phi = SampleDiskFibonacci(i, n).y;
phi += VanDerCorputBase2(_TaaFrameIndex % 4) * TWO_PI;
#endif
float sinPsi = _TaaFrameRotation.x;
float cosPsi = _TaaFrameRotation.y;
// The angle 'psi' is loop-invariant. All the trigonometry is done at compile time.
// cos(a + b) = cos(a) * cos(b) - sin(a) * sin(b)
// sin(a + b) = sin(a) * cos(b) + cos(a) * sin(b)
float cosSum = cos(phi) * cosPsi - sin(phi) * sinPsi;
float sinSum = sin(phi) * cosPsi + cos(phi) * sinPsi;
float2 vec = r * float2(cosSum, sinSum);
#else
#endif
// Compute the screen-space position and the squared distance (in mm) in the image plane.
int2 position; float xy2;

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


#pragma shader_feature _ _BLENDMODE_ALPHA _BLENDMODE_ADD _BLENDMODE_PRE_MULTIPLY
#pragma shader_feature _ENABLE_FOG_ON_TRANSPARENT
//enable GPU instancing support
#pragma multi_compile_instancing
//-------------------------------------------------------------------------------------
// Define
//-------------------------------------------------------------------------------------

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/DefaultHDMaterial.mat


- _SubsurfaceRadius: 1
- _SurfaceType: 0
- _TexWorldScale: 1
- _TexWorldScaleEmissive: 1
- _Thickness: 1
- _ThicknessMultiplier: 1
- _TransparentBackfaceEnable: 0

- _UVDetail: 0
- _UVEmissive: 0
- _UVSec: 0
- _ZTestMode: 8
- _ZWrite: 1

- _TransmittanceColor: {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}
- _UVMappingMaskEmissive: {r: 1, g: 0, b: 0, a: 0}

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPass.cs


GBuffer,
Forward,
ForwardUnlit,
DeferredLighting,
DepthOnly,
Velocity,
Distortion,

17
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPass.cs.hlsl


#define SHADERPASS_GBUFFER (0)
#define SHADERPASS_FORWARD (1)
#define SHADERPASS_FORWARD_UNLIT (2)
#define SHADERPASS_DEPTH_ONLY (3)
#define SHADERPASS_VELOCITY (4)
#define SHADERPASS_DISTORTION (5)
#define SHADERPASS_LIGHT_TRANSPORT (6)
#define SHADERPASS_SHADOWS (7)
#define SHADERPASS_SUBSURFACE_SCATTERING (8)
#define SHADERPASS_VOLUMETRIC_LIGHTING (9)
#define SHADERPASS_DBUFFER (10)
#define SHADERPASS_DEFERRED_LIGHTING (3)
#define SHADERPASS_DEPTH_ONLY (4)
#define SHADERPASS_VELOCITY (5)
#define SHADERPASS_DISTORTION (6)
#define SHADERPASS_LIGHT_TRANSPORT (7)
#define SHADERPASS_SHADOWS (8)
#define SHADERPASS_SUBSURFACE_SCATTERING (9)
#define SHADERPASS_VOLUMETRIC_LIGHTING (10)
#define SHADERPASS_DBUFFER (11)
#endif

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassForward.hlsl


LightLoop(V, posInput, preLightData, bsdfData, bakeLightingData, featureFlags, diffuseLighting, specularLighting);
#ifdef OUTPUT_SPLIT_LIGHTING
if ((_EnableSubsurfaceScattering != 0) && HaveSubsurfaceScattering(bsdfData))
if (_EnableSubsurfaceScattering != 0 && PixelHasSubsurfaceScattering(bsdfData))
{
outColor = float4(specularLighting, 1.0);
outDiffuseLighting = float4(TagLightingForSSS(diffuseLighting), 1.0);

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassLightTransport.hlsl


{
VaryingsToPS output;
UNITY_SETUP_INSTANCE_ID(inputMesh);
UNITY_TRANSFER_INSTANCE_ID(inputMesh, output);
// Output UV coordinate in vertex shader
float2 uv;

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


#if defined(SHADER_API_XBOXONE) || defined(SHADER_API_PSSL)
#else
#define MAX_TESSELLATION_FACTORS 64.0
#endif
struct TessellationFactors
{

23
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/VaryingMesh.hlsl


#ifdef ATTRIBUTES_NEED_COLOR
float4 color : COLOR;
#endif
// UNITY_INSTANCE_ID
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct VaryingsMeshToPS

#ifdef VARYINGS_NEED_COLOR
float4 color;
#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct PackedVaryingsMeshToPS

#if defined(VARYINGS_NEED_CULLFACE) && SHADER_STAGE_FRAGMENT
FRONT_FACE_TYPE cullFace : FRONT_FACE_SEMANTIC;
#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
};
// Functions to pack data to use as few interpolator as possible, the ShaderGraph should generate these functions

UNITY_TRANSFER_INSTANCE_ID(input, output);
output.positionCS = input.positionCS;
#ifdef VARYINGS_NEED_POSITION_WS

FragInputs output;
ZERO_INITIALIZE(FragInputs, output);
UNITY_SETUP_INSTANCE_ID(input);
// Init to some default value to make the computer quiet (else it output "divide by zero" warning even if value is not used).
// TODO: this is a really poor workaround, but the variable is used in a bunch of places
// to compute normals which are then passed on elsewhere to compute other values...

#ifdef VARYINGS_DS_NEED_COLOR
float4 color;
#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct PackedVaryingsMeshToDS

#ifdef VARYINGS_DS_NEED_COLOR
float4 interpolators5 : TEXCOORD2;
#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
};
// Functions to pack data to use as few interpolator as possible, the ShaderGraph should generate these functions

UNITY_TRANSFER_INSTANCE_ID(input, output)
output.interpolators0 = input.positionWS;
output.interpolators1 = input.normalWS;
#ifdef VARYINGS_DS_NEED_TANGENT

VaryingsMeshToDS UnpackVaryingsMeshToDS(PackedVaryingsMeshToDS input)
{
VaryingsMeshToDS output;
UNITY_TRANSFER_INSTANCE_ID(input, output)
output.positionWS = input.interpolators0;
output.normalWS = input.interpolators1;

VaryingsMeshToDS InterpolateWithBaryCoordsMeshToDS(VaryingsMeshToDS input0, VaryingsMeshToDS input1, VaryingsMeshToDS input2, float3 baryCoords)
{
VaryingsMeshToDS ouput;
UNITY_TRANSFER_INSTANCE_ID(input0, output)
TESSELLATION_INTERPOLATE_BARY(positionWS, baryCoords);
TESSELLATION_INTERPOLATE_BARY(normalWS, baryCoords);

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/VertMesh.hlsl


{
VaryingsMeshType output;
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input, output);
float3 positionWS = TransformObjectToWorld(input.positionOS);
#ifdef ATTRIBUTES_NEED_NORMAL
float3 normalWS = TransformObjectToWorldNormal(input.normalOS);

VaryingsMeshToPS VertMeshTesselation(VaryingsMeshToDS input)
{
VaryingsMeshToPS output;
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input, output);
output.positionCS = TransformWorldToHClip(input.positionWS);

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariables.hlsl


int unity_StereoEyeIndex;
#endif
float3 unity_ShadowColor;
uint _TaaFrameIndex; // [0, 7]
float4 unity_ShadowColor;
float2 _TaaFrameRotation; // {x = sin(_TaaFrameIndex * PI/2), y = cos(_TaaFrameIndex * PI/2), z = unused}
uint _TaaFrameIndex; // [0, 7]
uint _Align128; // Pad for 128-bit alignment
// Volumetric lighting. Should be a struct in 'UnityPerFrame'.
// Unfortunately, structures inside constant buffers are not supported by Unity.
float3 _GlobalFog_Scattering;

#else
#include "ShaderVariablesMatrixDefsHDCamera.hlsl"
#endif
#include "CoreRP/ShaderLibrary/UnityInstancing.hlsl"
#include "ShaderVariablesFunctions.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/OpaqueAtmosphericScattering.shader


#pragma vertex Vert
#pragma fragment Frag
#pragma enable_d3d11_debug_symbols
// #pragma enable_d3d11_debug_symbols
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "../ShaderVariables.hlsl"

4
ScriptableRenderPipeline/HDRenderPipeline/package.json


{
"name": "com.unity.render-pipelines.high-definition",
"description": "HD Render Pipeline for Unity.",
"version": "0.1.23",
"version": "0.1.24",
"com.unity.render-pipelines.core": "0.1.23"
"com.unity.render-pipelines.core": "0.1.24"
}
}

18
ScriptableRenderPipeline/LightweightPipeline/LWRP/Data/LightweightPipelineAsset.cs


public static readonly string[] m_SearchPaths = {"Assets", "Packages/com.unity.render-pipelines.lightweight"};
// Default values set when a new LightweightPipeline asset is created
[SerializeField] private float kAssetVersion = 1.0f;
[SerializeField] private bool m_RequireCameraDepthTexture = false;
[SerializeField] private bool m_RequireDepthTexture = false;
[SerializeField] private bool m_RequireSoftParticles = false;
[SerializeField] private bool m_SupportsHDR = false;
[SerializeField] private MSAAQuality m_MSAA = MSAAQuality._4x;
[SerializeField] private float m_RenderScale = 1.0f;

return ShadowSetting != ShadowType.NO_SHADOW;
}
public float GetAssetVersion()
{
return kAssetVersion;
}
public int MaxPixelLights
{
get { return m_MaxPixelLights; }

get { return m_SupportsVertexLight; }
}
public bool RequireCameraDepthTexture
public bool RequireDepthTexture
get { return m_RequireCameraDepthTexture; }
get { return m_RequireDepthTexture; }
}
public bool RequireSoftParticles
{
get { return m_RequireSoftParticles; }
}
public bool SupportsHDR

37
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/LightweightAssetEditor.cs


using UnityEditor;
using UnityEditor.AnimatedValues;
namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{

public static GUIContent enableVertexLightLabel = new GUIContent("Vertex Lighting",
"If enabled shades additional lights exceeding the maximum number of pixel lights per-vertex up to the maximum of 8 lights.");
public static GUIContent requireCameraDepthTexture = new GUIContent("Camera Depth Texture", "If enabled the pipeline will generate camera's depth that can be bound in shaders as _CameraDepthTexture. This is necessary for some effect like Soft Particles.");
public static GUIContent requireDepthTexture = new GUIContent("Depth Texture", "If enabled the pipeline will generate camera's depth that can be bound in shaders as _CameraDepthTexture.");
public static GUIContent requireSoftParticles = new GUIContent("Soft Particles", "If enabled the pipeline will enable SOFT_PARTICLES keyword.");
public static GUIContent shadowType = new GUIContent("Type",
"Global shadow settings. Options are NO_SHADOW, HARD_SHADOWS and SOFT_SHADOWS.");

public static string[] shadowCascadeOptions = {"No Cascades", "Two Cascades", "Four Cascades"};
}
AnimBool m_ShowSoftParticles = new AnimBool();
private int kMaxSupportedPixelLights = 8;
private float kMinRenderScale = 0.1f;
private float kMaxRenderScale = 4.0f;

private SerializedProperty m_RequireCameraDepthTextureProp;
private SerializedProperty m_RequireDepthTextureProp;
private SerializedProperty m_RequireSoftParticlesProp;
private SerializedProperty m_ShadowTypeProp;
private SerializedProperty m_ShadowNearPlaneOffsetProp;
private SerializedProperty m_ShadowDistanceProp;

m_RenderScale = serializedObject.FindProperty("m_RenderScale");
m_MaxPixelLights = serializedObject.FindProperty("m_MaxPixelLights");
m_SupportsVertexLightProp = serializedObject.FindProperty("m_SupportsVertexLight");
m_RequireCameraDepthTextureProp = serializedObject.FindProperty("m_RequireCameraDepthTexture");
m_RequireDepthTextureProp = serializedObject.FindProperty("m_RequireDepthTexture");
m_RequireSoftParticlesProp = serializedObject.FindProperty("m_RequireSoftParticles");
m_ShadowTypeProp = serializedObject.FindProperty("m_ShadowType");
m_ShadowNearPlaneOffsetProp = serializedObject.FindProperty("m_ShadowNearPlaneOffset");
m_ShadowDistanceProp = serializedObject.FindProperty("m_ShadowDistance");

m_ShadowCascade4SplitProp = serializedObject.FindProperty("m_Cascade4Split");
m_HDR = serializedObject.FindProperty("m_SupportsHDR");
m_MSAA = serializedObject.FindProperty("m_MSAA");
m_ShowSoftParticles.valueChanged.AddListener(Repaint);
m_ShowSoftParticles.value = m_RequireSoftParticlesProp.boolValue;
}
void OnDisable()
{
m_ShowSoftParticles.valueChanged.RemoveListener(Repaint);
}
void UpdateAnimationValues()
{
m_ShowSoftParticles.target = m_RequireDepthTextureProp.boolValue;
}
void DrawAnimatedProperty(SerializedProperty prop, GUIContent content, AnimBool animation)
{
using (var group = new EditorGUILayout.FadeGroupScope(animation.faded))
if (group.visible)
EditorGUILayout.PropertyField(prop, content);
}
protected void DoPopup(GUIContent label, SerializedProperty property, string[] options)

{
serializedObject.Update();
UpdateAnimationValues();
EditorGUILayout.Space();
EditorGUILayout.LabelField(Styles.renderingLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel++;

m_MaxPixelLights.intValue = EditorGUILayout.IntSlider(m_MaxPixelLights.intValue, 0, kMaxSupportedPixelLights);
EditorGUILayout.EndHorizontal();
EditorGUILayout.PropertyField(m_SupportsVertexLightProp, Styles.enableVertexLightLabel);
EditorGUILayout.PropertyField(m_RequireCameraDepthTextureProp, Styles.requireCameraDepthTexture);
EditorGUILayout.PropertyField(m_RequireDepthTextureProp, Styles.requireDepthTexture);
DrawAnimatedProperty(m_RequireSoftParticlesProp, Styles.requireSoftParticles, m_ShowSoftParticles);
EditorGUILayout.PropertyField(m_HDR, Styles.hdrContent);
EditorGUILayout.PropertyField(m_MSAA, Styles.msaaContent);

2
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/LightweightShaderIncludePaths.cs


using System.IO;
using System.IO;
using System.Linq;
using UnityEngine;

120
ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs


private RenderTargetIdentifier m_Color;
private bool m_IntermediateTextureArray;
private bool m_RequiredDepth;
private bool m_RequireDepthTexture;
private bool m_RequireCopyColor;
private bool m_DepthRenderBuffer;
private MixedLightingSetup m_MixedLightingSetup;
private const int kDepthStencilBufferBits = 32;

base.Dispose();
Shader.globalRenderPipeline = "";
SupportedRenderingFeatures.active = new SupportedRenderingFeatures();
CoreUtils.Destroy(m_ErrorMaterial);
CoreUtils.Destroy(m_CopyDepthMaterial);
CoreUtils.Destroy(m_BlitMaterial);

ShadowPass(visibleLights, ref context, ref lightData);
FrameRenderingConfiguration frameRenderingConfiguration;
SetupFrameRendering(out frameRenderingConfiguration, stereoEnabled);
SetupFrameRenderingConfiguration(out frameRenderingConfiguration, stereoEnabled);
SetupIntermediateResources(frameRenderingConfiguration, ref context);
// SetupCameraProperties does the following:

// Setup global time properties (_Time, _SinTime, _CosTime)
context.SetupCameraProperties(m_CurrCamera, stereoEnabled);
if (LightweightUtils.HasFlag(frameRenderingConfiguration, FrameRenderingConfiguration.DepthPass))
if (LightweightUtils.HasFlag(frameRenderingConfiguration, FrameRenderingConfiguration.DepthPrePass))
DepthPass(ref context);
ForwardPass(visibleLights, frameRenderingConfiguration, ref context, ref lightData, stereoEnabled);

private void AfterOpaque(ref ScriptableRenderContext context, FrameRenderingConfiguration config)
{
if (!m_RequiredDepth)
if (!m_RequireDepthTexture)
// When only one opaque effect is active we need to blit to a work RT. We blit to copy color.
// TODO: We can check if there are more than one opaque postfx and avoid an extra blit.
bool setRenderTarget = false;
RenderTargetIdentifier depthRT = m_DepthRT;
RenderPostProcess(cmd, m_ColorRT, m_CopyColorRT, true);
m_CurrCameraColorRT = (m_IsOffscreenCamera) ? BuiltinRenderTextureType.CameraTarget : m_ColorRT;
// When only have one effect in the stack we blit to a work RT then blit it back to active color RT.
// This seems like an extra blit but it saves us a depth copy/blit which has some corner cases like msaa depth resolve.
if (m_RequireCopyColor)
{
RenderPostProcess(cmd, m_CurrCameraColorRT, m_CopyColorRT, true);
cmd.Blit(m_CopyColorRT, m_CurrCameraColorRT);
}
else
RenderPostProcess(cmd, m_CurrCameraColorRT, m_CurrCameraColorRT, true);
setRenderTarget = true;
SetRenderTarget(cmd, m_CurrCameraColorRT, m_DepthRT);
RenderTargetIdentifier colorRT = (m_IsOffscreenCamera) ? BuiltinRenderTextureType.CameraTarget : m_ColorRT;
SetRenderTarget(cmd, colorRT, m_CopyDepth);
depthRT = m_CopyDepth;
setRenderTarget = true;
if (setRenderTarget)
SetRenderTarget(cmd, m_CurrCameraColorRT, depthRT);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}

return;
CommandBuffer cmd = CommandBufferPool.Get("After Transparent");
RenderPostProcess(cmd, BuiltinRenderTextureType.CurrentActive, BuiltinRenderTextureType.CameraTarget, false);
RenderPostProcess(cmd, m_CurrCameraColorRT, BuiltinRenderTextureType.CameraTarget, false);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}

}
}
private void SetupFrameRendering(out FrameRenderingConfiguration configuration, bool stereoEnabled)
private void SetupFrameRenderingConfiguration(out FrameRenderingConfiguration configuration, bool stereoEnabled)
{
configuration = (stereoEnabled) ? FrameRenderingConfiguration.Stereo : FrameRenderingConfiguration.None;
if (stereoEnabled && XRSettings.eyeTextureDesc.dimension == TextureDimension.Tex2DArray)

m_Asset.RenderScale < 1.0f || hdrEnabled;
m_ColorFormat = hdrEnabled ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default;
m_RequiredDepth = false;
m_RequireCopyColor = false;
m_DepthRenderBuffer = false;
m_CameraPostProcessLayer = m_CurrCamera.GetComponent<PostProcessLayer>();
bool msaaEnabled = m_CurrCamera.allowMSAA && m_Asset.MSAASampleCount > 1 && (m_CurrCamera.targetTexture == null || m_CurrCamera.targetTexture.antiAliasing > 1);

bool softParticlesEnabled = m_Asset.RequireCameraDepthTexture && !stereoEnabled;
m_RequireDepthTexture = m_Asset.RequireDepthTexture && !stereoEnabled;
m_RequiredDepth = true;
m_RequireDepthTexture = true;
{
// Resolving depth msaa requires texture2DMS. Currently if msaa is enabled we do a depth pre-pass.
if (msaaEnabled)
configuration |= FrameRenderingConfiguration.DepthPass;
}
// In case of soft particles we need depth copy. If depth copy not supported fallback to depth prepass
if (softParticlesEnabled)
{
m_RequiredDepth = true;
intermediateTexture = true;
bool supportsDepthCopy = m_CopyTextureSupport != CopyTextureSupport.None && m_Asset.CopyDepthShader.isSupported;
// currently fallback to depth prepass if msaa is enabled since. We need texture2DMS to support depth resolve.
configuration |= (msaaEnabled || !supportsDepthCopy) ? FrameRenderingConfiguration.DepthPass : FrameRenderingConfiguration.DepthCopy;
if (m_CameraPostProcessLayer.sortedBundles[PostProcessEvent.BeforeTransparent].Count == 1)
m_RequireCopyColor = true;
}
}
if (msaaEnabled)

}
if (m_RequireDepthTexture)
{
// If msaa is enabled we don't use a depth renderbuffer as we might not have support to Texture2DMS to resolve depth.
// Instead we use a depth prepass and whenever depth is needed we use the 1 sample depth from prepass.
if (!msaaEnabled)
{
bool supportsDepthCopy = m_CopyTextureSupport != CopyTextureSupport.None && m_Asset.CopyDepthShader.isSupported;
m_DepthRenderBuffer = true;
intermediateTexture = true;
// If requiring a camera depth texture we need separate depth as it reads/write to depth at same time
// Post process doesn't need the copy
if (!m_Asset.RequireDepthTexture && postProcessEnabled)
configuration |= (supportsDepthCopy) ? FrameRenderingConfiguration.DepthCopy : FrameRenderingConfiguration.DepthPrePass;
}
else
{
configuration |= FrameRenderingConfiguration.DepthPrePass;
}
else
intermediateTexture = true;
if (intermediateTexture)
configuration |= FrameRenderingConfiguration.IntermediateTexture;

int rtWidth = (int)((float)m_CurrCamera.pixelWidth * renderScale);
int rtHeight = (int)((float)m_CurrCamera.pixelHeight * renderScale);
if (m_RequiredDepth)
if (m_RequireDepthTexture)
{
RenderTextureDescriptor depthRTDesc = new RenderTextureDescriptor(rtWidth, rtHeight, RenderTextureFormat.Depth, kDepthStencilBufferBits);
cmd.GetTemporaryRT(CameraRenderTargetID.depth, depthRTDesc, FilterMode.Bilinear);

m_CurrCameraColorRT = m_ColorRT;
}
// When postprocessing is enabled we might have a before transparent effect. In that case we need to
// use the camera render target as input. We blit to an opaque RT and then after before postprocessing is done
// we blit to the final camera RT. If no postprocessing we blit to final camera RT from beginning.
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.BeforeTransparentPostProcess))
// When BeforeTransparent PostFX is enabled and only one effect is in the stack we need to create a temp
// color RT to blit the effect.
if (m_RequireCopyColor)
cmd.GetTemporaryRT(CameraRenderTargetID.copyColor, colorRTDesc, FilterMode.Point);
}

}
Light light = lightData.light;
// TODO: Add support to shadow mask
// TODO: Add support to shadow mask
if (m_MixedLightingSetup == MixedLightingSetup.None && lightData.light.shadows != LightShadows.None)
{
m_MixedLightingSetup = MixedLightingSetup.Subtractive;

CoreUtils.SetKeyword(cmd, "_ADDITIONAL_LIGHTS", lightData.totalAdditionalLightsCount > 0);
CoreUtils.SetKeyword(cmd, "_MIXED_LIGHTING_SUBTRACTIVE", m_MixedLightingSetup == MixedLightingSetup.Subtractive);
CoreUtils.SetKeyword(cmd, "_VERTEX_LIGHTS", vertexLightsCount > 0);
CoreUtils.SetKeyword(cmd, "SOFTPARTICLES_ON", m_Asset.RequireCameraDepthTexture);
CoreUtils.SetKeyword(cmd, "SOFTPARTICLES_ON", m_RequireDepthTexture && m_Asset.RequireSoftParticles);
bool linearFogModeEnabled = false;
bool exponentialFogModeEnabled = false;

if (!m_IsOffscreenCamera)
colorRT = m_CurrCameraColorRT;
if (m_RequiredDepth && !LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.DepthPass))
if (m_RequireDepthTexture)
depthRT = m_DepthRT;
}

var cmd = CommandBufferPool.Get("Blit");
if (m_IntermediateTextureArray)
{
SetRenderTarget(cmd, BuiltinRenderTextureType.CameraTarget);
cmd.Blit(m_CurrCameraColorRT, BuiltinRenderTextureType.CurrentActive);
cmd.Blit(m_CurrCameraColorRT, BuiltinRenderTextureType.CameraTarget);
Material blitMaterial = m_BlitMaterial;
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Stereo))
blitMaterial = null;
Blit(cmd, renderingConfig, BuiltinRenderTextureType.CurrentActive, BuiltinRenderTextureType.CameraTarget, m_BlitMaterial);
Blit(cmd, renderingConfig, m_CurrCameraColorRT, BuiltinRenderTextureType.CameraTarget, blitMaterial);
}
SetRenderTarget(cmd, BuiltinRenderTextureType.CameraTarget);

private void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier colorRT, RenderTargetIdentifier depthRT, ClearFlag clearFlag = ClearFlag.None)
{
if (depthRT == BuiltinRenderTextureType.None)
if (depthRT == BuiltinRenderTextureType.None || !m_DepthRenderBuffer)
{
SetRenderTarget(cmd, colorRT, clearFlag);
return;

if (opaqueOnly)
{
m_CameraPostProcessLayer.RenderOpaqueOnly(m_PostProcessRenderContext);
cmd.Blit(m_CopyColorRT, m_ColorRT);
}
else
m_CameraPostProcessLayer.Render(m_PostProcessRenderContext);

2
ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipelineUtils.cs


Msaa = (1 << 1),
BeforeTransparentPostProcess = (1 << 2),
PostProcess = (1 << 3),
DepthPass = (1 << 4),
DepthPrePass = (1 << 4),
DepthCopy = (1 << 5),
DefaultViewport = (1 << 6),
IntermediateTexture = (1 << 7),

2
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightBlit.shader


#pragma vertex Vertex
#pragma fragment Fragment
#include "LightweightShaderLibrary/Core.hlsl"
#include "LWRP/ShaderLibrary/Core.hlsl"
struct VertexInput
{

2
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightCopyDepth.shader


#pragma vertex vert
#pragma fragment frag
#include "LightweightShaderLibrary/Core.hlsl"
#include "LWRP/ShaderLibrary/Core.hlsl"
TEXTURE2D(_CameraDepthTexture);
SAMPLER(sampler_CameraDepthTexture);

18
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandard.shader


SubShader
{
// Lightweight Pipeline tag is required. If Lightweight pipeline is not set in the graphics settings
// this Subshader will fail. One can add a subshader below or fallback to Standard built-in to make this
// material work with both Lightweight Pipeline and Builtin Unity Pipeline
// Base forward pass (directional light, emission, lightmaps, ...)
// Forward pass. Shades all light in a single pass. GI + emission + Fog
// Lightmode matches the ShaderPassName set in LightweightPipeline.cs. SRPDefaultUnlit and passes with
// no LightMode tag are also rendered by Lightweight Pipeline
Tags{"LightMode" = "LightweightForward"}
Blend[_SrcBlend][_DstBlend]

// Required to compile gles 2.0 with standard srp library
// Required to compile gles 2.0 with standard SRP library
// All shaders must be compiled with HLSLcc and currently only gles is not using HLSLcc by default
#pragma prefer_hlslcc gles
#pragma target 3.0

#pragma vertex LitPassVertex
#pragma fragment LitPassFragment
#include "LightweightPassLit.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
ENDHLSL
}

#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "LightweightPassShadow.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassShadow.hlsl"
ENDHLSL
}

#pragma vertex vert
#pragma fragment frag
#include "LightweightShaderLibrary/Core.hlsl"
#include "LWRP/ShaderLibrary/Core.hlsl"
float4 vert(float4 pos : POSITION) : SV_POSITION
{

#pragma shader_feature _SPECGLOSSMAP
#include "LightweightPassMeta.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassMeta.hlsl"
ENDHLSL
}

6
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardParticles.shader


#pragma shader_feature _FADING_ON
#pragma shader_feature _REQUIRE_UV2
#include "LightweightShaderLibrary/Particles.hlsl"
#include "LightweightShaderLibrary/Lighting.hlsl"
#include "LWRP/ShaderLibrary/Particles.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"
VertexOutputLit ParticlesLitVertex(appdata_particles v)
{

InitializeSurfaceData(IN, surfaceData);
float3 positionWS = IN.posWS.xyz;
half3 viewDirWS = SafeNormalize(_WorldSpaceCameraPos - positionWS);
half3 viewDirWS = SafeNormalize(GetCameraPositionWS() - positionWS);
half fogFactor = IN.posWS.w;
#if _NORMALMAP

4
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardParticlesUnlit.shader


#pragma vertex vertParticleUnlit
#pragma fragment fragParticleUnlit
#include "LightweightShaderLibrary/Particles.hlsl"
#include "LightweightShaderLibrary/Core.hlsl"
#include "LWRP/ShaderLibrary/Particles.hlsl"
#include "LWRP/ShaderLibrary/Core.hlsl"
VertexOutputLit vertParticleUnlit(appdata_particles v)
{

8
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardSimpleLighting.shader


#pragma vertex LitPassVertex
#pragma fragment LitPassFragmentSimple
#include "LightweightPassLit.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
ENDHLSL
}

#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "LightweightPassShadow.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassShadow.hlsl"
ENDHLSL
}

#pragma vertex vert
#pragma fragment frag
#include "LightweightShaderLibrary/Core.hlsl"
#include "LWRP/ShaderLibrary/Core.hlsl"
float4 vert(float4 pos : POSITION) : SV_POSITION
{

#pragma shader_feature _EMISSION
#pragma shader_feature _SPECGLOSSMAP
#include "LightweightPassMeta.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassMeta.hlsl"
ENDHLSL
}
}

6
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardTerrain.shader


#define LIGHTMAP_ON
#endif
#include "LightweightShaderLibrary/Lighting.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"
CBUFFER_START(_Terrain)
half _Metallic0;

indirectDiffuse = SampleLightmap(IN.uvControlAndLM.zw, normalWS);
#endif
half3 viewDirectionWS = SafeNormalize(_WorldSpaceCameraPos - IN.positionWS);
half3 viewDirectionWS = SafeNormalize(GetCameraPositionWS() - IN.positionWS);
half fogFactor = IN.fogFactorAndVertexLight.x;
half4 color = LightweightFragmentPBR(IN.positionWS, normalWS, viewDirectionWS, indirectDiffuse,
IN.fogFactorAndVertexLight.yzw, albedo, metallic, specular, smoothness, /* occlusion */ 1.0, /* emission */ half3(0, 0, 0), alpha);

#pragma vertex vert
#pragma fragment frag
#include "LightweightShaderLibrary/Core.hlsl"
#include "LWRP/ShaderLibrary/Core.hlsl"
float4 vert(float4 pos : POSITION) : SV_POSITION
{

4
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightUnlit.shader


#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON
// Lighting include is needed because of GI
#include "LightweightShaderLibrary/Lighting.hlsl"
#include "LightweightShaderLibrary/InputSurface.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"
#include "LWRP/ShaderLibrary/InputSurface.hlsl"
struct VertexInput
{

4
ScriptableRenderPipeline/LightweightPipeline/package.json


{
"name": "com.unity.render-pipelines.lightweight",
"description": "Lightweight Render Pipeline for Unity.",
"version": "0.1.23",
"version": "0.1.24",
"com.unity.render-pipelines.core": "0.1.23"
"com.unity.render-pipelines.core": "0.1.24"
}
}

2
ScriptableRenderPipeline/master-package.json


{
"version": "0.1.23",
"version": "0.1.24",
"unity": "2018.1",
"dependencies": {
"com.unity.postprocessing": "0.1.7"

4
TestbedPipelines/OnTileDeferredPipeline/Shaders/LightingTemplate.hlsl


#define BOX_LIGHT (2)
#define DIRECTIONAL_LIGHT (3)
#include "OnTileCommon.hlsl"
#if defined(SHADER_API_D3D11)
# include "CoreRP/ShaderLibrary/API/D3D11.hlsl"
#elif defined(SHADER_API_PSSL)

# error unsupported shader api
#endif
#include "CoreRP/ShaderLibrary/API/Validate.hlsl"
#include "../../Fptl/Shadow.hlsl"
#include "Shadow.hlsl"
UNITY_DECLARE_DEPTH_TEXTURE(_CameraGBufferZ);

9
TestbedPipelines/OnTileDeferredPipeline/Shaders/ShadowContext.hlsl


// This can be custom for each project and needs to be in sync with the ShadowMgr
#ifndef ONTILE_SHADOW_CONTEXT_HLSL
#define ONTILE_SHADOW_CONTEXT_HLSL
#define SHADOWCONTEXT_MAX_TEX2DARRAY 1
#define SHADOWCONTEXT_MAX_TEXCUBEARRAY 0

SHADOWCONTEXT_DECLARE( SHADOWCONTEXT_MAX_TEX2DARRAY, SHADOWCONTEXT_MAX_TEXCUBEARRAY, SHADOWCONTEXT_MAX_COMPSAMPLER, SHADOWCONTEXT_MAX_SAMPLER );
#include "CoreRP/ShaderLibrary/Shadow/Shadow.hlsl"
SAMPLER2D_SHADOW(sampler_ShadowmapExp_PCF);
SAMPLER_CMP(sampler_ShadowmapExp_PCF);
StructuredBuffer<ShadowData> _ShadowDatasExp;
StructuredBuffer<int4> _ShadowPayloads;

return sc;
}
#endif // ONTILE_SHADOW_CONTEXT_HLSL

29
TestbedPipelines/OnTileDeferredPipeline/Shaders/Standard.shader


{
_Color("Color", Color) = (1,1,1,1)
_MainTex("Albedo", 2D) = "white" {}
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5

_EmissionColor("Color", Color) = (0,0,0)
_EmissionMap("Emission", 2D) = "white" {}
_DetailMask("Detail Mask", 2D) = "white" {}
_DetailAlbedoMap("Detail Albedo x2", 2D) = "grey" {}

}
CGINCLUDE
#include "OnTileCommon.hlsl"
#define UNITY_SETUP_BRDF_INPUT MetallicSetup
ENDCG

LOD 300
// ------------------------------------------------------------------
// Forward pass
Pass

// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD_BASE"
Name "FORWARD_BASE"
Tags { "LightMode" = "ForwardBase" }
Blend [_SrcBlend] [_DstBlend]

// This pass it not used during regular rendering.
Pass
{
Name "META"
Name "META"
Tags { "LightMode"="Meta" }
Cull Off

// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Blend [_SrcBlend] [_DstBlend]

#pragma target 2.0
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICGLOSSMAP
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICGLOSSMAP
#pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature _ _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature _ _GLOSSYREFLECTIONS_OFF

Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest LEqual
CGPROGRAM
#pragma target 2.0

#pragma shader_feature ___ _DETAIL_MULX2
// SM2.0: NOT SUPPORTED shader_feature _PARALLAXMAP
#pragma skip_variants SHADOWS_SOFT
#pragma vertex vertAdd
#pragma fragment fragAdd
#include "UnityStandardCoreForward.cginc"

Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
CGPROGRAM

// This pass it not used during regular rendering.
Pass
{
Name "META"
Name "META"
Tags { "LightMode"="Meta" }
Cull Off

29
TestbedPipelines/OnTileDeferredPipeline/Shaders/StandardSpecular.shader


{
_Color("Color", Color) = (1,1,1,1)
_MainTex("Albedo", 2D) = "white" {}
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5

_EmissionColor("Color", Color) = (0,0,0)
_EmissionMap("Emission", 2D) = "white" {}
_DetailMask("Detail Mask", 2D) = "white" {}
_DetailAlbedoMap("Detail Albedo x2", 2D) = "grey" {}

}
CGINCLUDE
#include "OnTileCommon.hlsl"
#define UNITY_SETUP_BRDF_INPUT SpecularSetup
ENDCG

LOD 300
Pass
{
Name "FORWARD"

// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Blend [_SrcBlend] [_DstBlend]

// This pass it not used during regular rendering.
Pass
{
Name "META"
Name "META"
Tags { "LightMode"="Meta" }
Cull Off

// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Name "FORWARD"
Name "FORWARD"
Tags { "LightMode" = "ForwardBase" }
Blend [_SrcBlend] [_DstBlend]

#pragma target 2.0
#pragma shader_feature _EMISSION
#pragma shader_feature _EMISSION
#pragma shader_feature _SPECGLOSSMAP
#pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature _ _SPECULARHIGHLIGHTS_OFF

#pragma skip_variants SHADOWS_SOFT DYNAMICLIGHTMAP_ON DIRLIGHTMAP_COMBINED
#pragma multi_compile_fwdbase
#pragma multi_compile_fog

Fog { Color (0,0,0,0) } // in additive pass fog should be black
ZWrite Off
ZTest LEqual
CGPROGRAM
#pragma target 2.0

#pragma shader_feature ___ _DETAIL_MULX2
// SM2.0: NOT SUPPORTED shader_feature _PARALLAXMAP
#pragma skip_variants SHADOWS_SOFT
#pragma vertex vertAdd
#pragma fragment fragAdd
#include "UnityStandardCoreForward.cginc"

Pass {
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
ZWrite On ZTest LEqual
CGPROGRAM

// This pass it not used during regular rendering.
Pass
{
Name "META"
Name "META"
Tags { "LightMode"="Meta" }
Cull Off

3
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/3DObjects/CornelBox/Cornell Box.fbx.meta


2186277476908879420: ImportLogs
2186277476908879422: ImportLogs
2186277476908879424: ImportLogs
2186277476908879426: ImportLogs
2186277476908879428: ImportLogs
2186277476908879430: ImportLogs
externalObjects:
- first:
type: UnityEngine:Material

3
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/3DObjects/Sphere/Sphere.fbx.meta


2186277476908879422: ImportLogs
2186277476908879424: ImportLogs
2186277476908879426: ImportLogs
2186277476908879428: ImportLogs
2186277476908879430: ImportLogs
2186277476908879432: ImportLogs
externalObjects: {}
materials:
importMaterials: 0

3
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Materials/HDRP_Default_Material.mat


- _SubsurfaceRadius: 1
- _SurfaceType: 0
- _TexWorldScale: 1
- _TexWorldScaleEmissive: 1
- _Thickness: 1
- _ThicknessMultiplier: 1
- _TransparentBackfaceEnable: 0

- _UVDetail: 0
- _UVEmissive: 0
- _ZTestMode: 8
- _ZWrite: 1
m_Colors:

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

3
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1210_Lit_BentNormal/BentNormal_Tangent.mat


- _SubsurfaceRadius: 1
- _SurfaceType: 0
- _TexWorldScale: 1
- _TexWorldScaleEmissive: 1
- _Thickness: 1
- _ThicknessMultiplier: 1
- _TransparentBackfaceEnable: 0

- _UVDetail: 0
- _UVEmissive: 0
- _ZTestMode: 4
- _ZWrite: 1
m_Colors:

- _TransmittanceColor: {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}
- _UVMappingMaskEmissive: {r: 1, g: 0, b: 0, a: 0}

3
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1210_Lit_BentNormal/Green_Emissive.mat


- _SubsurfaceRadius: 1
- _SurfaceType: 0
- _TexWorldScale: 1
- _TexWorldScaleEmissive: 1
- _Thickness: 1
- _ThicknessMultiplier: 1
- _TransparentBackfaceEnable: 0

- _UVDetail: 0
- _UVEmissive: 0
- _ZTestMode: 4
- _ZWrite: 1
m_Colors:

- _TransmittanceColor: {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}
- _UVMappingMaskEmissive: {r: 1, g: 0, b: 0, a: 0}

3
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1210_Lit_BentNormal/Red_Emissive.mat


- _SubsurfaceRadius: 1
- _SurfaceType: 0
- _TexWorldScale: 1
- _TexWorldScaleEmissive: 1
- _Thickness: 1
- _ThicknessMultiplier: 1
- _TransparentBackfaceEnable: 0

- _UVDetail: 0
- _UVEmissive: 0
- _ZTestMode: 4
- _ZWrite: 1
m_Colors:

- _TransmittanceColor: {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}
- _UVMappingMaskEmissive: {r: 1, g: 0, b: 0, a: 0}

192
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/3xxx_DebugView/3002_ObjectMotionVector.unity


m_GameObject: {fileID: 12769659}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c413a5df32c4fec4eb320c4465678193, type: 3}
m_Script: {fileID: 11500000, guid: 9311bd511d7afc04b95779ad6b218383, type: 3}
localSpace: 0
fps: 60
--- !u!23 &12769661
MeshRenderer:
m_ObjectHideFlags: 0

m_Father: {fileID: 0}
m_RootOrder: 4
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &29872219
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 29872223}
- component: {fileID: 29872222}
- component: {fileID: 29872221}
- component: {fileID: 29872220}
m_Layer: 0
m_Name: Rotate
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &29872220
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 29872219}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 14d7896b83927c247821fa13f452106f, type: 3}
m_Name:
m_EditorClassIdentifier:
localSpace: 0
angles: {x: 0, y: 0, z: 90}
frequency: 5
fps: 60
--- !u!23 &29872221
MeshRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 29872219}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RenderingLayerMask: 4294967295
m_Materials:
- {fileID: 2100000, guid: 051804eacb0bc2144a9e96128a428a15, 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: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 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!33 &29872222
MeshFilter:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 29872219}
m_Mesh: {fileID: 4300000, guid: b32e17769a31e9c4c8b3176dcb04dea9, type: 3}
--- !u!4 &29872223
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 29872219}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: -2.5, y: -3, z: 0}
m_LocalScale: {x: 2, y: 1.9999996, z: 1.9999996}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 7
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &176131434
GameObject:
m_ObjectHideFlags: 0

m_GameObject: {fileID: 176131434}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c413a5df32c4fec4eb320c4465678193, type: 3}
m_Script: {fileID: 11500000, guid: 9311bd511d7afc04b95779ad6b218383, type: 3}
localSpace: 0
fps: 60
--- !u!23 &176131436
MeshRenderer:
m_ObjectHideFlags: 0

m_Father: {fileID: 0}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &764440502
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 764440506}
- component: {fileID: 764440505}
- component: {fileID: 764440504}
- component: {fileID: 764440503}
m_Layer: 0
m_Name: Scale
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &764440503
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 764440502}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 382c9a87993196d4596a688b68b60221, type: 3}
m_Name:
m_EditorClassIdentifier:
min: {x: 1.5, y: 1.5, z: 1.5}
max: {x: 3, y: 3, z: 3}
frequency: 5
fps: 60
--- !u!23 &764440504
MeshRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 764440502}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RenderingLayerMask: 4294967295
m_Materials:
- {fileID: 2100000, guid: 051804eacb0bc2144a9e96128a428a15, 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: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 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!33 &764440505
MeshFilter:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 764440502}
m_Mesh: {fileID: 4300000, guid: b32e17769a31e9c4c8b3176dcb04dea9, type: 3}
--- !u!4 &764440506
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 764440502}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: -7, y: -3, z: 0}
m_LocalScale: {x: 2, y: 1.9999996, z: 1.9999996}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 6
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1243403287
GameObject:
m_ObjectHideFlags: 0

m_GameObject: {fileID: 1243403287}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c413a5df32c4fec4eb320c4465678193, type: 3}
m_Script: {fileID: 11500000, guid: 9311bd511d7afc04b95779ad6b218383, type: 3}
localSpace: 0
fps: 60
--- !u!23 &1243403289
MeshRenderer:
m_ObjectHideFlags: 0

m_Script: {fileID: 11500000, guid: a9ad82d3a5300af40a7a6a9927907436, type: 3}
m_Name:
m_EditorClassIdentifier:
settingType: 1
gBuffer: 0
fullScreenDebugMode: 9
--- !u!4 &1962206527
Transform:

- target: {fileID: 114733060649624252, guid: c07ace9ab142ca9469fa377877c2f1e7,
type: 2}
propertyPath: waitForFrames
value: 15
value: 29
objectReference: {fileID: 0}
- target: {fileID: 114733060649624252, guid: c07ace9ab142ca9469fa377877c2f1e7,
type: 2}

9
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/EditorPlayModeTests.asset


m_Name: EditorPlayModeTests
m_EditorClassIdentifier:
scenesPath:
- Assets/Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/3xxx_DebugView/3002_ObjectMotionVector.unity
- 3xxx_DebugView/3002_ObjectMotionVector.unity
- 3xxx_DebugView/3003_CameraMotionVector_TranslateX.unity
- 3xxx_DebugView/3004_CameraMotionVector_TranslateY.unity
- 3xxx_DebugView/3005_CameraMotionVector_TranslateZ.unity
- 3xxx_DebugView/3006_CameraMotionVector_RotateX.unity
- 3xxx_DebugView/3007_CameraMotionVector_RotateY.unity
- 3xxx_DebugView/3008_CameraMotionVector_RotateZ.unity
- 3xxx_DebugView/3009_CameraMotionVector_FOV.unity

6
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Assets/CommonAssets/Cornell Box.fbx.meta


fileFormatVersion: 2
guid: b56f0b54c8a1042f3ae9a8904a576f5d
timeCreated: 1493308431
licenseType: Pro
ModelImporter:
serializedVersion: 22
fileIDToRecycleName:

4300000: Cornell Box
7400000: Take 001
9500000: //RootNode
2186277476908879412: ImportLogs
2186277476908879414: ImportLogs
2186277476908879416: ImportLogs
externalObjects:
- first:
type: UnityEngine:Material

animationRetargetingWarnings:
animationDoRetargetingWarnings: 0
importAnimatedCustomProperties: 0
importConstraints: 0
animationCompression: 1
animationRotationError: 0.5
animationPositionError: 0.5

5
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset


m_Script: {fileID: 11500000, guid: bf2edee5c58d82540a51f03df9d42094, type: 3}
m_Name: LightweightPipelineAsset
m_EditorClassIdentifier:
kAssetVersion: 1
m_RequireCameraDepthTexture: 0
m_RequireDepthTexture: 0
m_RequireSoftParticles: 0
m_SupportsHDR: 0
m_MSAA: 4
m_RenderScale: 1
m_ShadowType: 1

4
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/040_UpgradeScene/Models/Environment/Floor.fbx.meta


4300026: SmallPlank
7400000: Take 001
9500000: //RootNode
2186277476908879412: ImportLogs
2186277476908879414: ImportLogs
2186277476908879416: ImportLogs
externalObjects:
- first:
type: UnityEngine:Material

animationRetargetingWarnings:
animationDoRetargetingWarnings: 0
importAnimatedCustomProperties: 0
importConstraints: 0
animationCompression: 1
animationRotationError: 0.5
animationPositionError: 0.5

11
Tests/Scripts/Editor.meta


fileFormatVersion: 2
guid: 0f6887a1ff514ed690ada3786867d216
timeCreated: 1512986333
fileFormatVersion: 2
guid: 2ea8802fb7f2fa641a567a661fb6a58e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

14
Tests/Scripts/Editor/GraphicTests/Framework/EditorPlayModeTests_Editor.cs


using UnityEngine;
using UnityEditor;
using System;
using System.IO;
[DisallowMultipleComponent]
[CustomEditor(typeof(EditorPlayModeTests))]
class EditorPlayModeTests_Editor : Editor
{

if (newScene != null)
{
string newPath = AssetDatabase.GetAssetPath(newScene);
Debug.Log("New Path : " + newPath);
string listPath = AssetDatabase.GetAssetPath(target);
listPath = listPath.Remove(listPath.Length - 25, 25);
//Debug.Log("List path: " + listPath);
// Get scene path relative to the list file
newPath = newPath.Replace(listPath, "");
//Debug.Log("New Path : " + newPath);
if (newPath.EndsWith("unity"))
{
Debug.Log("Add the scene to the list");

11
Tests/Scripts/Editor/GraphicTests/Framework/TestFramework.cs


yield return null;
}
// Handle play mode and things to do before
if (testSetup.testInPlayMode)
{
//if (!testSetup.invokeAtStart) testSetup.thingToDoBeforeTest.Invoke();
//EditorApplication.isPlaying = true;
}
else
{
testSetup.thingToDoBeforeTest.Invoke();
}
testSetup.thingToDoBeforeTest.Invoke();
// Render the camera
Texture2D captured = TestFrameworkTools.RenderSetupToTexture(testSetup);

14
Tests/Scripts/GraphicTests/Framework/SetupSceneForRenderPipelineTest.cs


public UnityEvent thingToDoBeforeTest;
[Header("Run Play Mode for test")]
public bool testInPlayMode = false;
public bool invokeAtStart = true;
public IEnumerator Start()
{
// Wait for other things to happend, in particular allow for the render pipeline to reset
yield return new WaitForEndOfFrame();
if (invokeAtStart) thingToDoBeforeTest.Invoke();
if (!testInPlayMode) _readyForCapture = true;
Time.captureFramerate = forcedFrameRate;
}
public void Update()
{

34
Tests/Scripts/GraphicTests/Framework/TestFrameworkPlayMode.cs


using System.IO;
using System.Linq;
public class GraphicTestsPlayMode : IPrebuildSetup, IPostBuildCleanup
public class GraphicTestsPlayMode : IPrebuildSetup
{
public virtual string pipelineID { get { return "NoPipeline"; } }

Debug.Log("Setup for the test");
#if UNITY_EDITOR
oldScenes = UnityEditor.EditorBuildSettings.scenes;

#endif
}
[OneTimeTearDown]
//UnityEditor.EditorBuildSettings.scenes = oldScenes;
UnityEditor.EditorBuildSettings.scenes = oldScenes;
//public IEnumerator TestScene([ValueSource(typeof(TestFrameworkTools.CollectScenesPlayMode), "HDRP")]TestFrameworkTools.TestInfo testInfo)
string prjRelativeGraphsPath;
string filePath;
var prjRelativeGraphsPath = TestFrameworkTools.s_Path.Aggregate(TestFrameworkTools.s_RootPath, Path.Combine);
var filePath = Path.Combine(prjRelativeGraphsPath, testInfo.relativePath);
prjRelativeGraphsPath = TestFrameworkTools.s_Path.Aggregate(TestFrameworkTools.s_RootPath, Path.Combine);
filePath = Path.Combine(prjRelativeGraphsPath, testInfo.relativePath);
UnityEngine.SceneManagement.SceneManager.LoadScene( testInfo.relativePath , UnityEngine.SceneManagement.LoadSceneMode.Single);
UnityEngine.SceneManagement.SceneManager.LoadScene( testInfo.sceneListIndex , UnityEngine.SceneManagement.LoadSceneMode.Single);
//Assert.IsNotNull(testSetup, "No SetupSceneForRenderPipelineTest in scene " + testInfo.name);
//Assert.IsNotNull(testSetup.cameraToUse, "No configured camera in <SetupSceneForRenderPipelineTest>");
Time.captureFramerate = testSetup.forcedFrameRate;
// Initialize
testSetup.Setup();

var oldTarget = testSetup.cameraToUse.targetTexture;
testSetup.cameraToUse.targetTexture = tempTarget;
while (!testSetup.IsTestFinished) yield return null;
// Pause
float prevTimeScale = Time.timeScale;
Time.timeScale = 0f;
for (int f = 0; f < testSetup.waitForFrames; ++f) yield return null;
// render the scene

var captured = new Texture2D(tempTarget.width, tempTarget.height, TextureFormat.RGB24, false);
captured.ReadPixels(new Rect(0, 0, testSetup.width, testSetup.height), 0, 0);
RenderTexture.active = oldActive;
//Unpause
Time.timeScale = prevTimeScale;
// Load the template
Texture2D fromDisk = new Texture2D(2, 2);

35
Tests/Scripts/GraphicTests/Framework/TestFrameworkTools.cs


public static Dictionary<string, string> renderPipelineScenesFolder = new Dictionary<string, string>()
{
{ "HDRP", "HDRenderPipeline/Scenes" },
{ "LWRP", "LightweightPipeline" }
{ "LWRP", "LightweightPipeline/Scenes" }
};
// info that gets generated for use

public string relativePath;
public string templatePath;
public int frameWait;
public int sceneListIndex;
public override string ToString()
{

List<string> allPaths_List = new List<string>(allPaths);
allPaths_List.Sort();
// Get the play mode scenes
List<string> playModeScenes = new List<string>();
foreach( TestInfo ti in CollectScenesPlayMode.GetScenesForPipeline( _pipelinePath ) )
{
playModeScenes.Add(ti.templatePath);
}
// construct all the needed test infos
for (int i = 0; i < allPaths_List.Count; ++i)
{

var split = s_Path.Aggregate("", Path.Combine);
split = string.Format("{0}{1}", split, Path.DirectorySeparatorChar);
var splitPaths = p.FullName.Split(new[] { split }, StringSplitOptions.RemoveEmptyEntries);
// Filter out play mode tests from the list
if (playModeScenes.Contains(splitPaths.Last()))
continue;
TestInfo testInfo = new TestInfo()
{

public static IEnumerable GetScenesForPipeline(string _pipelinePath, bool fixtureParam = false)
{
#if UNITY_EDITOR
var absoluteScenesPath = s_Path.Aggregate("Assets", Path.Combine);
string absoluteScenesPath = s_Path.Aggregate(s_RootPath, Path.Combine);
string assetScenesPath = absoluteScenesPath.Replace(Application.dataPath, "");
assetScenesPath = Path.Combine("Assets", assetScenesPath.Remove(0, 1));
var filesPath = Path.Combine(absoluteScenesPath, _pipelinePath);
string filesPath = Path.Combine(assetScenesPath, _pipelinePath);
string listFilePath = Path.Combine(filesPath, "EditorPlayModeTests.asset");

AssetDatabase.CreateAsset(ScriptableObject.CreateInstance<EditorPlayModeTests>(), listFilePath);
AssetDatabase.Refresh();
foreach (string path in listFile.scenesPath)
for ( int i=0 ; i<listFile.scenesPath.Length ; ++i)
var p = new FileInfo(path);
string path = listFile.scenesPath[i];
var p = new FileInfo( Path.Combine(filesPath, path ) );
var split = s_Path.Aggregate("", Path.Combine);
split = string.Format("{0}{1}", split, Path.DirectorySeparatorChar);
var splitPaths = p.FullName.Split(new[] { split }, StringSplitOptions.RemoveEmptyEntries);

name = p.Name,
relativePath = path,
relativePath = p.ToString(),
frameWait = 100
frameWait = 100,
sceneListIndex = i
};
if (fixtureParam)

24
Tests/Scripts/GraphicTests/HDRenderPipeline/DebugViewController.cs


public class DebugViewController : MonoBehaviour
{
[SerializeField] FullScreenDebugMode fullScreenDebugMode = FullScreenDebugMode.None;
public enum SettingType { Material, Rendering }
public SettingType settingType = SettingType.Material;
MaterialDebugSettings materialDebugSettings = new MaterialDebugSettings();
[Header("Material")]
[SerializeField] int gBuffer = 0;
//DebugItemHandlerIntEnum(MaterialDebugSettings.debugViewMaterialGBufferStrings, MaterialDebugSettings.debugViewMaterialGBufferValues)
[Header("Rendering")]
[SerializeField] int fullScreenDebugMode = 0;
hdPipeline.debugDisplaySettings.fullScreenDebugMode = fullScreenDebugMode;
switch ( settingType )
{
case SettingType.Material:
hdPipeline.debugDisplaySettings.SetDebugViewGBuffer(gBuffer);
hdPipeline.debugDisplaySettings.fullScreenDebugMode = FullScreenDebugMode.None;
break;
case SettingType.Rendering:
hdPipeline.debugDisplaySettings.SetDebugViewGBuffer(0);
hdPipeline.debugDisplaySettings.fullScreenDebugMode = (FullScreenDebugMode) fullScreenDebugMode;
break;
}
}
}

9
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassLit.hlsl


#ifndef LIGHTWEIGHT_PASS_LIT_INCLUDED
#define LIGHTWEIGHT_PASS_LIT_INCLUDED
#include "LightweightShaderLibrary/InputSurface.hlsl"
#include "LightweightShaderLibrary/Lighting.hlsl"
#include "LWRP/ShaderLibrary/InputSurface.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"
struct LightweightVertexInput
{

o.posWS = TransformObjectToWorld(v.vertex.xyz);
o.clipPos = TransformWorldToHClip(o.posWS);
o.viewDir = SafeNormalize(_WorldSpaceCameraPos - o.posWS);
o.viewDir = SafeNormalize(GetCameraPositionWS() - o.posWS);
// initializes o.normal and if _NORMALMAP also o.tangent and o.binormal
OUTPUT_NORMAL(v, o);

half3 indirectDiffuse = SampleGI(IN.lightmapUVOrVertexSH, normalWS);
float fogFactor = IN.fogFactorAndVertexLight.x;
// viewDirection should be normalized here, but we avoid doing it as it's close enough and we save some ALU.
// Computes fog factor per-vertex
ApplyFog(color.rgb, fogFactor);
return color;
}

4
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMeta.hlsl


#ifndef LIGHTWEIGHT_PASS_META_INCLUDED
#define LIGHTWEIGHT_PASS_META_INCLUDED
#include "LightweightShaderLibrary/InputSurface.hlsl"
#include "LightweightShaderLibrary/Lighting.hlsl"
#include "LWRP/ShaderLibrary/InputSurface.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"
CBUFFER_START(UnityMetaPass)
// x = use uv1 as raster position

2
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassShadow.hlsl


#ifndef LIGHTWEIGHT_PASS_SHADOW_INCLUDED
#define LIGHTWEIGHT_PASS_SHADOW_INCLUDED
#include "LightweightShaderLibrary/Core.hlsl"
#include "LWRP/ShaderLibrary/Core.hlsl"
// x: global clip space bias, y: normal world space bias
float4 _ShadowBias;

5
Tests/Scripts/GraphicTests/HDRenderPipeline/SinMove.cs


public class SinMove : MonoBehaviour
{
[SerializeField] bool localSpace = false;
[SerializeField] float fps = 60;
Vector3 startPosition = Vector3.zero;

// Update is called once per frame
void Update ()
{
transform.position = startPosition + Mathf.Sin(Mathf.PI * Time.time * frequency) * vector;
transform.position = startPosition + Mathf.Sin(Mathf.PI * frequency * Time.frameCount / fps) * (localSpace?transform.TransformDirection(vector):vector);
}
}

2
Tests/Scripts/GraphicTests/HDRenderPipeline/SinMove.cs.meta


fileFormatVersion: 2
guid: c413a5df32c4fec4eb320c4465678193
guid: 9311bd511d7afc04b95779ad6b218383
MonoImporter:
externalObjects: {}
serializedVersion: 2

43
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/CoreFunctions.hlsl


#ifndef UNITY_SHADER_VARIABLES_FUNCTIONS_INCLUDED
#define UNITY_SHADER_VARIABLES_FUNCTIONS_INCLUDED
float3 GetCameraPositionWS()
{
return _WorldSpaceCameraPos;
}
float4x4 GetWorldToViewMatrix()
{
return UNITY_MATRIX_V;

return UNITY_MATRIX_VP;
}
float GetOddNegativeScale()
real GetOddNegativeScale()
{
return unity_WorldTransformParams.w;
}

return mul(GetWorldToViewMatrix(), float4(positionWS, 1.0)).xyz;
return mul(GetWorldToViewMatrix(), real4(positionWS, 1.0)).xyz;
return mul(GetObjectToWorldMatrix(), float4(positionOS, 1.0)).xyz;
return mul(GetObjectToWorldMatrix(), real4(positionOS, 1.0)).xyz;
}
float3 TransformWorldToObject(float3 positionWS)

float3 TransformObjectToWorldDir(float3 dirOS)
real3 TransformObjectToWorldDir(real3 dirOS)
return normalize(mul((float3x3)GetObjectToWorldMatrix(), dirOS));
return normalize(mul((real3x3)GetObjectToWorldMatrix(), dirOS));
float3 TransformWorldToObjectDir(float3 dirWS)
real3 TransformWorldToObjectDir(real3 dirWS)
return normalize(mul((float3x3)GetWorldToObjectMatrix(), dirWS));
return normalize(mul((real3x3)GetWorldToObjectMatrix(), dirWS));
float3 TransformObjectToWorldNormal(float3 normalOS)
real3 TransformObjectToWorldNormal(real3 normalOS)
{
#ifdef UNITY_ASSUME_UNIFORM_SCALING
return UnityObjectToWorldDir(normalOS);

return normalize(mul(normalOS, (float3x3)GetWorldToObjectMatrix()));
return normalize(mul(normalOS, (real3x3)GetWorldToObjectMatrix()));
#endif
}

return mul(GetWorldToHClipMatrix(), float4(positionWS, 1.0));
}
float3x3 CreateWorldToTangent(float3 normal, float3 tangent, float flipSign)
real3x3 CreateWorldToTangent(real3 normal, real3 tangent, real flipSign)
float sgn = flipSign * GetOddNegativeScale();
float3 bitangent = cross(normal, tangent) * sgn;
real sgn = flipSign * GetOddNegativeScale();
real3 bitangent = cross(normal, tangent) * sgn;
return float3x3(tangent, bitangent, normal);
return real3x3(tangent, bitangent, normal);
float3 TransformTangentToWorld(float3 dirTS, float3x3 worldToTangent)
real3 TransformTangentToWorld(real3 dirTS, real3x3 worldToTangent)
float3 TransformWorldToTangent(float3 dirWS, float3x3 worldToTangent)
real3 TransformWorldToTangent(real3 dirWS, real3x3 worldToTangent)
float3 TransformTangentToObject(float3 dirTS, float3x3 worldToTangent)
real3 TransformTangentToObject(real3 dirTS, real3x3 worldToTangent)
float3 normalWS = mul(dirTS, worldToTangent);
return mul((float3x3)GetWorldToObjectMatrix(), normalWS);
real3 normalWS = mul(dirTS, worldToTangent);
return mul((real3x3)GetWorldToObjectMatrix(), normalWS);
float3 TransformObjectToTangent(float3 dirOS, float3x3 worldToTangent)
real3 TransformObjectToTangent(real3 dirOS, real3x3 worldToTangent)
{
return mul(worldToTangent, TransformObjectToWorldDir(dirOS));
}

33
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Shadows.hlsl


return SampleShadowmap(shadowCoord);
}
half MixRealtimeAndBakedOcclusion(half realtimeAttenuation, half4 bakedOcclusion, half4 distanceAttenuation)
half MixRealtimeAndBakedOcclusion(half realtimeAttenuation, half subtractiveModeBakedOcclusion, half4 shadowMaskModeBakedOcclusion = half4(0, 0, 0, 0))
{
#if defined(LIGHTMAP_ON)
#if defined(_MIXED_LIGHTING_SHADOWMASK)

// We need to remove direct realtime contribution from mixed lights
// distanceAttenuation.w is set 0.0 if this light is mixed, 1.0 otherwise.
return realtimeAttenuation * distanceAttenuation.w;
// subtractiveModeBakedOcclusion is set 0.0 if this light occlusion was baked in the lightmap, 1.0 otherwise.
return realtimeAttenuation * subtractiveModeBakedOcclusion;
}
inline half3 SubtractDirectMainLightFromLightmap(half3 lightmap, half attenuation, half3 lambert)
{
// Let's try to make realtime shadows work on a surface, which already contains
// baked lighting and shadowing from the main sun light.
// Summary:
// 1) Calculate possible value in the shadow by subtracting estimated light contribution from the places occluded by realtime shadow:
// a) preserves other baked lights and light bounces
// b) eliminates shadows on the geometry facing away from the light
// 2) Clamp against user defined ShadowColor.
// 3) Pick original lightmap value, if it is the darkest one.
// 1) Gives good estimate of illumination as if light would've been shadowed during the bake.
// Preserves bounce and other baked lights
// No shadows on the geometry facing away from the light
half shadowStrength = _ShadowData.x;
half3 estimatedLightContributionMaskedByInverseOfShadow = lambert * (1.0 - attenuation);
half3 subtractedLightmap = lightmap - estimatedLightContributionMaskedByInverseOfShadow;
// 2) Allows user to define overall ambient of the scene and control situation when realtime shadow becomes too dark.
half3 realtimeShadow = max(subtractedLightmap, _SubtractiveShadowColor.xyz);
realtimeShadow = lerp(lightmap, realtimeShadow, shadowStrength);
// 3) Pick darkest color
return min(lightmap, realtimeShadow);
}
#endif

5
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Input.hlsl


#include "InputBuiltin.hlsl"
#include "CoreFunctions.hlsl"
float3 GetCameraPosition()
{
return _WorldSpaceCameraPos;
}
#endif

4
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputBuiltin.hlsl


#ifndef LIGHTWEIGHT_SHADER_VARIABLES_INCLUDED
#define LIGHTWEIGHT_SHADER_VARIABLES_INCLUDED
#if (defined(SHADER_API_D3D11) || defined(SHADER_API_PSSL)) && defined(STEREO_INSTANCING_ON)
#define UNITY_STEREO_INSTANCING_ENABLED
#endif
#if defined(UNITY_SINGLE_PASS_STEREO) || defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
#define USING_STEREO_MATRICES
#endif

744
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3003_CameraMotionVector_TranslateX.unity.png

之前 之后
宽度: 853  |  高度: 480  |  大小: 137 KiB

83
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3003_CameraMotionVector_TranslateX.unity.png.meta


fileFormatVersion: 2
guid: 196a05a9d25c75c41a5488213c68d68e
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}
serializedVersion: 5
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -1
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
vertices: []
indices:
edges: []
weights: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:

465
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3004_CameraMotionVector_TranslateY.unity.png

之前 之后
宽度: 853  |  高度: 480  |  大小: 135 KiB

83
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3004_CameraMotionVector_TranslateY.unity.png.meta


fileFormatVersion: 2
guid: 711363d4f145852418f72baec6c6b120
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}
serializedVersion: 5
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -1
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
vertices: []
indices:
edges: []
weights: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:

1001
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3005_CameraMotionVector_TranslateZ.unity.png
文件差异内容过多而无法显示
查看文件

83
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3005_CameraMotionVector_TranslateZ.unity.png.meta


fileFormatVersion: 2
guid: e7ea4bdd6b2d99447b094c1a32dfae02
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}
serializedVersion: 5
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -1
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
vertices: []
indices:
edges: []
weights: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:

902
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3006_CameraMotionVector_RotateX.unity.png

之前 之后
宽度: 853  |  高度: 480  |  大小: 253 KiB

83
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3006_CameraMotionVector_RotateX.unity.png.meta


fileFormatVersion: 2
guid: a97bb246a85dc1846bedbd03effb6e31
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}
serializedVersion: 5
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -1
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
vertices: []
indices:
edges: []
weights: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:

956
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3007_CameraMotionVector_RotateY.unity.png

之前 之后
宽度: 853  |  高度: 480  |  大小: 256 KiB

83
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3007_CameraMotionVector_RotateY.unity.png.meta


fileFormatVersion: 2
guid: 628c41c6730a1474586fa02455196702
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}
serializedVersion: 5
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -1
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
vertices: []
indices:
edges: []
weights: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:

1001
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3008_CameraMotionVector_RotateZ.unity.png
文件差异内容过多而无法显示
查看文件

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

正在加载...
取消
保存