浏览代码

Merge branch 'master' into decals/api_change

# Conflicts:
#	ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalSystem.cs
/main
Paul Melamed 7 年前
当前提交
07ab7b09
共有 153 个文件被更改,包括 1144 次插入926 次删除
  1. 1
      .gitignore
  2. 6
      README.md
  3. 15
      ScriptableRenderPipeline/Core/CoreRP/Debugging/Prefabs/Scripts/UIFoldout.cs
  4. 9
      ScriptableRenderPipeline/Core/CoreRP/Editor/TextureCombiner/TextureCombiner.cs
  5. 7
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/API/GLCore.hlsl
  6. 7
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/API/GLES3.hlsl
  7. 7
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/API/Metal.hlsl
  8. 7
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/API/Vulkan.hlsl
  9. 2
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/BSDF.hlsl
  10. 29
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/EntityLighting.hlsl
  11. 2
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Shadow/ShadowAlgorithms.hlsl
  12. 15
      ScriptableRenderPipeline/Core/CoreRP/Shadow/Shadow.cs
  13. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDAdditionalCameraData.cs
  14. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugColorPicker.shader
  15. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.hlsl
  16. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplayLatlong.shader
  17. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugFullScreen.shader
  18. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugViewMaterialGBuffer.shader
  19. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugViewTiles.shader
  20. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalSystem.cs
  21. 15
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraEditor.cs
  22. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/EditorRenderPipelineResources/ReflectionProbesPreview.shader
  23. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDAssetFactory.cs
  24. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDRenderPipelineMenuItems.cs
  25. 22
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.cs
  26. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.ProbeUtility.cs
  27. 17
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs
  28. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/DiffusionProfile/DrawDiffusionProfile.shader
  29. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/DiffusionProfile/DrawTransmittanceGraph.shader
  30. 44
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs
  31. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Unlit/UnlitsToHDUnlitUpgrader.cs
  32. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/RenderPipelineSettingsUI.cs
  33. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Sky/HDRISky/HDRISkyEditor.cs
  34. 23
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs
  35. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs
  36. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Deferred.shader
  37. 44
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDAdditionalLightData.cs
  38. 259
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightDefinition.cs
  39. 289
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightDefinition.cs.hlsl
  40. 30
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs
  41. 72
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-bigtile.compute
  42. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/scrbound.compute
  43. 21
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtilities.hlsl
  44. 16
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtils.cs
  45. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ReflectionProbeCache.cs
  46. 48
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/VolumeProjection.hlsl
  47. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs.hlsl
  48. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.shader
  49. 20
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalUtilities.hlsl
  50. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/GGXConvolve.shader
  51. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLit.shader
  52. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitTessellation.shader
  53. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl
  54. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.shader
  55. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitTessellation.shader
  56. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Resources/PreIntegratedFGD.shader
  57. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitDepthPass.hlsl
  58. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitDistortionPass.hlsl
  59. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitVelocityPass.hlsl
  60. 15
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/MaterialUtilities.hlsl
  61. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/CombineLighting.shader
  62. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.shader
  63. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Unlit/Unlit.shader
  64. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/Blit.shader
  65. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CameraMotionVectors.shader
  66. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CopyDepthBuffer.shader
  67. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CopyStencilBuffer.shader
  68. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset
  69. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/RenderPipelineResources.cs
  70. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISky.cs
  71. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISkyRenderer.cs
  72. 29
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/ProceduralSky/ProceduralSkyRenderer.cs
  73. 7
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Data/LightweightPipelineAsset.cs
  74. 89
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/LightweightMaterialUpgrader.cs
  75. 118
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGUI/LightweightShaderGUI.cs
  76. 50
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGUI/LightweightStandardGUI.cs
  77. 73
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGUI/LightweightStandardSimpleLightingGUI.cs
  78. 105
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGUI/LightweightUnlitGUI.cs
  79. 15
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/UpgradeCommon.cs
  80. 106
      ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs
  81. 25
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Core.hlsl
  82. 4
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/CoreFunctions.hlsl
  83. 3
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/InputBuiltin.hlsl
  84. 4
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Lighting.hlsl
  85. 5
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassLit.hlsl
  86. 4
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/LightweightPassMeta.hlsl
  87. 12
      ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Shadows.hlsl
  88. 17
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightScreenSpaceShadows.shader
  89. 16
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandard.shader
  90. 16
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardSimpleLighting.shader
  91. 19
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardUnlit.shader
  92. 48
      build.py
  93. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISky.shader
  94. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/ProceduralSky/ProceduralSky.shader
  95. 11
      CHANGELOG.md
  96. 31
      LICENSE.md
  97. 7
      LICENSE.md.meta
  98. 11
      ScriptableRenderPipeline/Core/CHANGELOG.md
  99. 7
      ScriptableRenderPipeline/Core/CHANGELOG.md.meta
  100. 8
      ScriptableRenderPipeline/Core/Documentation.meta

1
.gitignore


Library/*
obj/*
Temp/*
.DS_Store
*.aspx
*.browser
*.csproj

6
README.md


__Note: The Master branch is our current development branch and may not work on the latest publicly available version of Unity. You should always use the latest release tag and latest Unity beta version for testing purposes.__
To use the latest version of the SRP, follow the instructions below:
This repository consists of a folder that needs to be placed in the Assets\ folder of your Unity project. We recommend creating a new project to test SRP. Do not clone this repo into an existing project unless you want to break it, or unless you are updating to a newer version of the SRP repo.
This repository consists of a folder that needs to be placed in the Assets\ folder of your Unity project. We recommend creating a new project to test SRP. Do not clone this repo into an existing project unless you want to break it, or unless you are updating to a newer version of the SRP repo. Your project's `packages.json` file (in either `UnityPackageManager/` or `Packages/`) does not have a dependency on any of the packages in this repository or the contained submodules.
You can use the GitHub desktop app to clone the latest version of the SRP repo or you can use GitHub console commands.

```
> git checkout Unity-2018.1.0b2 (or the latest tag)
> git submodule update --init --recursive --remote (This command fetches the Postprocessing module, which is needed to use SRP)
> git submodule update --init (This command fetches the Postprocessing module, which is needed to use SRP)
```
### To download the repo using console commands:

> git clone https://github.com/Unity-Technologies/ScriptableRenderPipeline
> cd ScriptableRenderPipeline
> git checkout Unity-2018.1.0b2 (or the latest tag)
> git submodule update --init --recursive --remote (This command fetches the Postprocessing module, which is needed to use SRP)
> git submodule update --init (This command fetches the Postprocessing module, which is needed to use SRP)
```
## Scriptable Render Pipeline Assets

15
ScriptableRenderPipeline/Core/CoreRP/Debugging/Prefabs/Scripts/UIFoldout.cs


public GameObject arrowOpened;
public GameObject arrowClosed;
protected override void Awake()
protected override void Start()
base.Awake();
base.Start();
onValueChanged.AddListener(SetState);
SetState(isOn);
}

if (arrowOpened == null || arrowClosed == null || content == null)
return;
arrowOpened.SetActive(state);
arrowClosed.SetActive(!state);
content.SetActive(state);
if (arrowOpened.activeSelf != state)
arrowOpened.SetActive(state);
if (arrowClosed.activeSelf == state)
arrowClosed.SetActive(!state);
if (content.activeSelf != state)
content.SetActive(state);
if (rebuildLayout)
LayoutRebuilder.ForceRebuildLayoutImmediate(transform.parent as RectTransform);

9
ScriptableRenderPipeline/Core/CoreRP/Editor/TextureCombiner/TextureCombiner.cs


return combined;
}
private Texture GetRawTexture (Texture original, bool sRGB = false)
private Texture GetRawTexture (Texture original, bool sRGBFallback = false)
{
if (m_RawTextures == null) m_RawTextures = new Dictionary<Texture, Texture>();
if (!m_RawTextures.ContainsKey(original))

AssetDatabase.ImportAsset(rawPath);
TextureImporter rawImporter = (TextureImporter) TextureImporter.GetAtPath(rawPath);
TextureImporter rawImporter = (TextureImporter) AssetImporter.GetAtPath(rawPath);
rawImporter.textureType = TextureImporterType.Default;
rawImporter.mipmapEnabled = false;
rawImporter.isReadable = true;

rawImporter.sRGBTexture = sRGB;
Texture2D originalTex2D = original as Texture2D;
rawImporter.sRGBTexture = (originalTex2D == null)? sRGBFallback : ( AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(original)) as TextureImporter).sRGBTexture;
rawImporter.maxTextureSize = 8192;
rawImporter.textureCompression = TextureImporterCompression.Uncompressed;

7
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/API/GLCore.hlsl


#define CBUFFER_START(name)
#define CBUFFER_END
// flow control attributes
#define UNITY_BRANCH [branch]
#define UNITY_FLATTEN [flatten]
#define UNITY_UNROLL [unroll]
#define UNITY_UNROLLX(_x) [unroll(_x)]
#define UNITY_LOOP [loop]
// OpenGL 4.1 SM 5.0 https://docs.unity3d.com/Manual/SL-ShaderCompileTargets.html
#if (SHADER_TARGET >= 46)
#define OPENGL4_1_SM5 1

7
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/API/GLES3.hlsl


#define CBUFFER_START(name)
#define CBUFFER_END
// flow control attributes
#define UNITY_BRANCH [branch]
#define UNITY_FLATTEN [flatten]
#define UNITY_UNROLL [unroll]
#define UNITY_UNROLLX(_x) [unroll(_x)]
#define UNITY_LOOP [loop]
// GLES 3.1 + AEP shader feature https://docs.unity3d.com/Manual/SL-ShaderCompileTargets.html
#if (SHADER_TARGET >= 40)
#define GLES3_1_AEP 1

7
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/API/Metal.hlsl


#define CBUFFER_START(name) cbuffer name {
#define CBUFFER_END };
// flow control attributes
#define UNITY_BRANCH [branch]
#define UNITY_FLATTEN [flatten]
#define UNITY_UNROLL [unroll]
#define UNITY_UNROLLX(_x) [unroll(_x)]
#define UNITY_LOOP [loop]
// Initialize arbitrary structure with zero values.
// Do not exist on some platform, in this case we need to have a standard name that call a function that will initialize all parameters to 0
#define ZERO_INITIALIZE(type, name) name = (type)0;

7
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/API/Vulkan.hlsl


#define CBUFFER_START(name) cbuffer name {
#define CBUFFER_END };
// flow control attributes
#define UNITY_BRANCH [branch]
#define UNITY_FLATTEN [flatten]
#define UNITY_UNROLL [unroll]
#define UNITY_UNROLLX(_x) [unroll(_x)]
#define UNITY_LOOP [loop]
// Initialize arbitrary structure with zero values.
// Do not exist on some platform, in this case we need to have a standard name that call a function that will initialize all parameters to 0
#define ZERO_INITIALIZE(type, name) name = (type)0;

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


}
// Evaluate the reflectance for a thin-film layer on top of a dielectric medum.
real3 EvalIridescence(real eta_1, real cosTheta1, real iridescenceThickness, real baseLayerFresnel0)
real3 EvalIridescence(real eta_1, real cosTheta1, real iridescenceThickness, real3 baseLayerFresnel0)
{
// iridescenceThickness unit is micrometer for this equation here. Mean 0.5 is 500nm.
real Dinc = 3.0 * iridescenceThickness;

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


// It is required for other platform that aren't supporting this format to implement variant of these functions
// (But these kind of platform should use regular render loop and not news shaders).
// RGBM lightmaps are currently always gamma encoded, so we use a constant of range^2.2 = 5^2.2
#define LIGHTMAP_RGBM_RANGE 34.493242
// DLDR lightmaps are currently always gamma encoded, so we use a constant of 2.0^2.2 = 4.59
#define LIGHTMAP_DLDR_RANGE 4.59
// TODO: This is the max value allowed for emissive (bad name - but keep for now to retrieve it) (It is 8^2.2 (gamma) and 8 is the limit of punctual light slider...), comme from UnityCg.cginc. Fix it!
// Ask Jesper if this can be change for HDRenderPipeline
#define EMISSIVE_RGBM_SCALE 97.0

return rgbm;
}
real3 UnpackLightmapRGBM(real4 rgbmInput)
real3 UnpackLightmapRGBM(real4 rgbmInput, real4 decodeInstructions)
// RGBM lightmaps are always gamma encoded for now, so decode with that in mind:
return rgbmInput.rgb * pow(rgbmInput.a, 2.2) * LIGHTMAP_RGBM_RANGE;
return rgbmInput.rgb * pow(rgbmInput.a, decodeInstructions.y) * decodeInstructions.x;
real3 UnpackLightmapDoubleLDR(real4 encodedColor)
real3 UnpackLightmapDoubleLDR(real4 encodedColor, real4 decodeInstructions)
return encodedColor.rgb * LIGHTMAP_DLDR_RANGE;
return encodedColor.rgb * decodeInstructions.x;
real3 DecodeLightmap(real4 encodedIlluminance)
real3 DecodeLightmap(real4 encodedIlluminance, real4 decodeInstructions)
return UnpackLightmapRGBM(encodedIlluminance);
return UnpackLightmapRGBM(encodedIlluminance, decodeInstructions);
return UnpackLightmapDoubleLDR(encodedIlluminance);
return UnpackLightmapDoubleLDR(encodedIlluminance, decodeInstructions);
#endif
}

return (decodeInstructions.x * pow(alpha, decodeInstructions.y)) * encodedIrradiance.rgb;
}
real3 SampleSingleLightmap(TEXTURE2D_ARGS(lightmapTex, lightmapSampler), float2 uv, float4 transform, bool encodedLightmap)
real3 SampleSingleLightmap(TEXTURE2D_ARGS(lightmapTex, lightmapSampler), float2 uv, float4 transform, bool encodedLightmap, real4 decodeInstructions)
{
// transform is scale and bias
uv = uv * transform.xy + transform.zw;

{
real4 encodedIlluminance = SAMPLE_TEXTURE2D(lightmapTex, lightmapSampler, uv).rgba;
illuminance = DecodeLightmap(encodedIlluminance);
illuminance = DecodeLightmap(encodedIlluminance, decodeInstructions);
}
else
{

}
real3 SampleDirectionalLightmap(TEXTURE2D_ARGS(lightmapTex, lightmapSampler), TEXTURE2D_ARGS(lightmapDirTex, lightmapDirSampler), float2 uv, float4 transform, float3 normalWS, bool encodedLightmap)
real3 SampleDirectionalLightmap(TEXTURE2D_ARGS(lightmapTex, lightmapSampler), TEXTURE2D_ARGS(lightmapDirTex, lightmapDirSampler), float2 uv, float4 transform, float3 normalWS, bool encodedLightmap, real4 decodeInstructions)
{
// In directional mode Enlighten bakes dominant light direction
// in a way, that using it for half Lambert and then dividing by a "rebalancing coefficient"

if (encodedLightmap)
{
real4 encodedIlluminance = SAMPLE_TEXTURE2D(lightmapTex, lightmapSampler, uv).rgba;
illuminance = DecodeLightmap(encodedIlluminance);
illuminance = DecodeLightmap(encodedIlluminance, decodeInstructions);
}
else
{

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


wposDir = -sphere.xyz + positionWS;
float distSq = dot( wposDir, wposDir );
relDistance = distSq / sphere.w;
if( relDistance <= 1.0 )
if( relDistance > 0.0 && relDistance <= 1.0 )
{
splitSphere = sphere.xyz;
wposDir /= sqrt( distSq );

15
ScriptableRenderPipeline/Core/CoreRP/Shadow/Shadow.cs


if( sr.shadowType == GPUShadowType.Directional )
{
asd.GetShadowCascades( out cascadeCnt, out cascadeRatios, out cascadeBorders );
for( int i = 0; i < m_TmpSplits.Length; i++ )
m_TmpSplits[i].w = -1.0f;
}

}
// read
float texelSizeX = 1.0f, texelSizeY = 1.0f;
CachedEntry ce = m_EntryCache[ceIdx];
ce.zclip = sr.shadowType != GPUShadowType.Directional;

if( ce.current.splitData.cullingSphere.w != float.NegativeInfinity )
{
int face = (int)key.faceIdx;
texelSizeX = 2.0f / ce.current.proj.m00;
texelSizeY = 2.0f / ce.current.proj.m11;
m_TmpBorders[face] = cascadeBorders[face];
m_TmpSplits[key.faceIdx].w *= ce.current.splitData.cullingSphere.w;
}

uint first = k_MaxCascadesInShader, second = k_MaxCascadesInShader;
for( uint i = 0; i < k_MaxCascadesInShader; i++, payloadOffset++ )
{
first = (first == k_MaxCascadesInShader && m_TmpSplits[i].w > 0.0f) ? i : first;
second = (second == k_MaxCascadesInShader && m_TmpSplits[i].w > 0.0f) ? i : second;
first = ( first == k_MaxCascadesInShader && m_TmpSplits[i].w > 0.0f) ? i : first;
second = ((second == k_MaxCascadesInShader || second == first) && m_TmpSplits[i].w > 0.0f) ? i : second;
sp.Set( m_TmpSplits[i] );
payload[payloadOffset] = sp;
}

}
if( curx + vp.width > xmax || cury + curh > ymax || curslice == m_Slices )
{
Debug.LogError( "ERROR! Shadow atlasing failed." );
Debug.LogWarning( "Shadow atlasing has failed." );
return false;
}
vp.x = curx;

}
if( smidx == k_MaxShadowmapPerType )
{
Debug.LogError("The requested shadows do not fit into any shadowmap.");
Debug.LogWarning("The requested shadows do not fit into any shadowmap.");
return false;
}
}

{
if( !sm.ReserveFinalize( frameId, ref shadowDatas, ref shadowmapPayload ) )
{
Debug.LogError("Shadow allocation failed in the ReserveFinalize step." );
Debug.LogWarning("Shadow allocation failed in the ReserveFinalize step." );
return false;
}
}

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


using UnityEngine.Serialization;
using UnityEngine.Serialization;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{

void UnRegisterDebug()
{
if (m_camera == null)
return;
if (m_IsDebugRegistered)
{
if (m_camera.cameraType != CameraType.Preview && m_camera.cameraType != CameraType.Reflection)

// When LDR, unity render in 8bitSRGB, then do a final shader with sRGB conversion
// What should be done is just in our Post process we convert to sRGB and store in a linear 10bit, but require C++ change...
m_camera = GetComponent<Camera>();
if (m_camera == null)
return;
m_camera.allowHDR = false;
// Tag as dirty so frameSettings are correctly initialize at next HDRenderPipeline.Render() call

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugColorPicker.shader


{
SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
ZWrite Off

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


}
// 4. Display leading 0
#pragma warning(disable : 3557) // loop only executes for 0 iteration(s)
#pragma warning(default : 3557)
// 5. Display sign
if (intValue < 0 || forceNegativeSign)

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplayLatlong.shader


{
SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
ZWrite On

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugFullScreen.shader


{
SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
ZWrite Off

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugViewMaterialGBuffer.shader


{
SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
ZWrite Off

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugViewTiles.shader


{
SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
ZWrite Off

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


if (m_DecalAtlas != null)
m_DecalAtlas.Release();
CoreUtils.Destroy(m_DecalMesh);
m_DecalAtlas = null; // set to null so that it gets recreated correctly
// set to null so that they get recreated
m_DecalAtlas = null;
m_DecalMesh = null;
}
}

15
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraEditor.cs


using System;
using System;
using UnityEngine.Assertions;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine.Rendering.PostProcessing;

[CanEditMultipleObjects]
partial class HDCameraEditor : Editor
{
[MenuItem("CONTEXT/Camera/Remove HD Camera", false, 0)]
static void RemoveLight(MenuCommand menuCommand)
{
GameObject go = ((Camera)menuCommand.context).gameObject;
Assert.IsNotNull(go);
Undo.SetCurrentGroupName("Remove HD Camera");
Undo.DestroyObjectImmediate(go.GetComponent<Camera>());
Undo.DestroyObjectImmediate(go.GetComponent<HDAdditionalCameraData>());
}
SerializedHDCamera m_SerializedCamera;
HDCameraUI m_UIState = new HDCameraUI();

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


_Exposure("_Exposure", Range(-10.0,10.0)) = 0.0
}
SubShader
SubShader
Tags{ "RenderType" = "Opaque" "Queue" = "Transparent" }
Tags{ "RenderPipeline" = "HDRenderPipeline" "RenderType" = "Opaque" "Queue" = "Transparent" }
ZWrite On
Cull Back

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDAssetFactory.cs


newAsset.computeGgxIblSampleData = Load<ComputeShader>(HDRenderPipelinePath + "Material/GGXConvolution/ComputeGgxIblSampleData.compute");
newAsset.GGXConvolve = Load<Shader>(HDRenderPipelinePath + "Material/GGXConvolution/GGXConvolve.shader");
newAsset.opaqueAtmosphericScattering = Load<Shader>(HDRenderPipelinePath + "Sky/OpaqueAtmosphericScattering.shader");
newAsset.hdriSky = Load<Shader>(HDRenderPipelinePath + "Sky/HDRISky/HDRISky.shader");
newAsset.proceduralSky = Load<Shader>(HDRenderPipelinePath + "Sky/ProceduralSky/ProceduralSky.shader");
// Utilities / Core
newAsset.encodeBC6HCS = Load<ComputeShader>(CorePath + "CoreResources/EncodeBC6H.compute");

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDRenderPipelineMenuItems.cs


}
else if (add.lightTypeExtent == LightTypeExtent.Line)
{
add.areaIntensity = l.intensity / LightUtils.calculateLineLightArea(1.0f, add.shapeWidth);
add.areaIntensity = l.intensity / LightUtils.CalculateLineLightIntensity(1.0f, add.shapeWidth);
}
}

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


using System;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;

[CustomEditorForRenderPipeline(typeof(Light), typeof(HDRenderPipelineAsset))]
sealed partial class HDLightEditor : LightEditor
{
[MenuItem("CONTEXT/Light/Remove HD Light", false,0)]
static void RemoveLight(MenuCommand menuCommand)
{
GameObject go = ( (Light) menuCommand.context ).gameObject;
Assert.IsNotNull(go);
Undo.IncrementCurrentGroup();
Undo.DestroyObjectImmediate(go.GetComponent<Light>());
Undo.DestroyObjectImmediate(go.GetComponent<HDAdditionalLightData>());
Undo.DestroyObjectImmediate(go.GetComponent<AdditionalShadowData>());
}
sealed class SerializedLightData
{
public SerializedProperty directionalIntensity;

base.OnEnable();
// Get & automatically add additional HD data if not present
var lightData = CoreEditorUtils.GetAdditionalData<HDAdditionalLightData>(targets);
var lightData = CoreEditorUtils.GetAdditionalData<HDAdditionalLightData>(targets, HDAdditionalLightData.InitDefaultHDAdditionalLightData);
var shadowData = CoreEditorUtils.GetAdditionalData<AdditionalShadowData>(targets, HDAdditionalShadowData.InitDefaultHDAdditionalShadowData);
m_SerializedAdditionalLightData = new SerializedObject(lightData);
m_SerializedAdditionalShadowData = new SerializedObject(shadowData);

m_SerializedAdditionalLightData.Update();
m_SerializedAdditionalShadowData.Update();
// Disable the default light editor for the release, it is just use for development
/*
// Temporary toggle to go back to the old editor & separated additional datas
bool useOldInspector = m_AdditionalLightData.useOldInspector.boolValue;

m_SerializedAdditionalLightData.ApplyModifiedProperties();
return;
}
*/
// New editor
ApplyAdditionalComponentsVisibility(true);

}
}
// Caution: this function must match the one in HDAdditionalLightData.ConvertPhysicalLightIntensityToLightIntensity - any change need to be replicated
void UpdateLightIntensity()
{
switch (m_LightShape)

break;
case LightShape.Line:
settings.intensity.floatValue = LightUtils.calculateLineLightArea(m_AdditionalLightData.areaIntensity.floatValue, m_AdditionalLightData.shapeWidth.floatValue);
settings.intensity.floatValue = LightUtils.CalculateLineLightIntensity(m_AdditionalLightData.areaIntensity.floatValue, m_AdditionalLightData.shapeWidth.floatValue);
break;
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.ProbeUtility.cs


using UnityEngine;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using Object = UnityEngine.Object;

{
void ChangeVisibilityOfAllTargets(bool visibility)
{
if (targets.Length == 0) return;
var p = (ReflectionProbe)targets[i];
HDReflectionProbeEditorUtility.ChangeVisibility(p, visibility);
if (targets[i] != null)
{
var p = (ReflectionProbe)targets[i];
HDReflectionProbeEditorUtility.ChangeVisibility(p, visibility);
}
}
}

17
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs


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

[CanEditMultipleObjects]
partial class HDReflectionProbeEditor : Editor
{
[MenuItem("CONTEXT/ReflectionProbe/Remove HD Reflection Probe", false, 0)]
static void RemoveLight(MenuCommand menuCommand)
{
GameObject go = ((ReflectionProbe)menuCommand.context).gameObject;
Assert.IsNotNull(go);
Undo.SetCurrentGroupName("Remove HD Reflection Probe");
Undo.DestroyObjectImmediate(go.GetComponent<ReflectionProbe>());
Undo.DestroyObjectImmediate(go.GetComponent<HDAdditionalReflectionData>());
Undo.DestroyObjectImmediate(go.GetComponent<MeshRenderer>());
Undo.DestroyObjectImmediate(go.GetComponent<MeshFilter>());
}
static Dictionary<ReflectionProbe, HDReflectionProbeEditor> s_ReflectionProbeEditors = new Dictionary<ReflectionProbe, HDReflectionProbeEditor>();
static HDReflectionProbeEditor GetEditorFor(ReflectionProbe p)

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/DiffusionProfile/DrawDiffusionProfile.shader


{
SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
Cull Off

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/DiffusionProfile/DrawTransmittanceGraph.shader


{
SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
Cull Off

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


RenameTexture("_SpecGlossMap", "_SpecularColorMap");
}
}
public override void Convert(Material srcMaterial, Material dstMaterial)
{
dstMaterial.hideFlags = HideFlags.DontUnloadUnusedAsset;

// Metallic
bool hasMetallic = false;
Texture metallicMap;
Texture metallicMap = Texture2D.blackTexture;
if (hasMetallic) metallicMap = TextureCombiner.GetTextureSafe(srcMaterial, "_MetallicGlossMap", Color.white);
if (hasMetallic)
{
metallicMap = TextureCombiner.GetTextureSafe(srcMaterial, "_MetallicGlossMap", Color.white);
}
else
{
float metallicValue = Mathf.Pow(srcMaterial.GetFloat("_Metallic"), 2.2f); // Convert _Metallic value from Gamma to Linear
dstMaterial.SetFloat("_Metallic", metallicValue);
metallicMap = TextureCombiner.TextureFromColor(Color.white * metallicValue);
}
else
metallicMap = Texture2D.blackTexture;
Texture occlusionMap;
Texture occlusionMap = Texture2D.whiteTexture;
Texture detailMaskMap;
Texture detailMaskMap = Texture2D.whiteTexture;
if (hasDetailMask) detailMaskMap = TextureCombiner.GetTextureSafe(srcMaterial, "_DetailMask", Color.white);
// Smoothness

if (hasSmoothness)
smoothnessMap = (Texture2D)TextureCombiner.GetTextureSafe(srcMaterial, "_SpecGlossMap", Color.grey);
}
}
else
{
string smoothnessTextureChannel = "_MainTex";

Texture2D maskMap;
TextureCombiner maskMapCombiner = new TextureCombiner(
TextureCombiner.GetTextureSafe(srcMaterial, "_MetallicGlossMap", Color.white), 4, // Metallic
TextureCombiner.GetTextureSafe(srcMaterial, "_OcclusionMap", Color.white), 4, // Occlusion
TextureCombiner.GetTextureSafe(srcMaterial, "_DetailMask", Color.white), 4, // Detail Mask
smoothnessMap, (srcMaterial.shader.name == Standard_Rough)?-4:3 // Smoothness Texture
metallicMap, 0, // R: Metallic from red
occlusionMap, 0, // G: Occlusion from red
detailMaskMap, 0, // B: Detail Mask from red
smoothnessMap, (srcMaterial.shader.name == Standard_Rough)?-4:3 // A: Smoothness Texture from inverse greyscale for roughness setup, or alpha
dstMaterial.SetFloat("_Metallic", 1f); // Force _Metallic value to 1, to use the value stored in the mask map without modification
string maskMapPath = AssetDatabase.GetAssetPath(srcMaterial);
maskMapPath = maskMapPath.Remove(maskMapPath.Length-4) + "_MaskMap.png";
maskMap = maskMapCombiner.Combine( maskMapPath );

dstMaterial.SetFloat("_AlphaCutoffEnable", 0);
dstMaterial.SetFloat("_EnableBlendModePreserveSpecularLighting", 0);
break;
case 3: // Transparent -> Alpha
case 3: // Transparent -> Alpha
dstMaterial.SetFloat("_SurfaceType", 1);
dstMaterial.SetFloat("_BlendMode", 0);
dstMaterial.SetFloat("_AlphaCutoffEnable", 0);

// Emission: Convert the HDR emissive color to ldr color + intensity
Color hdrEmission = srcMaterial.GetColor("_EmissionColor");
float intensity = Mathf.Max(hdrEmission.r, Mathf.Max(hdrEmission.g, hdrEmission.b));
if (intensity > 1f)
{
hdrEmission.r /= intensity;

intensity = 1f;
intensity = Mathf.Pow(intensity, 2.2f); // Gamma to Linear conversion
}
}

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Unlit/UnlitsToHDUnlitUpgrader.cs


public class UnlitsToHDUnlitUpgrader : MaterialUpgrader
{
string Unlit_Color = "Unlit/Color";
string Unlit_Texture = "Unlit/Texture";
//string Unlit_Texture = "Unlit/Texture";
string Unlit_Transparent = "Unlit/Transparent";
string Unlit_Cutout = "Unlit/Transparent Cutout";

//dstMaterial.hideFlags = HideFlags.DontUnloadUnusedAsset;
base.Convert(srcMaterial, dstMaterial);
HDEditorUtils.ResetMaterialKeywords(dstMaterial);
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/RenderPipelineSettingsUI.cs


EditorGUILayout.PropertyField(d.supportForwardOnly, _.GetContent("Support Forward Only"));
EditorGUILayout.PropertyField(d.supportMotionVectors, _.GetContent("Support Motion Vectors"));
EditorGUILayout.PropertyField(d.supportStereo, _.GetContent("Support Stereo Rendering"));
EditorGUILayout.PropertyField(d.enableUltraQualitySSS, _.GetContent("Enable Ultra Quality SSS"));
EditorGUILayout.PropertyField(d.enableUltraQualitySSS, _.GetContent("Increase SSS Sample Count"));
--EditorGUI.indentLevel;
}
}

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Sky/HDRISky/HDRISkyEditor.cs


public class HDRISkyEditor
: SkySettingsEditor
{
SerializedDataParameter m_SkyHDRI;
SerializedDataParameter m_hdriSky;
public override void OnEnable()
{

m_SkyHDRI = Unpack(o.Find(x => x.skyHDRI));
m_hdriSky = Unpack(o.Find(x => x.hdriSky));
PropertyField(m_SkyHDRI);
PropertyField(m_hdriSky);
EditorGUILayout.Space();

23
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs


InitializeDebugMaterials();
m_MaterialList.ForEach(material => material.Build(asset));
m_IBLFilterGGX = new IBLFilterGGX(asset.renderPipelineResources);

void SetRenderingFeatures()
{
// Set subshader pipeline tag
Shader.globalRenderPipeline = "HDRenderPipeline";
// HD use specific GraphicsSettings
GraphicsSettings.lightsUseLinearIntensity = true;
GraphicsSettings.lightsUseColorTemperature = true;

#endif
}
void UnsetRenderingFeatures()
{
Shader.globalRenderPipeline = "";
SupportedRenderingFeatures.active = new SupportedRenderingFeatures();
Lightmapping.ResetDelegate();
}
void InitializeDebugMaterials()
{
m_DebugViewMaterialGBuffer = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugViewMaterialGBufferShader);

DestroyRenderTextures();
SupportedRenderingFeatures.active = new SupportedRenderingFeatures();
Lightmapping.ResetDelegate();
UnsetRenderingFeatures();
#if UNITY_EDITOR
SceneViewDrawMode.ResetDrawMode();

}
VolumeManager.instance.Update(camera.transform, layerMask);
}
}
// Disable postprocess if we enable debug mode
if (m_CurrentDebugDisplaySettings.fullScreenDebugMode == FullScreenDebugMode.None && m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled())
{
m_FrameSettings.enablePostprocess = false;
}
var postProcessLayer = camera.GetComponent<PostProcessLayer>();

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs


public static readonly int _EnvLightIndexShift = Shader.PropertyToID("_EnvLightIndexShift");
public static readonly int g_isOrthographic = Shader.PropertyToID("g_isOrthographic");
public static readonly int g_iNrVisibLights = Shader.PropertyToID("g_iNrVisibLights");
public static readonly int g_mScrProjectionArr = Shader.PropertyToID("g_mScrProjectionArr");
public static readonly int g_mInvScrProjectionArr = Shader.PropertyToID("g_mInvScrProjectionArr");
public static readonly int g_iLog2NumClusters = Shader.PropertyToID("g_iLog2NumClusters");
public static readonly int g_screenSize = Shader.PropertyToID("g_screenSize");
public static readonly int g_iNumSamplesMSAA = Shader.PropertyToID("g_iNumSamplesMSAA");

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


SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
Stencil

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


}
#endif
// Caution: this function must match the one in HDLightEditor.UpdateLightIntensity - any change need to be replicated
public void ConvertPhysicalLightIntensityToLightIntensity()
{
var light = gameObject.GetComponent<Light>();
if (lightTypeExtent == LightTypeExtent.Punctual)
{
switch (light.type)
{
case LightType.Directional:
light.intensity = directionalIntensity;
break;
case LightType.Point:
light.intensity = LightUtils.ConvertPointLightIntensity(punctualIntensity);
break;
case LightType.Spot:
// Spot should used conversion which take into account the angle, and thus the intensity vary with angle.
// This is not easy to manipulate for lighter, so we simply consider any spot light as just occluded point light. So reuse the same code.
light.intensity = LightUtils.ConvertPointLightIntensity(punctualIntensity);
// TODO: What to do with box shape ?
// var spotLightShape = (SpotLightShape)m_AdditionalspotLightShape.enumValueIndex;
break;
}
}
else if (lightTypeExtent == LightTypeExtent.Rectangle)
{
light.intensity = LightUtils.ConvertRectLightIntensity(areaIntensity, shapeWidth, shapeHeight);
}
else if (lightTypeExtent == LightTypeExtent.Line)
{
light.intensity = LightUtils.CalculateLineLightIntensity(areaIntensity, shapeWidth);
}
}
// As we have our own default value, we need to initialize the light intensity correctly
public static void InitDefaultHDAdditionalLightData(HDAdditionalLightData lightData)
{
// At first init we need to initialize correctly the default value
lightData.ConvertPhysicalLightIntensityToLightIntensity();
}
}
}

259
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightDefinition.cs


public struct EnvLightData
{
// Packing order depends on chronological access to avoid cache misses
// Caution: The struct need to be align on byte16 (not strictly needed for structured buffer but if we do array later better).
public float capturePositionWSX;
public float capturePositionWSY;
public float capturePositionWSZ;
public Vector3 capturePositionWS;
public float proxyExtentsX;
public float proxyExtentsY;
public float proxyExtentsZ;
public Vector3 proxyExtents;
public float proxyPositionWSX;
public float proxyPositionWSY;
public float proxyPositionWSZ;
public float proxyForwardX;
public float proxyForwardY;
public float proxyForwardZ;
public float proxyUpX;
public float proxyUpY;
public float proxyUpZ;
public float proxyRightX;
public float proxyRightY;
public float proxyRightZ;
public Vector3 proxyPositionWS;
public Vector3 proxyForward;
public Vector3 proxyUp;
public Vector3 proxyRight;
public float influencePositionWSX;
public float influencePositionWSY;
public float influencePositionWSZ;
public float influenceForwardX;
public float influenceForwardY;
public float influenceForwardZ;
public float influenceUpX;
public float influenceUpY;
public float influenceUpZ;
public float influenceRightX;
public float influenceRightY;
public float influenceRightZ;
public Vector3 influencePositionWS;
public Vector3 influenceForward;
public Vector3 influenceUp;
public Vector3 influenceRight;
public float influenceExtentsX;
public float influenceExtentsY;
public float influenceExtentsZ;
public Vector3 influenceExtents;
public float blendDistancePositiveX;
public float blendDistancePositiveY;
public float blendDistancePositiveZ;
public float blendDistanceNegativeX;
public float blendDistanceNegativeY;
public float blendDistanceNegativeZ;
public float blendNormalDistancePositiveX;
public float blendNormalDistancePositiveY;
public float blendNormalDistancePositiveZ;
public float blendNormalDistanceNegativeX;
public float blendNormalDistanceNegativeY;
public float blendNormalDistanceNegativeZ;
public Vector3 blendDistancePositive;
public Vector3 blendDistanceNegative;
public Vector3 blendNormalDistancePositive;
public Vector3 blendNormalDistanceNegative;
public float boxSideFadePositiveX;
public float boxSideFadePositiveY;
public float boxSideFadePositiveZ;
public float boxSideFadeNegativeX;
public float boxSideFadeNegativeY;
public float boxSideFadeNegativeZ;
public Vector3 boxSideFadePositive;
public Vector3 boxSideFadeNegative;
public float sampleDirectionDiscardWSX;
public float sampleDirectionDiscardWSY;
public float sampleDirectionDiscardWSZ;
public Vector3 sampleDirectionDiscardWS;
public Vector3 capturePositionWS
{
get { return new Vector3(capturePositionWSX, capturePositionWSY, capturePositionWSZ); }
set
{
capturePositionWSX = value.x;
capturePositionWSY = value.y;
capturePositionWSZ = value.z;
}
}
public Vector3 proxyExtents
{
get { return new Vector3(proxyExtentsX, proxyExtentsY, proxyExtentsZ); }
set
{
proxyExtentsX = value.x;
proxyExtentsY = value.y;
proxyExtentsZ = value.z;
}
}
public Vector3 proxyPositionWS
{
get { return new Vector3(proxyPositionWSX, proxyPositionWSY, proxyPositionWSZ); }
set
{
proxyPositionWSX = value.x;
proxyPositionWSY = value.y;
proxyPositionWSZ = value.z;
}
}
public Vector3 proxyForward
{
get { return new Vector3(proxyForwardX, proxyForwardY, proxyForwardZ); }
set
{
proxyForwardX = value.x;
proxyForwardY = value.y;
proxyForwardZ = value.z;
}
}
public Vector3 proxyUp
{
get { return new Vector3(proxyUpX, proxyUpY, proxyUpZ); }
set
{
proxyUpX = value.x;
proxyUpY = value.y;
proxyUpZ = value.z;
}
}
public Vector3 proxyRight
{
get { return new Vector3(proxyRightX, proxyRightY, proxyRightZ); }
set
{
proxyRightX = value.x;
proxyRightY = value.y;
proxyRightZ = value.z;
}
}
public Vector3 influenceExtents
{
get { return new Vector3(influenceExtentsX, influenceExtentsY, influenceExtentsZ); }
set
{
influenceExtentsX = value.x;
influenceExtentsY = value.y;
influenceExtentsZ = value.z;
}
}
public Vector3 influencePositionWS
{
get { return new Vector3(influencePositionWSX, influencePositionWSY, influencePositionWSZ); }
set
{
influencePositionWSX = value.x;
influencePositionWSY = value.y;
influencePositionWSZ = value.z;
}
}
public Vector3 influenceForward
{
get { return new Vector3(influenceForwardX, influenceForwardY, influenceForwardZ); }
set
{
influenceForwardX = value.x;
influenceForwardY = value.y;
influenceForwardZ = value.z;
}
}
public Vector3 influenceUp
{
get { return new Vector3(influenceUpX, influenceUpY, influenceUpZ); }
set
{
influenceUpX = value.x;
influenceUpY = value.y;
influenceUpZ = value.z;
}
}
public Vector3 influenceRight
{
get { return new Vector3(influenceRightX, influenceRightY, influenceRightZ); }
set
{
influenceRightX = value.x;
influenceRightY = value.y;
influenceRightZ = value.z;
}
}
public Vector3 blendDistancePositive
{
get { return new Vector3(blendDistancePositiveX, blendDistancePositiveY, blendDistancePositiveZ); }
set
{
blendDistancePositiveX = value.x;
blendDistancePositiveY = value.y;
blendDistancePositiveZ = value.z;
}
}
public Vector3 blendDistanceNegative
{
get { return new Vector3(blendDistanceNegativeX, blendDistanceNegativeY, blendDistanceNegativeZ); }
set
{
blendDistanceNegativeX = value.x;
blendDistanceNegativeY = value.y;
blendDistanceNegativeZ = value.z;
}
}
public Vector3 blendNormalDistancePositive
{
get { return new Vector3(blendNormalDistancePositiveX, blendNormalDistancePositiveY, blendNormalDistancePositiveZ); }
set
{
blendNormalDistancePositiveX = value.x;
blendNormalDistancePositiveY = value.y;
blendNormalDistancePositiveZ = value.z;
}
}
public Vector3 blendNormalDistanceNegative
{
get { return new Vector3(blendNormalDistanceNegativeX, blendNormalDistanceNegativeY, blendNormalDistanceNegativeZ); }
set
{
blendNormalDistanceNegativeX = value.x;
blendNormalDistanceNegativeY = value.y;
blendNormalDistanceNegativeZ = value.z;
}
}
public Vector3 boxSideFadePositive
{
get { return new Vector3(boxSideFadePositiveX, boxSideFadePositiveY, boxSideFadePositiveZ); }
set
{
boxSideFadePositiveX = value.x;
boxSideFadePositiveY = value.y;
boxSideFadePositiveZ = value.z;
}
}
public Vector3 boxSideFadeNegative
{
get { return new Vector3(boxSideFadeNegativeX, boxSideFadeNegativeY, boxSideFadeNegativeZ); }
set
{
boxSideFadeNegativeX = value.x;
boxSideFadeNegativeY = value.y;
boxSideFadeNegativeZ = value.z;
}
}
public Vector3 sampleDirectionDiscardWS
{
get { return new Vector3(sampleDirectionDiscardWSX, sampleDirectionDiscardWSY, sampleDirectionDiscardWSZ); }
set
{
sampleDirectionDiscardWSX = value.x;
sampleDirectionDiscardWSY = value.y;
sampleDirectionDiscardWSZ = value.z;
}
}
};
[GenerateHLSL]

289
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightDefinition.cs.hlsl


// PackingRules = Exact
struct EnvLightData
{
float capturePositionWSX;
float capturePositionWSY;
float capturePositionWSZ;
float3 capturePositionWS;
float proxyExtentsX;
float proxyExtentsY;
float proxyExtentsZ;
float3 proxyExtents;
float proxyPositionWSX;
float proxyPositionWSY;
float proxyPositionWSZ;
float proxyForwardX;
float proxyForwardY;
float proxyForwardZ;
float proxyUpX;
float proxyUpY;
float proxyUpZ;
float proxyRightX;
float proxyRightY;
float proxyRightZ;
float influencePositionWSX;
float influencePositionWSY;
float influencePositionWSZ;
float influenceForwardX;
float influenceForwardY;
float influenceForwardZ;
float influenceUpX;
float influenceUpY;
float influenceUpZ;
float influenceRightX;
float influenceRightY;
float influenceRightZ;
float influenceExtentsX;
float influenceExtentsY;
float influenceExtentsZ;
float3 proxyPositionWS;
float3 proxyForward;
float3 proxyUp;
float3 proxyRight;
float3 influencePositionWS;
float3 influenceForward;
float3 influenceUp;
float3 influenceRight;
float3 influenceExtents;
float blendDistancePositiveX;
float blendDistancePositiveY;
float blendDistancePositiveZ;
float blendDistanceNegativeX;
float blendDistanceNegativeY;
float blendDistanceNegativeZ;
float blendNormalDistancePositiveX;
float blendNormalDistancePositiveY;
float blendNormalDistancePositiveZ;
float blendNormalDistanceNegativeX;
float blendNormalDistanceNegativeY;
float blendNormalDistanceNegativeZ;
float boxSideFadePositiveX;
float boxSideFadePositiveY;
float boxSideFadePositiveZ;
float boxSideFadeNegativeX;
float boxSideFadeNegativeY;
float boxSideFadeNegativeZ;
float3 blendDistancePositive;
float3 blendDistanceNegative;
float3 blendNormalDistancePositive;
float3 blendNormalDistanceNegative;
float3 boxSideFadePositive;
float3 boxSideFadeNegative;
float sampleDirectionDiscardWSX;
float sampleDirectionDiscardWSY;
float sampleDirectionDiscardWSZ;
float3 sampleDirectionDiscardWS;
int envIndex;
};

//
// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.EnvLightData
//
float GetCapturePositionWSX(EnvLightData value)
{
return value.capturePositionWSX;
}
float GetCapturePositionWSY(EnvLightData value)
float3 GetCapturePositionWS(EnvLightData value)
return value.capturePositionWSY;
}
float GetCapturePositionWSZ(EnvLightData value)
{
return value.capturePositionWSZ;
return value.capturePositionWS;
float GetProxyExtentsX(EnvLightData value)
float3 GetProxyExtents(EnvLightData value)
return value.proxyExtentsX;
}
float GetProxyExtentsY(EnvLightData value)
{
return value.proxyExtentsY;
}
float GetProxyExtentsZ(EnvLightData value)
{
return value.proxyExtentsZ;
return value.proxyExtents;
float GetProxyPositionWSX(EnvLightData value)
float3 GetProxyPositionWS(EnvLightData value)
return value.proxyPositionWSX;
return value.proxyPositionWS;
float GetProxyPositionWSY(EnvLightData value)
float3 GetProxyForward(EnvLightData value)
return value.proxyPositionWSY;
return value.proxyForward;
float GetProxyPositionWSZ(EnvLightData value)
float3 GetProxyUp(EnvLightData value)
return value.proxyPositionWSZ;
return value.proxyUp;
float GetProxyForwardX(EnvLightData value)
{
return value.proxyForwardX;
}
float GetProxyForwardY(EnvLightData value)
{
return value.proxyForwardY;
}
float GetProxyForwardZ(EnvLightData value)
float3 GetProxyRight(EnvLightData value)
return value.proxyForwardZ;
return value.proxyRight;
float GetProxyUpX(EnvLightData value)
float3 GetInfluencePositionWS(EnvLightData value)
return value.proxyUpX;
}
float GetProxyUpY(EnvLightData value)
{
return value.proxyUpY;
return value.influencePositionWS;
float GetProxyUpZ(EnvLightData value)
float3 GetInfluenceForward(EnvLightData value)
return value.proxyUpZ;
return value.influenceForward;
float GetProxyRightX(EnvLightData value)
float3 GetInfluenceUp(EnvLightData value)
return value.proxyRightX;
return value.influenceUp;
float GetProxyRightY(EnvLightData value)
float3 GetInfluenceRight(EnvLightData value)
return value.proxyRightY;
return value.influenceRight;
float GetProxyRightZ(EnvLightData value)
float3 GetInfluenceExtents(EnvLightData value)
return value.proxyRightZ;
}
float GetInfluencePositionWSX(EnvLightData value)
{
return value.influencePositionWSX;
}
float GetInfluencePositionWSY(EnvLightData value)
{
return value.influencePositionWSY;
}
float GetInfluencePositionWSZ(EnvLightData value)
{
return value.influencePositionWSZ;
}
float GetInfluenceForwardX(EnvLightData value)
{
return value.influenceForwardX;
}
float GetInfluenceForwardY(EnvLightData value)
{
return value.influenceForwardY;
}
float GetInfluenceForwardZ(EnvLightData value)
{
return value.influenceForwardZ;
}
float GetInfluenceUpX(EnvLightData value)
{
return value.influenceUpX;
}
float GetInfluenceUpY(EnvLightData value)
{
return value.influenceUpY;
}
float GetInfluenceUpZ(EnvLightData value)
{
return value.influenceUpZ;
}
float GetInfluenceRightX(EnvLightData value)
{
return value.influenceRightX;
}
float GetInfluenceRightY(EnvLightData value)
{
return value.influenceRightY;
}
float GetInfluenceRightZ(EnvLightData value)
{
return value.influenceRightZ;
}
float GetInfluenceExtentsX(EnvLightData value)
{
return value.influenceExtentsX;
}
float GetInfluenceExtentsY(EnvLightData value)
{
return value.influenceExtentsY;
}
float GetInfluenceExtentsZ(EnvLightData value)
{
return value.influenceExtentsZ;
return value.influenceExtents;
float GetBlendDistancePositiveX(EnvLightData value)
{
return value.blendDistancePositiveX;
}
float GetBlendDistancePositiveY(EnvLightData value)
{
return value.blendDistancePositiveY;
}
float GetBlendDistancePositiveZ(EnvLightData value)
{
return value.blendDistancePositiveZ;
}
float GetBlendDistanceNegativeX(EnvLightData value)
{
return value.blendDistanceNegativeX;
}
float GetBlendDistanceNegativeY(EnvLightData value)
{
return value.blendDistanceNegativeY;
}
float GetBlendDistanceNegativeZ(EnvLightData value)
{
return value.blendDistanceNegativeZ;
}
float GetBlendNormalDistancePositiveX(EnvLightData value)
{
return value.blendNormalDistancePositiveX;
}
float GetBlendNormalDistancePositiveY(EnvLightData value)
{
return value.blendNormalDistancePositiveY;
}
float GetBlendNormalDistancePositiveZ(EnvLightData value)
{
return value.blendNormalDistancePositiveZ;
}
float GetBlendNormalDistanceNegativeX(EnvLightData value)
{
return value.blendNormalDistanceNegativeX;
}
float GetBlendNormalDistanceNegativeY(EnvLightData value)
{
return value.blendNormalDistanceNegativeY;
}
float GetBlendNormalDistanceNegativeZ(EnvLightData value)
{
return value.blendNormalDistanceNegativeZ;
}
float GetBoxSideFadePositiveX(EnvLightData value)
float3 GetBlendDistancePositive(EnvLightData value)
return value.boxSideFadePositiveX;
return value.blendDistancePositive;
float GetBoxSideFadePositiveY(EnvLightData value)
float3 GetBlendDistanceNegative(EnvLightData value)
return value.boxSideFadePositiveY;
return value.blendDistanceNegative;
float GetBoxSideFadePositiveZ(EnvLightData value)
float3 GetBlendNormalDistancePositive(EnvLightData value)
return value.boxSideFadePositiveZ;
return value.blendNormalDistancePositive;
float GetBoxSideFadeNegativeX(EnvLightData value)
float3 GetBlendNormalDistanceNegative(EnvLightData value)
return value.boxSideFadeNegativeX;
return value.blendNormalDistanceNegative;
float GetBoxSideFadeNegativeY(EnvLightData value)
float3 GetBoxSideFadePositive(EnvLightData value)
return value.boxSideFadeNegativeY;
return value.boxSideFadePositive;
float GetBoxSideFadeNegativeZ(EnvLightData value)
float3 GetBoxSideFadeNegative(EnvLightData value)
return value.boxSideFadeNegativeZ;
return value.boxSideFadeNegative;
}
float GetDimmer(EnvLightData value)
{

{
return value.unused01;
}
float GetSampleDirectionDiscardWSX(EnvLightData value)
{
return value.sampleDirectionDiscardWSX;
}
float GetSampleDirectionDiscardWSY(EnvLightData value)
{
return value.sampleDirectionDiscardWSY;
}
float GetSampleDirectionDiscardWSZ(EnvLightData value)
float3 GetSampleDirectionDiscardWS(EnvLightData value)
return value.sampleDirectionDiscardWSZ;
return value.sampleDirectionDiscardWS;
}
int GetEnvIndex(EnvLightData value)
{

#endif
#include "LightDefinition.cs.custom.hlsl"

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


};
// clustered light list specific buffers and data end
static int[] s_TempIntArray = new int[2]; // Used to avoid GC stress when calling SetComputeIntParams
static int[] s_TempScreenDimArray = new int[2]; // Used to avoid GC stress when calling SetComputeIntParams
FrameSettings m_FrameSettings = null;
RenderPipelineResources m_Resources = null;

m_CurrentSunLightShadowIndex = shadowIdx;
}
// TODO: Currently m_maxShadowDistance is based on shadow settings, but this value is define for a whole level. We should be able to change this value during gameplay
float scale;
float bias;
GetScaleAndBiasForLinearDistanceFade(m_maxShadowDistance, out scale, out bias);

if (additionalshadowData)
{
float shadowDistanceFade = ComputeLinearDistanceFade(distanceToCamera, additionalshadowData.shadowFadeDistance);
float shadowDistanceFade = ComputeLinearDistanceFade(distanceToCamera, Mathf.Min(shadowSettings.maxShadowDistance, additionalshadowData.shadowFadeDistance));
lightData.shadowDimmer = additionalshadowData.shadowDimmer * shadowDistanceFade;
}
else

{
// If any light require it, we need to enabled bake shadow mask feature
m_enableBakeShadowMask = false;
m_maxShadowDistance = shadowSettings.maxShadowDistance;
m_lightList.Clear();

}
UpdateDataBuffers();
m_maxShadowDistance = shadowSettings.maxShadowDistance;
return m_enableBakeShadowMask;
}

var w = (int)hdCamera.screenSize.x;
var h = (int)hdCamera.screenSize.y;
s_TempIntArray[0] = w;
s_TempIntArray[1] = h;
s_TempScreenDimArray[0] = w;
s_TempScreenDimArray[1] = h;
var numBigTilesX = (w + 63) / 64;
var numBigTilesY = (h + 63) / 64;

// enable coarse 2D pass on 64x64 tiles (used for both fptl and clustered).
if (m_FrameSettings.lightLoopSettings.enableBigTilePrepass)
{
cmd.SetComputeIntParam(buildPerBigTileLightListShader, HDShaderIDs.g_iNrVisibLights, m_lightCount);
cmd.SetComputeIntParams(buildPerBigTileLightListShader, HDShaderIDs.g_viDimensions, s_TempIntArray);
cmd.SetComputeIntParams(buildPerBigTileLightListShader, HDShaderIDs.g_viDimensions, s_TempScreenDimArray);
// TODO: These two aren't actually used...
cmd.SetComputeIntParam(buildPerBigTileLightListShader, HDShaderIDs.g_iNrVisibLights, m_lightCount);
cmd.SetComputeMatrixParam(buildPerBigTileLightListShader, HDShaderIDs.g_mScrProjection, projscrArr[0]);
cmd.SetComputeMatrixParam(buildPerBigTileLightListShader, HDShaderIDs.g_mInvScrProjection, invProjscrArr[0]);
cmd.SetComputeMatrixArrayParam(buildPerBigTileLightListShader, HDShaderIDs.g_mScrProjectionArr, projscrArr);
cmd.SetComputeMatrixArrayParam(buildPerBigTileLightListShader, HDShaderIDs.g_mInvScrProjectionArr, invProjscrArr);
cmd.SetComputeFloatParam(buildPerBigTileLightListShader, HDShaderIDs.g_fNearPlane, camera.nearClipPlane);
cmd.SetComputeFloatParam(buildPerBigTileLightListShader, HDShaderIDs.g_fFarPlane, camera.farClipPlane);

cmd.SetComputeBufferParam(buildPerBigTileLightListShader, s_GenListPerBigTileKernel, HDShaderIDs.g_data, s_ConvexBoundsBuffer);
cmd.DispatchCompute(buildPerBigTileLightListShader, s_GenListPerBigTileKernel, numBigTilesX, numBigTilesY, 1);
int tgZ = m_FrameSettings.enableStereo ? 2 : 1;
cmd.DispatchCompute(buildPerBigTileLightListShader, s_GenListPerBigTileKernel, numBigTilesX, numBigTilesY, tgZ);
}
var numTilesX = GetNumTileFtplX(hdCamera);

if (m_FrameSettings.lightLoopSettings.isFptlEnabled)
{
cmd.SetComputeIntParam(buildPerTileLightListShader, HDShaderIDs.g_isOrthographic, isOrthographic ? 1 : 0);
cmd.SetComputeIntParams(buildPerTileLightListShader, HDShaderIDs.g_viDimensions, s_TempIntArray);
cmd.SetComputeIntParams(buildPerTileLightListShader, HDShaderIDs.g_viDimensions, s_TempScreenDimArray);
cmd.SetComputeIntParam(buildPerTileLightListShader, HDShaderIDs._EnvLightIndexShift, m_lightList.lights.Count);
cmd.SetComputeIntParam(buildPerTileLightListShader, HDShaderIDs._DecalIndexShift, m_lightList.lights.Count + m_lightList.envLights.Count);
cmd.SetComputeIntParam(buildPerTileLightListShader, HDShaderIDs.g_iNrVisibLights, m_lightCount);

}
cmd.SetComputeIntParam(buildMaterialFlagsShader, HDShaderIDs.g_BaseFeatureFlags, (int)baseFeatureFlags);
cmd.SetComputeIntParams(buildMaterialFlagsShader, HDShaderIDs.g_viDimensions, s_TempIntArray);
cmd.SetComputeIntParams(buildMaterialFlagsShader, HDShaderIDs.g_viDimensions, s_TempScreenDimArray);
cmd.SetComputeBufferParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, s_TileFeatureFlags);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, stencilTextureRT);

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


#include "LightLoop.cs.hlsl"
#include "LightingConvexHullUtils.hlsl"
#include "SortingComputeUtils.hlsl"
#include "LightCullUtils.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal

uniform int g_iNrVisibLights;
uniform uint2 g_viDimensions;
uniform float4x4 g_mInvScrProjection;
uniform float4x4 g_mScrProjection;
uniform float4x4 g_mInvScrProjectionArr[2];
uniform float4x4 g_mScrProjectionArr[2];
// TODO: These aren't used, we should remove them
uniform int _EnvLightIndexShift;
uniform int _DecalIndexShift;

groupshared unsigned int lightsListLDS[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE];
groupshared uint lightOffs;
// TODO: Remove this function and g_mInvScrProjectionArr from constants.
// Only usage of that constant.
float4x4 g_mInvScrProjection = g_mInvScrProjectionArr[0];
// for perspective projection m22 is zero and m23 is +1/-1 (depends on left/right hand proj)
// however this function must also work for orthographic projection so we keep it like this.
float m22 = g_mInvScrProjection[2].z, m23 = g_mInvScrProjection[2].w;

//return v4Pres.z / v4Pres.w;
}
float3 GetViewPosFromLinDepth(float2 v2ScrPos, float fLinDepth)
float3 GetViewPosFromLinDepth(float2 v2ScrPos, float fLinDepth, uint eyeIndex)
float4x4 g_mScrProjection = g_mScrProjectionArr[eyeIndex];
bool isOrthographic = g_isOrthographic!=0;
float fSx = g_mScrProjection[0].x;
float fSy = g_mScrProjection[1].y;

return float3(isOrthographic ? p.xy : (fLinDepth*p.xy), fLinDepth);
}
float GetOnePixDiagWorldDistAtDepthOne()
float GetOnePixDiagWorldDistAtDepthOne(uint eyeIndex)
float4x4 g_mScrProjection = g_mScrProjectionArr[eyeIndex];
float fSx = g_mScrProjection[0].x;
float fSy = g_mScrProjection[1].y;

#ifdef PERFORM_SPHERICAL_INTERSECTION_TESTS
void SphericalIntersectionTests(uint threadID, int iNrCoarseLights, float2 screenCoordinate);
void SphericalIntersectionTests(uint threadID, int iNrCoarseLights, float2 screenCoordinate, uint eyeIndex);
void CullByExactEdgeTests(uint threadID, int iNrCoarseLights, uint2 viTilLL, uint2 viTilUR);
void CullByExactEdgeTests(uint threadID, int iNrCoarseLights, uint2 viTilLL, uint2 viTilUR, uint eyeIndex);
#endif

void BigTileLightListGen(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID)
{
uint eyeIndex = u3GroupID.z;
uint2 tileIDX = u3GroupID.xy;
uint t=threadID;

GroupMemoryBarrierWithGroupSync();
#endif
// Raw pixel coordinates of tile
// 'Normalized' coordinates of tile
float2 vTileLL = float2(viTilLL.x/(float) iWidth, viTilLL.y/(float) iHeight);
float2 vTileUR = float2(viTilUR.x/(float) iWidth, viTilUR.y/(float) iHeight);

const float2 vMi = g_vBoundsBuffer[l].xy;
const float2 vMa = g_vBoundsBuffer[l+g_iNrVisibLights].xy;
const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(l, g_iNrVisibLights, eyeIndex);
const float2 vMi = g_vBoundsBuffer[boundsIndices.min].xy;
const float2 vMa = g_vBoundsBuffer[boundsIndices.max].xy;
if( all(vMa>vTileLL) && all(vMi<vTileUR))
{

if(uIndex<MAX_NR_BIGTILE_LIGHTS) lightsListLDS[uIndex] = l; // add to light list
}
}

int iNrCoarseLights = min(lightOffs,MAX_NR_BIGTILE_LIGHTS);
#ifdef PERFORM_SPHERICAL_INTERSECTION_TESTS
SphericalIntersectionTests( t, iNrCoarseLights, float2(min(viTilLL.xy+uint2(64/2,64/2), uint2(iWidth-1, iHeight-1))) );
SphericalIntersectionTests( t, iNrCoarseLights, float2(min(viTilLL.xy+uint2(64/2,64/2), uint2(iWidth-1, iHeight-1))), eyeIndex );
CullByExactEdgeTests(t, iNrCoarseLights, viTilLL.xy, viTilUR.xy);
CullByExactEdgeTests(t, iNrCoarseLights, viTilLL.xy, viTilUR.xy, eyeIndex);
#endif

GroupMemoryBarrierWithGroupSync();
iNrCoarseLights = lightOffs;
int offs = tileIDX.y*nrBigTilesX + tileIDX.x;
int offs = tileIDX.y*nrBigTilesX + tileIDX.x + (eyeIndex * nrBigTilesX * nrBigTilesY);
for(i=t; i<(iNrCoarseLights+1); i+=NR_THREADS)
g_vLightList[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE*offs + i] = i==0 ? iNrCoarseLights : lightsListLDS[max(i-1, 0)];

#ifdef PERFORM_SPHERICAL_INTERSECTION_TESTS
void SphericalIntersectionTests(uint threadID, int iNrCoarseLights, float2 screenCoordinate)
void SphericalIntersectionTests(uint threadID, int iNrCoarseLights, float2 screenCoordinate, uint eyeIndex)
float3 V = GetViewPosFromLinDepth( screenCoordinate, 1.0);
float3 V = GetViewPosFromLinDepth( screenCoordinate, 1.0, eyeIndex);
float3 V = GetViewPosFromLinDepth( screenCoordinate, -1.0);
float3 V = GetViewPosFromLinDepth( screenCoordinate, -1.0, eyeIndex);
float onePixDiagDist = GetOnePixDiagWorldDistAtDepthOne();
float onePixDiagDist = GetOnePixDiagWorldDistAtDepthOne(eyeIndex);
SFiniteLightBound lgtDat = g_data[lightsListLDS[l]];
const int boundIndex = GenerateLightCullDataIndex(lightsListLDS[l], g_iNrVisibLights, eyeIndex);
SFiniteLightBound lgtDat = g_data[boundIndex];
if( !DoesSphereOverlapTile(V, halfTileSizeAtZDistOne, lgtDat.center.xyz, lgtDat.radius, g_isOrthographic!=0) )
lightsListLDS[l]=UINT_MAX;

#ifdef EXACT_EDGE_TESTS
float3 GetTileVertex(uint2 viTilLL, uint2 viTilUR, int i, float fTileFarPlane)
float3 GetTileVertex(uint2 viTilLL, uint2 viTilUR, int i, float fTileFarPlane, uint eyeIndex)
{
float x = (i&1)==0 ? viTilLL.x : viTilUR.x;
float y = (i&2)==0 ? viTilLL.y : viTilUR.y;

#endif
return GetViewPosFromLinDepth( float2(x, y), z);
return GetViewPosFromLinDepth( float2(x, y), z, eyeIndex);
void GetFrustEdge(out float3 vP0, out float3 vE0, const int e0, uint2 viTilLL, uint2 viTilUR, float fTileFarPlane)
void GetFrustEdge(out float3 vP0, out float3 vE0, const int e0, uint2 viTilLL, uint2 viTilUR, float fTileFarPlane, uint eyeIndex)
vP0 = GetTileVertex(uint2(viTilLL.x, viTilUR.y), uint2(viTilUR.x, viTilLL.y), i, fTileFarPlane);
vP0 = GetTileVertex(uint2(viTilLL.x, viTilUR.y), uint2(viTilUR.x, viTilLL.y), i, fTileFarPlane, eyeIndex);
#if USE_LEFT_HAND_CAMERA_SPACE
float3 edgeSectionZero = g_isOrthographic==0 ? vP0 : float3(0.0,0.0,1.0);

vE0 = iSection == 0 ? edgeSectionZero : (((iSwizzle & 0x2) == 0 ? 1.0f : (-1.0f)) * ((int)(iSwizzle & 0x1) == (iSwizzle >> 1) ? float3(1, 0, 0) : float3(0, 1, 0)));
}
void CullByExactEdgeTests(uint threadID, int iNrCoarseLights, uint2 viTilLL, uint2 viTilUR)
void CullByExactEdgeTests(uint threadID, int iNrCoarseLights, uint2 viTilLL, uint2 viTilUR, uint eyeIndex)
{
const bool bOnlyNeedFrustumSideEdges = true;
const int nrFrustEdges = bOnlyNeedFrustumSideEdges ? 4 : 8; // max 8 since we never need to test 4 far edges of frustum since they are identical vectors to near edges and plane is placed at vP0 on light hull.

{
const uint idxCoarse = lightsListLDS[l];
const int bufIdxCoarse = GenerateLightCullDataIndex(idxCoarse, g_iNrVisibLights, eyeIndex);
if(canEnter) canEnter = _LightVolumeData[idxCoarse].lightVolume != LIGHTVOLUMETYPE_SPHERE; // don't bother doing edge tests for sphere lights since these have camera aligned bboxes.
if(canEnter) canEnter = _LightVolumeData[bufIdxCoarse].lightVolume != LIGHTVOLUMETYPE_SPHERE; // don't bother doing edge tests for sphere lights since these have camera aligned bboxes.
SFiniteLightBound lgtDat = g_data[idxCoarse];
SFiniteLightBound lgtDat = g_data[bufIdxCoarse];
const float3 boxX = lgtDat.boxAxisX.xyz;
const float3 boxY = lgtDat.boxAxisY.xyz;

float3 vP1, vE1;
GetFrustEdge(vP1, vE1, e1, viTilLL, viTilUR, g_fFarPlane);
GetFrustEdge(vP1, vE1, e1, viTilLL, viTilUR, g_fFarPlane, eyeIndex);
// potential separation plane
float3 vN = cross(vE0, vE1);

positive=0; negative=0;
for(int j=0; j<8; j++)
{
float3 vPf = GetTileVertex(viTilLL, viTilUR, j, g_fFarPlane);
float3 vPf = GetTileVertex(viTilLL, viTilUR, j, g_fFarPlane, eyeIndex);
float fSignDist = dot(vN, vPf-vP0);
if(fSignDist>0) ++positive; else if(fSignDist<0) ++negative;
}

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


#include "CoreRP/ShaderLibrary/common.hlsl"
#include "LightLoop.cs.hlsl"
#include "LightCullUtils.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal

const int lgtIndex = subLigt+(int) g*8;
const int sideIndex = (int) (t%8);
const int eyeAdjustedLgtIndex = lgtIndex + (eyeIndex * g_iNrVisibLights);
const int eyeAdjustedLgtIndex = GenerateLightCullDataIndex(lgtIndex, g_iNrVisibLights, eyeIndex);
SFiniteLightBound lgtDat = g_data[eyeAdjustedLgtIndex];
const float3 boxX = lgtDat.boxAxisX.xyz;

// Each light's AABB is represented by two float3s, the min and max of the box.
// And for stereo, we have two sets of lights. Therefore, each eye has a set of mins, followed by
// a set of maxs, and each set is equal to g_iNrVisibLights.
const int eyeBaseIndex = eyeIndex * g_iNrVisibLights * 2;
const int minIndex = eyeBaseIndex + lgtIndex + 0;
const int maxIndex = eyeBaseIndex + lgtIndex + (int)g_iNrVisibLights;
g_vBoundsBuffer[minIndex] = float3(0.5*vMin.x + 0.5, 0.5*vMin.y + 0.5, vMin.z*VIEWPORT_SCALE_Z);
g_vBoundsBuffer[maxIndex] = float3(0.5*vMax.x + 0.5, 0.5*vMax.y + 0.5, vMax.z*VIEWPORT_SCALE_Z);
const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(lgtIndex, g_iNrVisibLights, eyeIndex);
g_vBoundsBuffer[boundsIndices.min] = float3(0.5*vMin.x + 0.5, 0.5*vMin.y + 0.5, vMin.z*VIEWPORT_SCALE_Z);
g_vBoundsBuffer[boundsIndices.max] = float3(0.5*vMax.x + 0.5, 0.5*vMax.y + 0.5, vMax.z*VIEWPORT_SCALE_Z);
}
}
}

21
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtilities.hlsl


#include "LightDefinition.cs.hlsl"
#define SETTER_FLOAT3(data, field, value)\
data.##field##X = value.x;\
data.##field##Y = value.y;\
data.##field##Z = value.z
// The EnvLightData of the sky light contains a bunch of compile-time constants.
// This function sets them directly to allow the compiler to propagate them and optimize the code.
EnvLightData InitSkyEnvLightData(int envIndex)

output.influenceShapeType = ENVSHAPETYPE_SKY;
output.envIndex = envIndex;
SETTER_FLOAT3(output, influenceForward, float3(0.0, 0.0, 1.0));
SETTER_FLOAT3(output, influenceUp, float3(0.0, 1.0, 0.0));
SETTER_FLOAT3(output, influenceRight, float3(1.0, 0.0, 0.0));
SETTER_FLOAT3(output, influencePositionWS, float3(0.0, 0.0, 0.0));
output.influenceForward = float3(0.0, 0.0, 1.0);
output.influenceUp = float3(0.0, 1.0, 0.0);
output.influenceRight = float3(1.0, 0.0, 0.0);
output.influencePositionWS = float3(0.0, 0.0, 0.0);
SETTER_FLOAT3(output, proxyForward, float3(0.0, 0.0, 1.0));
SETTER_FLOAT3(output, proxyUp, float3(0.0, 1.0, 0.0));
SETTER_FLOAT3(output, proxyRight, float3(1.0, 0.0, 0.0));
output.proxyForward = float3(0.0, 0.0, 1.0);
output.proxyUp = float3(0.0, 1.0, 0.0);
output.proxyRight = float3(1.0, 0.0, 0.0);
#undef SETTER_FLOAT3
#endif // UNITY_LIGHT_UTILITIES_INCLUDED

16
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtils.cs


}
// convert intensity (lumen) to nits
public static float calculateLineLightArea(float intensity, float lineWidth)
public static float CalculateLineLightIntensity(float intensity, float lineWidth)
// The area of a cylinder is this:
// float lineRadius = 0.01f; // 1cm
//return intensity / (2.0f * Mathf.PI * lineRadius * lineWidth * Mathf.PI);
// But with our current line light algorithm we get an insane gap in intensity
// following formula (fully empirical) give a better match to a rect light of 1cm of width.
// It is basically point light intensity / line width.
// Line lights in the shader expect intensity (W / sr).
// In the UI, we specify luminous flux(power) in lumens.
// First, it needs to be converted to radiometric units(radiant flux, W).
// Then we must recall how to compute power from intensity for a line light:
// power = Integral{length, Integral{sphere, intensity}}.
// For an isotropic line light, intensity is constant, so
// power = length * (4 * Pi) * intensity,
// intensity = power / (length * (4 * Pi)).
return intensity / (4.0f * Mathf.PI * lineWidth);
}
}

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ReflectionProbeCache.cs


bool formatMismatch = cubeTexture.format != TextureFormat.RGBAHalf; // Temporary RT for convolution is always FP16
if (formatMismatch || sizeMismatch)
{
// We comment the following warning as they have no impact on the result but spam the console, it is just that we waste offline time and a bit of quality for nothing.
Debug.LogWarningFormat("Baked Reflection Probe {0} does not match HDRP Reflection Probe Cache size of {1}. Consider baking it at the same size for better loading performance.", texture.name, m_ProbeSize);
// Debug.LogWarningFormat("Baked Reflection Probe {0} does not match HDRP Reflection Probe Cache size of {1}. Consider baking it at the same size for better loading performance.", texture.name, m_ProbeSize);
Debug.LogWarningFormat("Baked Reflection Probe {0} is compressed but the HDRP Reflection Probe Cache is not. Consider removing compression from the input texture for better quality.", texture.name);
// Debug.LogWarningFormat("Baked Reflection Probe {0} is compressed but the HDRP Reflection Probe Cache is not. Consider removing compression from the input texture for better quality.", texture.name);
}
ConvertTexture(cmd, cubeTexture, m_TempRenderTexture);
}

48
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/VolumeProjection.hlsl


{
return transpose(
float3x3(
GetProxyRight(lightData),
GetProxyUp(lightData),
GetProxyForward(lightData)
lightData.proxyRight,
lightData.proxyUp,
lightData.proxyForward
)
); // worldToLocal assume no scaling
}

float3 positionPS = positionWS - GetProxyPositionWS(lightData);
float3 positionPS = positionWS - lightData.proxyPositionWS;
positionPS = mul(positionPS, worldToPS).xyz;
return positionPS;
}

float sphereOuterDistance = lightData.proxyExtentsX;
float sphereOuterDistance = lightData.proxyExtents.x;
float projectionDistance = IntersectRaySphereSimple(positionPS, dirPS, sphereOuterDistance);
projectionDistance = max(projectionDistance, lightData.minProjectionDistance); // Setup projection to infinite if requested (mean no projection shape)

float IntersectBoxProxy(EnvLightData lightData, float3 dirPS, float3 positionPS)
{
float3 boxOuterDistance = GetProxyExtents(lightData);
float3 boxOuterDistance = lightData.proxyExtents;
float projectionDistance = IntersectRayAABBSimple(positionPS, dirPS, -boxOuterDistance, boxOuterDistance);
projectionDistance = max(projectionDistance, lightData.minProjectionDistance); // Setup projection to infinite if requested (mean no projection shape)

float InfluenceSphereWeight(EnvLightData lightData, BSDFData bsdfData, float3 positionWS, float3 positionLS, float3 dirLS)
{
float lengthPositionLS = length(positionLS);
float sphereInfluenceDistance = lightData.influenceExtentsX - lightData.blendDistancePositiveX;
float sphereInfluenceDistance = lightData.influenceExtents.x - lightData.blendDistancePositive.x;
float alpha = saturate(1.0 - distFade / max(lightData.blendDistancePositiveX, 0.0001)); // avoid divide by zero
float alpha = saturate(1.0 - distFade / max(lightData.blendDistancePositive.x, 0.0001)); // avoid divide by zero
float insideInfluenceNormalVolume = lengthPositionLS <= (lightData.influenceExtentsX - lightData.blendNormalDistancePositiveX) ? 1.0 : 0.0;
float insideWeight = InfluenceFadeNormalWeight(bsdfData.normalWS, normalize(positionWS - GetCapturePositionWS(lightData)));
float insideInfluenceNormalVolume = lengthPositionLS <= (lightData.influenceExtents.x - lightData.blendNormalDistancePositive.x) ? 1.0 : 0.0;
float insideWeight = InfluenceFadeNormalWeight(bsdfData.normalWS, normalize(positionWS - lightData.capturePositionWS));
alpha *= insideInfluenceNormalVolume ? 1.0 : insideWeight;
#endif

float InfluenceBoxWeight(EnvLightData lightData, BSDFData bsdfData, float3 positionWS, float3 positionIS, float3 dirIS)
{
float3 influenceExtents = GetInfluenceExtents(lightData);
float3 influenceExtents = lightData.influenceExtents;
// 2. Process the position influence
// Calculate falloff value, so reflections on the edges of the volume would gradually blend to previous reflection.
#if defined(ENVMAP_FEATURE_PERFACEINFLUENCE) || defined(ENVMAP_FEATURE_INFLUENCENORMAL) || defined(ENVMAP_FEATURE_PERFACEFADE)

#if defined(ENVMAP_FEATURE_PERFACEINFLUENCE)
// Influence falloff for each face
float3 negativeFalloff = negativeDistance / max(0.0001, GetBlendDistanceNegative(lightData));
float3 positiveFalloff = positiveDistance / max(0.0001, GetBlendDistancePositive(lightData));
float3 negativeFalloff = negativeDistance / max(0.0001, lightData.blendDistanceNegative);
float3 positiveFalloff = positiveDistance / max(0.0001, lightData.blendDistancePositive);
// Fallof is the min for all faces
float influenceFalloff = min(

float alpha = saturate(influenceFalloff);
#else
float distFace = DistancePointBox(positionIS, -influenceExtents + lightData.blendDistancePositiveX, influenceExtents - lightData.blendDistancePositiveX);
float alpha = saturate(1.0 - distFace / max(lightData.blendDistancePositiveX, 0.0001));
float distFace = DistancePointBox(positionIS, -influenceExtents + lightData.blendDistancePositive.x, influenceExtents - lightData.blendDistancePositive.x);
float alpha = saturate(1.0 - distFace / max(lightData.blendDistancePositive.x, 0.0001));
float3 belowPositiveInfluenceNormalVolume = positiveDistance / max(0.0001, GetBlendNormalDistancePositive(lightData));
float3 aboveNegativeInfluenceNormalVolume = negativeDistance / max(0.0001, GetBlendNormalDistanceNegative(lightData));
float3 belowPositiveInfluenceNormalVolume = positiveDistance / max(0.0001, lightData.blendNormalDistancePositive);
float3 aboveNegativeInfluenceNormalVolume = negativeDistance / max(0.0001, lightData.blendNormalDistanceNegative);
float insideWeight = InfluenceFadeNormalWeight(bsdfData.normalWS, normalize(positionWS - GetCapturePositionWS(lightData)));
float insideWeight = InfluenceFadeNormalWeight(bsdfData.normalWS, normalize(positionWS - lightData.capturePositionWS));
alpha *= insideInfluenceNormalVolume ? 1.0 : insideWeight;
#endif

// We consider R.x as cos(X) and then fade as angle from 60°(=acos(1/2)) to 75°(=acos(1/4))
// For positive axes: axisFade = (R - 1/4) / (1/2 - 1/4)
// <=> axisFace = 4 * R - 1;
float3 faceFade = saturate((4 * dirIS - 1) * GetBoxSideFadePositive(lightData))
+ saturate((-4 * dirIS - 1) * GetBoxSideFadeNegative(lightData));
float3 faceFade = saturate((4 * dirIS - 1) * lightData.boxSideFadePositive)
+ saturate((-4 * dirIS - 1) * lightData.boxSideFadeNegative);
alpha *= saturate(faceFade.x + faceFade.y + faceFade.z);
#endif

{
return transpose(
float3x3(
GetInfluenceRight(lightData),
GetInfluenceUp(lightData),
GetInfluenceForward(lightData)
lightData.influenceRight,
lightData.influenceUp,
lightData.influenceForward
)
); // worldToLocal assume no scaling
}

float3 positionIS = positionWS - GetInfluencePositionWS(lightData);
float3 positionIS = positionWS - lightData.influencePositionWS;
positionIS = mul(positionIS, worldToIS).xyz;
return positionIS;
}

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


// PackingRules = Exact
struct DecalData
{
float4x4 worldToDecal;
float4x4 worldToDecal;
float4x4 normalToWorld;
};

float4x4 GetWorldToDecal(DecalData value)
{
return value.worldToDecal;
}
float4x4 GetNormalToWorld(DecalData value)
{
return value.normalToWorld;

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.shader


Shader "HDRenderPipeline/Decal"
{
Properties
{
{
_MaskMap("MaskMap", 2D) = "white" {}
_MaskMap("MaskMap", 2D) = "white" {}
_DecalBlend("_DecalBlend", Range(0.0, 1.0)) = 0.5
}

//-------------------------------------------------------------------------------------
// Define
//-------------------------------------------------------------------------------------
#define UNITY_MATERIAL_DECAL
#define UNITY_MATERIAL_DECAL
//-------------------------------------------------------------------------------------
// Include
//-------------------------------------------------------------------------------------

SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline"}
Pass
{
Name "DBuffer" // Name is not used

#define SHADERPASS SHADERPASS_DBUFFER
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"

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


return _DecalDatas[j];
}
// Caution: We can't compute LOD inside a dynamic loop. The gradient are not accessible.
// we need to find a way to calculate mips. For now just fetch first mip of the decals
src.xyz = mul(decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D_ARRAY(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex))) * 0.5f + 0.5f;
src.xyz = mul(decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, 0 /* ComputeTextureLOD(texCoords) */))) * 0.5f + 0.5f;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);

void ApplyBlendDiffuse(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float blend)
{
float4 src = SAMPLE_TEXTURE2D_ARRAY(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex);
float4 src = SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, 0 /* ComputeTextureLOD(texCoords) */);
src.w *= blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);

void ApplyBlendMask(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float blend)
{
float4 src = SAMPLE_TEXTURE2D_ARRAY(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex);
float4 src = SAMPLE_TEXTURE2D_ARRAY_LOD(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex, 0 /* ComputeTextureLOD(texCoords) */);
src.z = src.w;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);

{
if(_EnableDBuffer)
{
DecalSurfaceData decalSurfaceData;
DecalSurfaceData decalSurfaceData;
int mask = 0;
// the code in the macros, gets moved inside the conditionals by the compiler
FETCH_DBUFFER(DBuffer, _DBufferTexture, posInput.positionSS);

decalStart = 0;
#endif
float3 positionWS = GetAbsolutePositionWS(posInput.positionWS);
uint i = 0;
uint i = 0;
DecalData decalData = FetchDecal(decalStart, i);
DecalData decalData = FetchDecal(decalStart, i);
float3 positionDS = mul(decalData.worldToDecal, float4(positionWS, 1.0)).xyz;
positionDS = positionDS * float3(1.0, -1.0, 1.0) + float3(0.5, 0.0f, 0.5);
float decalBlend = decalData.normalToWorld[0][3];

}
}
#else
mask = UnpackByte(LOAD_TEXTURE2D(_DecalHTileTexture, posInput.positionSS / 8));
mask = UnpackByte(LOAD_TEXTURE2D(_DecalHTileTexture, posInput.positionSS / 8).r);
DECODE_FROM_DBUFFER(DBuffer, decalSurfaceData);
DECODE_FROM_DBUFFER(DBuffer, decalSurfaceData);
if(mask & DBUFFERHTILEBIT_NORMAL)
{
surfaceData.normalWS.xyz = normalize(surfaceData.normalWS.xyz * decalSurfaceData.normalWS.w + decalSurfaceData.normalWS.xyz);

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/GGXConvolve.shader


{
SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
Cull Off

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


SubShader
{
// This tags allow to use the shader replacement features
Tags{ "RenderType" = "HDLitShader" }
Tags{ "RenderPipeline" = "HDRenderPipeline" "RenderType" = "HDLitShader" }
// Caution: The outline selection in the editor use the vertex shader/hull/domain shader of the first pass declare. So it should not bethe meta pass.
Pass

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


SubShader
{
// This tags allow to use the shader replacement features
Tags{ "RenderType" = "HDLitShader" }
Tags{ "RenderPipeline" = "HDRenderPipeline" "RenderType" = "HDLitShader" }
// Caution: The outline selection in the editor use the vertex shader/hull/domain shader of the first pass declare. So it should not bethe meta pass.
Pass

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


{
projectionDistance = IntersectSphereProxy(lightData, dirPS, positionPS);
// We can reuse dist calculate in LS directly in WS as there is no scaling. Also the offset is already include in lightData.capturePositionWS
float3 capturePositionWS = GetCapturePositionWS(lightData);
float3 capturePositionWS = lightData.capturePositionWS;
R = (positionWS + projectionDistance * R) - capturePositionWS;
// Test again for clear coat

projectionDistance = IntersectBoxProxy(lightData, dirPS, positionPS);
// No need to normalize for fetching cubemap
// We can reuse dist calculate in LS directly in WS as there is no scaling. Also the offset is already include in lightData.capturePositionWS
float3 capturePositionWS = GetCapturePositionWS(lightData);
float3 capturePositionWS = lightData.capturePositionWS;
R = (positionWS + projectionDistance * R) - capturePositionWS;
// TODO: add distance based roughness

float roughness = PerceptualRoughnessToRoughness(preLightData.iblPerceptualRoughness);
R = lerp(R, preLightData.iblR, saturate(smoothstep(0, 1, roughness * roughness)));
float3 sampleDirectionDiscardWS = GetSampleDirectionDiscardWS(lightData);
float3 sampleDirectionDiscardWS = lightData.sampleDirectionDiscardWS;
if (dot(sampleDirectionDiscardWS, R) < 0)
return lighting;

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


SubShader
{
// This tags allow to use the shader replacement features
Tags{ "RenderType" = "HDLitShader" }
Tags{ "RenderPipeline"="HDRenderPipeline" "RenderType" = "HDLitShader" }
// Caution: The outline selection in the editor use the vertex shader/hull/domain shader of the first pass declare. So it should not bethe meta pass.
Pass

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


SubShader
{
// This tags allow to use the shader replacement features
Tags{ "RenderType" = "HDLitShader" }
Tags{ "RenderPipeline" = "HDRenderPipeline" "RenderType" = "HDLitShader" }
// Caution: The outline selection in the editor use the vertex shader/hull/domain shader of the first pass declare. So it should not bethe meta pass.
Pass

7
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Resources/PreIntegratedFGD.shader


Shader "Hidden/HDRenderPipeline/PreIntegratedFGD"
{
SubShader {
Pass {
SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
ZTest Always Cull Off ZWrite Off
HLSLPROGRAM

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitDepthPass.hlsl


#endif
// About UV
// If we have a lit shader, only the UV0 is available for opacity or heightmap
// If we have a layered shader, any UV can be use for this. To reduce the number of variant we groupt UV0/UV1 and UV2/UV3 instead of having variant for UV0/UV1/UV2/UV3
#define ATTRIBUTES_NEED_TEXCOORD0
#ifdef LAYERED_LIT_SHADER
#define ATTRIBUTES_NEED_TEXCOORD0
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#endif
#if defined(_REQUIRE_UV3)
#endif
#if defined(_REQUIRE_UV3)
#endif
#endif
#endif

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitDistortionPass.hlsl


#endif
// About UV
// If we have a lit shader, only the UV0 is available for opacity or heightmap
// If we have a layered shader, any UV can be use for this. To reduce the number of variant we groupt UV0/UV1 and UV2/UV3 instead of having variant for UV0/UV1/UV2/UV3
#ifdef LAYERED_LIT_SHADER
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#endif
#if defined(_REQUIRE_UV3)
#endif
#if defined(_REQUIRE_UV3)
#endif
#endif
#endif

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/ShaderPass/LitVelocityPass.hlsl


#endif
// About UV
// If we have a lit shader, only the UV0 is available for opacity or heightmap
// If we have a layered shader, any UV can be use for this. To reduce the number of variant we groupt UV0/UV1 and UV2/UV3 instead of having variant for UV0/UV1/UV2/UV3
#define ATTRIBUTES_NEED_TEXCOORD0
#ifdef LAYERED_LIT_SHADER
#define ATTRIBUTES_NEED_TEXCOORD0
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)
#endif
#if defined(_REQUIRE_UV3)
#endif
#if defined(_REQUIRE_UV3)
#endif
#endif
#endif

15
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/MaterialUtilities.hlsl


#ifdef UNITY_LIGHTMAP_FULL_HDR
bool useRGBMLightmap = false;
float4 decodeInstructions = float4(0.0, 0.0, 0.0, 0.0); // Never used but needed for the interface since it supports gamma lightmaps
#if defined(UNITY_LIGHTMAP_RGBM_ENCODING)
float4 decodeInstructions = float4(34.493242, 2.2, 0.0, 0.0); // range^2.2 = 5^2.2, gamma = 2.2
#else
float4 decodeInstructions = float4(0.0, 0.0, 0.0, 0.0); // range = 2.0^2.2 = 4.59
#endif
#endif
#ifdef LIGHTMAP_ON

uvStaticLightmap, unity_LightmapST, normalWS, useRGBMLightmap);
uvStaticLightmap, unity_LightmapST, normalWS, useRGBMLightmap, decodeInstructions);
bakeDiffuseLighting += SampleSingleLightmap(TEXTURE2D_PARAM(unity_Lightmap, samplerunity_Lightmap), uvStaticLightmap, unity_LightmapST, useRGBMLightmap);
bakeDiffuseLighting += SampleSingleLightmap(TEXTURE2D_PARAM(unity_Lightmap, samplerunity_Lightmap), uvStaticLightmap, unity_LightmapST, useRGBMLightmap, decodeInstructions);
float4 decodeInstructions = float4(0.0, 0.0, 0.0, 0.0); // Never used but needed for the interface since it supports gamma lightmaps
uvDynamicLightmap, unity_DynamicLightmapST, normalWS, false);
uvDynamicLightmap, unity_DynamicLightmapST, normalWS, false, decodeInstructions);
bakeDiffuseLighting += SampleSingleLightmap(TEXTURE2D_PARAM(unity_DynamicLightmap, samplerunity_DynamicLightmap), uvDynamicLightmap, unity_DynamicLightmapST, false);
bakeDiffuseLighting += SampleSingleLightmap(TEXTURE2D_PARAM(unity_DynamicLightmap, samplerunity_DynamicLightmap), uvDynamicLightmap, unity_DynamicLightmapST, false, decodeInstructions);
#endif
#endif

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/CombineLighting.shader


SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
Stencil

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.shader


SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
Stencil

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


SubShader
{
// This tags allow to use the shader replacement features
Tags{ "RenderType" = "HDUnlitShader" }
Tags{ "RenderPipeline" = "HDRenderPipeline" "RenderType" = "HDUnlitShader" }
// Caution: The outline selection in the editor use the vertex shader/hull/domain shader of the first pass declare. So it should not be the meta pass.

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


SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
// 0: Nearest
Pass
{

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CameraMotionVectors.shader


SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
// We will perform camera motion velocity only where there is no object velocity

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CopyDepthBuffer.shader


SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
Name "Copy Depth"

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/CopyStencilBuffer.shader


SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" }
Pass
{
Name "Pass 0 - Copy stencilRef to output"

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset


GGXConvolve: {fileID: 4800000, guid: 123ed592ad5c2494b8aed301fd609e7b, type: 3}
opaqueAtmosphericScattering: {fileID: 4800000, guid: 326059e48e5735e46a98047eff4f0295,
type: 3}
hdriSky: {fileID: 4800000, guid: 9bd32a6ece529fd4f9408b8d7e00c10d, type: 3}
proceduralSky: {fileID: 4800000, guid: ec63f47fd265df243a7b1d40f9ef7fe7, type: 3}
skyboxCubemap: {fileID: 103, guid: 0000000000000000f000000000000000, type: 0}
encodeBC6HCS: {fileID: 7200000, guid: aa922d239de60304f964e24488559eeb, type: 3}
cubeToPanoShader: {fileID: 4800000, guid: 595434cc3b6405246b6cd3086d0b6f7d, type: 3}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/RenderPipelineResources.cs


public ComputeShader computeGgxIblSampleData;
public Shader GGXConvolve;
public Shader opaqueAtmosphericScattering;
public Shader hdriSky;
public Shader proceduralSky;
public Shader skyboxCubemap;

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISky.cs


public class HDRISky : SkySettings
{
[Tooltip("Cubemap used to render the sky.")]
public CubemapParameter skyHDRI = new CubemapParameter(null);
public CubemapParameter hdriSky = new CubemapParameter(null);
public override SkyRenderer CreateRenderer()
{

unchecked
{
hash = skyHDRI.value != null ? hash * 23 + skyHDRI.GetHashCode() : hash;
hash = hdriSky.value != null ? hash * 23 + hdriSky.GetHashCode() : hash;
}
return hash;

7
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISkyRenderer.cs


using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class HDRISkyRenderer : SkyRenderer

public override void Build()
{
m_SkyHDRIMaterial = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/Sky/SkyHDRI");
var hdrp = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;
m_SkyHDRIMaterial = CoreUtils.CreateEngineMaterial(hdrp.renderPipelineResources.hdriSky);
}
public override void Cleanup()

public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap)
{
m_SkyHDRIMaterial.SetTexture(HDShaderIDs._Cubemap, m_HdriSkyParams.skyHDRI);
m_SkyHDRIMaterial.SetTexture(HDShaderIDs._Cubemap, m_HdriSkyParams.hdriSky);
m_SkyHDRIMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_HdriSkyParams.exposure, m_HdriSkyParams.multiplier, -m_HdriSkyParams.rotation, 0.0f)); // -rotation to match Legacy...
// This matrix needs to be updated at the draw call frequency.

29
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/ProceduralSky/ProceduralSkyRenderer.cs


using UnityEngine.Rendering;
Material m_SkyProceduralMaterial;
Material m_ProceduralSkyMaterial;
MaterialPropertyBlock m_PropertyBlock;
ProceduralSky m_ProceduralSkyParams;

public override void Build()
{
m_SkyProceduralMaterial = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/Sky/SkyProcedural");
var hdrp = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;
m_ProceduralSkyMaterial = CoreUtils.CreateEngineMaterial(hdrp.renderPipelineResources.proceduralSky);
CoreUtils.Destroy(m_SkyProceduralMaterial);
CoreUtils.Destroy(m_ProceduralSkyMaterial);
}
public override void SetRenderTargets(BuiltinSkyParameters builtinParams)

public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap)
{
CoreUtils.SetKeyword(m_SkyProceduralMaterial, "_ENABLE_SUN_DISK", m_ProceduralSkyParams.enableSunDisk);
CoreUtils.SetKeyword(m_ProceduralSkyMaterial, "_ENABLE_SUN_DISK", m_ProceduralSkyParams.enableSunDisk);
Color sunColor = Color.white;
Vector3 sunDirection = Vector3.zero;

sunDirection = -builtinParams.sunLight.transform.forward;
}
m_SkyProceduralMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_ProceduralSkyParams.exposure, m_ProceduralSkyParams.multiplier, 0.0f, 0.0f));
m_SkyProceduralMaterial.SetFloat(_SunSizeParam, m_ProceduralSkyParams.sunSize);
m_SkyProceduralMaterial.SetFloat(_SunSizeConvergenceParam, m_ProceduralSkyParams.sunSizeConvergence);
m_SkyProceduralMaterial.SetFloat(_AtmoshpereThicknessParam, m_ProceduralSkyParams.atmosphereThickness);
m_SkyProceduralMaterial.SetColor(_SkyTintParam, m_ProceduralSkyParams.skyTint);
m_SkyProceduralMaterial.SetColor(_GroundColorParam, m_ProceduralSkyParams.groundColor);
m_SkyProceduralMaterial.SetColor(_SunColorParam, sunColor);
m_SkyProceduralMaterial.SetVector(_SunDirectionParam, sunDirection);
m_ProceduralSkyMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_ProceduralSkyParams.exposure, m_ProceduralSkyParams.multiplier, 0.0f, 0.0f));
m_ProceduralSkyMaterial.SetFloat(_SunSizeParam, m_ProceduralSkyParams.sunSize);
m_ProceduralSkyMaterial.SetFloat(_SunSizeConvergenceParam, m_ProceduralSkyParams.sunSizeConvergence);
m_ProceduralSkyMaterial.SetFloat(_AtmoshpereThicknessParam, m_ProceduralSkyParams.atmosphereThickness);
m_ProceduralSkyMaterial.SetColor(_SkyTintParam, m_ProceduralSkyParams.skyTint);
m_ProceduralSkyMaterial.SetColor(_GroundColorParam, m_ProceduralSkyParams.groundColor);
m_ProceduralSkyMaterial.SetColor(_SunColorParam, sunColor);
m_ProceduralSkyMaterial.SetVector(_SunDirectionParam, sunDirection);
CoreUtils.DrawFullScreen(builtinParams.commandBuffer, m_SkyProceduralMaterial, m_PropertyBlock, renderForCubemap ? 0 : 1);
CoreUtils.DrawFullScreen(builtinParams.commandBuffer, m_ProceduralSkyMaterial, m_PropertyBlock, renderForCubemap ? 0 : 1);
}
public override bool IsValid()

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


{
private const int PACKAGE_MANAGER_PATH_INDEX = 1;
private Shader m_DefaultShader;
public static readonly string[] m_SearchPaths = {"Assets", "Packages/com.unity.render-pipelines.lightweight"};
public static readonly string m_SearchPathProject = "Assets";
public static readonly string m_SearchPathPackage = "Packages/com.unity.render-pipelines.lightweight";
// Default values set when a new LightweightPipeline asset is created
[SerializeField] private int kAssetVersion = 2;

private static T LoadResourceFile<T>() where T : ScriptableObject
{
T resourceAsset = null;
var guids = AssetDatabase.FindAssets(typeof(T).Name + " t:scriptableobject", m_SearchPaths);
var guids = AssetDatabase.FindAssets(typeof(T).Name + " t:scriptableobject", new []{m_SearchPathProject});
foreach (string guid in guids)
{
string path = AssetDatabase.GUIDToAssetPath(guid);

// There's currently an issue that prevents FindAssets from find resources withing the package folder.
if (resourceAsset == null)
{
string path = m_SearchPaths[PACKAGE_MANAGER_PATH_INDEX] + "/LWRP/Data/" + typeof(T).Name + ".asset";
string path = m_SearchPathPackage + "/LWRP/Data/" + typeof(T).Name + ".asset";
resourceAsset = AssetDatabase.LoadAssetAtPath<T>(path);
}
return resourceAsset;

89
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/LightweightMaterialUpgrader.cs


// Legacy Shaders upgraders /
/////////////////////////////////////
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Diffuse", SupportedUpgradeParams.diffuseOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Diffuse Detail", SupportedUpgradeParams.diffuseOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Diffuse Fast", SupportedUpgradeParams.diffuseOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Parallax Diffuse", SupportedUpgradeParams.diffuseOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Parallax Specular", SupportedUpgradeParams.specularOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/VertexLit", SupportedUpgradeParams.specularOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/VertexLit", SupportedUpgradeParams.specularAlphaCutout));
// TODO:
//upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Diffuse", SupportedUpgradeParams.diffuseCubemap));
//upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Specular", SupportedUpgradeParams.specularOpaque));
//upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Diffuse", SupportedUpgradeParams.diffuseCubemap));
//upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Specular", SupportedUpgradeParams.specularOpaque));
// Reflective
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Diffuse", SupportedUpgradeParams.diffuseCubemap));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Specular", SupportedUpgradeParams.specularCubemap));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Unlit", SupportedUpgradeParams.diffuseCubemap));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped VertexLit", SupportedUpgradeParams.diffuseCubemap));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Diffuse", SupportedUpgradeParams.diffuseCubemap));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Specular", SupportedUpgradeParams.specularCubemap));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/VertexLit", SupportedUpgradeParams.diffuseCubemap));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Parallax Diffuse", SupportedUpgradeParams.diffuseCubemap));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Parallax Specular", SupportedUpgradeParams.specularCubemap));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Parallax Diffuse", SupportedUpgradeParams.diffuseOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Parallax Specular", SupportedUpgradeParams.specularOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/VertexLit", SupportedUpgradeParams.specularOpaque));
// Alpha Blended
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Diffuse", SupportedUpgradeParams.diffuseAlpha));

upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Bumped Diffuse", SupportedUpgradeParams.diffuseAlphaCutout));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Bumped Specular", SupportedUpgradeParams.specularAlphaCutout));
// Lightmapped
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Diffuse", SupportedUpgradeParams.diffuseOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Specular", SupportedUpgradeParams.specularOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/VertexLit", SupportedUpgradeParams.specularOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Bumped Specular", SupportedUpgradeParams.specularOpaque));
/////////////////////////////////////
// Sprites Upgraders
/////////////////////////////////////
upgraders.Add(new StandardSimpleLightingUpgrader("Sprites/Diffuse", SupportedUpgradeParams.diffuseAlpha));
/////////////////////////////////////
// UI Upgraders
/////////////////////////////////////
upgraders.Add(new StandardSimpleLightingUpgrader("UI/Lit/Bumped", SupportedUpgradeParams.diffuseAlphaCutout));
upgraders.Add(new StandardSimpleLightingUpgrader("UI/Lit/Detail", SupportedUpgradeParams.diffuseAlphaCutout));
upgraders.Add(new StandardSimpleLightingUpgrader("UI/Lit/Refraction", SupportedUpgradeParams.diffuseAlphaCutout));
upgraders.Add(new StandardSimpleLightingUpgrader("UI/Lit/Refraction Detail", SupportedUpgradeParams.diffuseAlphaCutout));
upgraders.Add(new StandardSimpleLightingUpgrader("UI/Lit/Transparent", SupportedUpgradeParams.diffuseAlpha));
/////////////////////////////////////
// Mobile Upgraders /
/////////////////////////////////////

upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/Unlit (Supports Lightmap)", SupportedUpgradeParams.diffuseOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/VertexLit", SupportedUpgradeParams.specularOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/VertexLit (Only Directional Lights)", SupportedUpgradeParams.specularOpaque));
upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/Particles/VertexLit Blended", SupportedUpgradeParams.specularOpaque));
////////////////////////////////////
// Terrain Upgraders //

////////////////////////////////////
upgraders.Add(new ParticleUpgrader("Particles/Standard Surface"));
upgraders.Add(new ParticleUpgrader("Particles/Standard Unlit"));
upgraders.Add(new ParticleUpgrader("Particles/VertexLit Blended"));
}
}

{
blendMode = UpgradeBlendMode.Opaque,
surfaceType = UpgradeSurfaceType.Opaque,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = false,
specularSource = SpecularSource.NoSpecular,
glosinessSource = GlossinessSource.BaseAlpha,
};

blendMode = UpgradeBlendMode.Opaque,
surfaceType = UpgradeSurfaceType.Opaque,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = false,
specularSource = SpecularSource.SpecularTextureAndColor,
glosinessSource = GlossinessSource.BaseAlpha,
};

surfaceType = UpgradeSurfaceType.Transparent,
alphaClip = false,
specularSource = SpecularSource.NoSpecular,
glosinessSource = GlossinessSource.SpecularAlpha,
};

surfaceType = UpgradeSurfaceType.Transparent,
alphaClip = false,
specularSource = SpecularSource.SpecularTextureAndColor,
glosinessSource = GlossinessSource.SpecularAlpha,
};

blendMode = UpgradeBlendMode.Cutout,
surfaceType = UpgradeSurfaceType.Opaque,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = true,
specularSource = SpecularSource.NoSpecular,
glosinessSource = GlossinessSource.SpecularAlpha,
};

blendMode = UpgradeBlendMode.Cutout,
surfaceType = UpgradeSurfaceType.Opaque,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = true,
specularSource = SpecularSource.SpecularTextureAndColor,
glosinessSource = GlossinessSource.SpecularAlpha,
};

blendMode = UpgradeBlendMode.Opaque,
surfaceType = UpgradeSurfaceType.Opaque,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = false,
specularSource = SpecularSource.NoSpecular,
glosinessSource = GlossinessSource.BaseAlpha,
};

blendMode = UpgradeBlendMode.Opaque,
surfaceType = UpgradeSurfaceType.Opaque,
blendMode = UpgradeBlendMode.Alpha,
alphaClip = false,
specularSource = SpecularSource.SpecularTextureAndColor,
glosinessSource = GlossinessSource.BaseAlpha,
};

surfaceType = UpgradeSurfaceType.Transparent,
alphaClip = false,
specularSource = SpecularSource.NoSpecular,
glosinessSource = GlossinessSource.BaseAlpha,
};

surfaceType = UpgradeSurfaceType.Transparent,
alphaClip = false,
specularSource = SpecularSource.SpecularTextureAndColor,
glosinessSource = GlossinessSource.BaseAlpha,
};

public StandardSimpleLightingUpgrader(string oldShaderName, UpgradeParams upgradeParams)
{
RenameShader(oldShaderName, LightweightShaderUtils.GetShaderPath(ShaderPathID.STANDARD_SIMPLE_LIGHTING), UpdateMaterialKeywords);
SetFloat("_Mode", (float)upgradeParams.blendMode);
SetFloat("_Surface", (float)upgradeParams.surfaceType);
SetFloat("_Blend", (float)upgradeParams.blendMode);
SetFloat("_AlphaClip", upgradeParams.alphaClip ? 1 : 0);
RenameTexture("_MainTex", "_EmissionMap");
RemoveTexture("_MainTex");
RenameTexture("_Illum", "_EmissionMap");
RemoveTexture("_Illum");
SetColor("_EmissionColor", Color.white);
}
}

118
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGUI/LightweightShaderGUI.cs


public abstract class LightweightShaderGUI : ShaderGUI
{
public enum BlendMode
public enum SurfaceType
Cutout,
Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency
Transparent // Physically plausible transparency mode, implemented as alpha pre-multiply
Transparent
}
public enum BlendMode
{
Alpha, // Old school alpha-blending mode, fresnel does not affect amount of transparency
Premultiply, // Physically plausible transparency mode, implemented as alpha pre-multiply
Additive,
Multiply
}
public abstract void FindProperties(MaterialProperty[] props);

public static void SetupMaterialBlendMode(Material material)
{
BlendMode blendMode = (BlendMode)material.GetFloat("_Mode");
switch (blendMode)
bool alphaClip = material.GetFloat("_AlphaClip") == 1;
if(alphaClip)
material.EnableKeyword("_ALPHATEST_ON");
else
material.DisableKeyword("_ALPHATEST_ON");
SurfaceType surfaceType = (SurfaceType)material.GetFloat("_Surface");
if(surfaceType == SurfaceType.Opaque)
case BlendMode.Opaque:
material.SetOverrideTag("RenderType", "");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.DisableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = -1;
material.SetShaderPassEnabled("ShadowCaster", true);
break;
case BlendMode.Cutout:
material.SetOverrideTag("RenderType", "TransparentCutout");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.EnableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
material.SetShaderPassEnabled("ShadowCaster", true);
break;
case BlendMode.Fade:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHATEST_ON");
material.EnableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
material.SetShaderPassEnabled("ShadowCaster", false);
break;
case BlendMode.Transparent:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
material.SetShaderPassEnabled("ShadowCaster", false);
break;
material.SetOverrideTag("RenderType", "");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = -1;
material.SetShaderPassEnabled("ShadowCaster", true);
}
else
{
BlendMode blendMode = (BlendMode)material.GetFloat("_Blend");
switch (blendMode)
{
case BlendMode.Alpha:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
material.SetShaderPassEnabled("ShadowCaster", false);
break;
case BlendMode.Premultiply:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
material.SetShaderPassEnabled("ShadowCaster", false);
break;
case BlendMode.Additive:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
material.SetShaderPassEnabled("ShadowCaster", false);
break;
case BlendMode.Multiply:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.DstColor);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
material.SetShaderPassEnabled("ShadowCaster", false);
break;
}
}
}

50
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGUI/LightweightStandardGUI.cs


private static class Styles
{
public static GUIContent twoSidedText = new GUIContent("Two Sided", "Render front and back faces");
public static GUIContent alphaClipText = new GUIContent("Alpha Clip", "Enable Alpha Clip");
public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff");
public static GUIContent clipThresholdText = new GUIContent("Clip Threshold", "Threshold for alpha clip");
public static GUIContent specularMapText = new GUIContent("Specular", "Specular (RGB) and Smoothness (A)");
public static GUIContent metallicMapText = new GUIContent("Metallic", "Metallic (R) and Smoothness (A)");
public static GUIContent smoothnessText = new GUIContent("Smoothness", "Smoothness value");

public static string secondaryMapsText = "Secondary Maps";
public static string forwardText = "Forward Rendering Options";
public static string workflowModeText = "Workflow Mode";
public static string renderingMode = "Rendering Mode";
public static string surfaceType = "Surface Type";
public static string blendingMode = "Blending Mode";
public static readonly string[] surfaceNames = Enum.GetNames(typeof(SurfaceType));
public static readonly string[] blendNames = Enum.GetNames(typeof(BlendMode));
public static readonly string[] metallicSmoothnessChannelNames = {"Metallic Alpha", "Albedo Alpha"};
public static readonly string[] specularSmoothnessChannelNames = {"Specular Alpha", "Albedo Alpha"};

private MaterialProperty surfaceType;
private MaterialProperty culling;
private MaterialProperty alphaClip;
private MaterialProperty alphaCutoff;
private MaterialProperty alphaThreshold;
private MaterialProperty smoothness;
private MaterialProperty smoothnessScale;

public override void FindProperties(MaterialProperty[] properties)
{
workflowMode = FindProperty("_WorkflowMode", properties);
blendMode = FindProperty("_Mode", properties);
surfaceType = FindProperty("_Surface", properties);
blendMode = FindProperty("_Blend", properties);
culling = FindProperty("_Cull", properties);
alphaClip = FindProperty("_AlphaClip", properties);
alphaCutoff = FindProperty("_Cutoff", properties);
alphaThreshold = FindProperty("_Cutoff", properties);
smoothness = FindProperty("_Glossiness", properties);
smoothnessScale = FindProperty("_GlossMapScale", properties, false);

EditorGUI.BeginChangeCheck();
{
DoPopup(Styles.workflowModeText, workflowMode, Styles.workflowNames);
DoPopup(Styles.renderingMode, blendMode, Styles.blendNames);
DoPopup(Styles.surfaceType, surfaceType, Styles.surfaceNames);
if ((SurfaceType)material.GetFloat("_Surface") == SurfaceType.Transparent)
DoPopup(Styles.blendingMode, blendMode, Styles.blendNames);
EditorGUI.BeginChangeCheck();
bool twoSidedEnabled = EditorGUILayout.Toggle(Styles.twoSidedText, culling.floatValue == 0);
if (EditorGUI.EndChangeCheck())
culling.floatValue = twoSidedEnabled ? 0 : 2;
EditorGUI.BeginChangeCheck();
bool alphaClipEnabled = EditorGUILayout.Toggle(Styles.alphaClipText, alphaClip.floatValue == 1);
if (EditorGUI.EndChangeCheck())
alphaClip.floatValue = alphaClipEnabled ? 1 : 0;
// Primary properties
GUILayout.Label(Styles.primaryMapsText, EditorStyles.boldLabel);

return;
}
BlendMode blendMode = BlendMode.Opaque;
SurfaceType surfaceType = SurfaceType.Opaque;
BlendMode blendMode = BlendMode.Alpha;
blendMode = BlendMode.Cutout;
surfaceType = SurfaceType.Opaque;
material.SetFloat("_AlphaClip", 1);
blendMode = BlendMode.Fade;
surfaceType = SurfaceType.Transparent;
blendMode = BlendMode.Alpha;
material.SetFloat("_Mode", (float)blendMode);
material.SetFloat("_Surface", (float)surfaceType);
material.SetFloat("_Blend", (float)blendMode);
if (oldShader.name.Equals("Standard (Specular setup)"))
{

void DoAlbedoArea(Material material)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor);
if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Cutout))
if (material.GetFloat("_AlphaClip") == 1)
m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
m_MaterialEditor.ShaderProperty(alphaThreshold, Styles.clipThresholdText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
}
}

73
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGUI/LightweightStandardSimpleLightingGUI.cs


public class LightweightStandardSimpleLightingGUI : LightweightShaderGUI
{
private const float kMinShininessValue = 0.01f;
private MaterialProperty surfaceTypeProp;
private MaterialProperty culling;
private MaterialProperty alphaClip;
private MaterialProperty alphaCutoffProp;
private MaterialProperty alphaThresholdProp;
private MaterialProperty specularSourceProp;
private MaterialProperty glossinessSourceProp;
private MaterialProperty specularGlossMapProp;

private static class Styles
{
public static GUIContent twoSidedLabel = new GUIContent("Two Sided", "Render front and back faces");
public static GUIContent alphaClipLabel = new GUIContent("Alpha Clip", "Enable Alpha Clip");
public static GUIContent[] albedoGlosinessLabels =
{
new GUIContent("Base (RGB) Glossiness (A)", "Base Color (RGB) and Glossiness (A)"),

public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map");
public static GUIContent emissionMapLabel = new GUIContent("Emission Map", "Emission Map");
public static readonly string[] surfaceNames = Enum.GetNames(typeof(SurfaceType));
public static string renderingModeLabel = "Rendering Mode";
public static string surfaceTypeLabel = "Surface Type";
public static string blendingModeLabel = "Blending Mode";
public static string specularSourceLabel = "Specular";
public static string glossinessSourceLabel = "Glossiness Source";
public static string glossinessSource = "Glossiness Source";

public static string alphaCutoffLabel = "Alpha Cutoff";
public static string clipThresholdLabel = "Clip Threshold";
public static string shininessLabel = "Shininess";
public static string normalMapLabel = "Normal map";
public static string emissionColorLabel = "Emission Color";

public override void FindProperties(MaterialProperty[] properties)
{
blendModeProp = FindProperty("_Mode", properties);
surfaceTypeProp = FindProperty("_Surface", properties);
blendModeProp = FindProperty("_Blend", properties);
culling = FindProperty("_Cull", properties);
alphaClip = FindProperty("_AlphaClip", properties);
alphaCutoffProp = FindProperty("_Cutoff", properties);
alphaThresholdProp = FindProperty("_Cutoff", properties);
specularSourceProp = FindProperty("_SpecSource", properties);
glossinessSourceProp = FindProperty("_GlossinessSource", properties);
specularGlossMapProp = FindProperty("_SpecGlossMap", properties);

{
EditorGUI.BeginChangeCheck();
{
DoBlendMode();
EditorGUILayout.Space();
DoSurfaceArea();
DoSpecular();
EditorGUILayout.Space();

StandardSimpleLightingUpgrader.UpdateMaterialKeywords(material);
}
private void DoBlendMode()
private void DoSurfaceArea()
int modeValue = (int)blendModeProp.floatValue;
int surfaceTypeValue = (int)surfaceTypeProp.floatValue;
modeValue = EditorGUILayout.Popup(Styles.renderingModeLabel, modeValue, Styles.blendNames);
surfaceTypeValue = EditorGUILayout.Popup(Styles.surfaceTypeLabel, surfaceTypeValue, Styles.surfaceNames);
blendModeProp.floatValue = modeValue;
surfaceTypeProp.floatValue = surfaceTypeValue;
if((SurfaceType)surfaceTypeValue == SurfaceType.Transparent)
{
int blendModeValue = (int)blendModeProp.floatValue;
EditorGUI.BeginChangeCheck();
blendModeValue = EditorGUILayout.Popup(Styles.blendingModeLabel, blendModeValue, Styles.blendNames);
if (EditorGUI.EndChangeCheck())
blendModeProp.floatValue = blendModeValue;
}
UpgradeBlendMode mode = (UpgradeBlendMode)blendModeProp.floatValue;
EditorGUI.BeginChangeCheck();
bool twoSidedEnabled = EditorGUILayout.Toggle(Styles.twoSidedLabel, culling.floatValue == 0);
if (EditorGUI.EndChangeCheck())
culling.floatValue = twoSidedEnabled ? 0 : 2;
EditorGUI.BeginChangeCheck();
bool alphaClipEnabled = EditorGUILayout.Toggle(Styles.alphaClipLabel, alphaClip.floatValue == 1);
if (EditorGUI.EndChangeCheck())
alphaClip.floatValue = alphaClipEnabled ? 1 : 0;
if (mode == UpgradeBlendMode.Opaque)
if ((SurfaceType)surfaceTypeValue == SurfaceType.Opaque)
m_MaterialEditor.TextureScaleOffsetProperty(albedoMapProp);
if (mode == UpgradeBlendMode.Cutout)
m_MaterialEditor.RangeProperty(alphaCutoffProp, "Cutoff");
if (alphaClipEnabled)
m_MaterialEditor.ShaderProperty(alphaThresholdProp, Styles.clipThresholdLabel, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
}
private void DoSpecular()

if (oldShaderName.Contains("Transp"))
{
shaderUpgradeParams.surfaceType = UpgradeSurfaceType.Transparent;
shaderUpgradeParams.alphaClip = false;
shaderUpgradeParams.blendMode = UpgradeBlendMode.Cutout;
shaderUpgradeParams.surfaceType = UpgradeSurfaceType.Opaque;
shaderUpgradeParams.blendMode = UpgradeBlendMode.Alpha;
shaderUpgradeParams.alphaClip = true;
shaderUpgradeParams.blendMode = UpgradeBlendMode.Opaque;
shaderUpgradeParams.surfaceType = UpgradeSurfaceType.Opaque;
shaderUpgradeParams.blendMode = UpgradeBlendMode.Alpha;
shaderUpgradeParams.alphaClip = false;
shaderUpgradeParams.glosinessSource = GlossinessSource.BaseAlpha;
}

shaderUpgradeParams.specularSource = SpecularSource.NoSpecular;
material.SetFloat("_Mode", (float)shaderUpgradeParams.blendMode);
material.SetFloat("_Surface", (float)shaderUpgradeParams.surfaceType);
material.SetFloat("_Blend", (float)shaderUpgradeParams.blendMode);
material.SetFloat("_SpecSource", (float)shaderUpgradeParams.specularSource);
material.SetFloat("_GlossinessSource", (float)shaderUpgradeParams.glosinessSource);

105
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/ShaderGUI/LightweightUnlitGUI.cs


public class LightweightUnlitGUI : LightweightShaderGUI
{
public enum UnlitBlendMode
{
Alpha, // Old school alpha-blending mode, fresnel does not affect amount of transparency
Additive,
Multiply
}
private MaterialProperty surfaceTypeProp;
private MaterialProperty culling;
private MaterialProperty alphaClip;
private MaterialProperty mainTexProp;
private MaterialProperty mainColorProp;
private MaterialProperty alphaCutoffProp;

private static class Styles
{
public static GUIContent twoSidedLabel = new GUIContent("Two Sided", "Render front and back faces");
public static GUIContent alphaClipLabel = new GUIContent("Alpha Clip", "Enable Alpha Clip");
public static GUIContent[] mainTexLabels =
{
new GUIContent("MainTex (RGB)", "Base Color"),

public static GUIContent normalMapLabel = new GUIContent("Normal Map", "Normal Map");
public static readonly string[] blendNames = Enum.GetNames(typeof(UpgradeBlendMode));
public static readonly string[] surfaceNames = Enum.GetNames(typeof(SurfaceType));
public static readonly string[] blendNames = Enum.GetNames(typeof(UnlitBlendMode));
public static string renderingModeLabel = "Rendering Mode";
public static string alphaCutoffLabel = "Alpha Cutoff";
public static string surfaceTypeLabel = "Surface Type";
public static string blendingModeLabel = "Blending Mode";
public static string clipThresholdLabel = "Clip Threshold";
blendModeProp = FindProperty("_Mode", properties);
surfaceTypeProp = FindProperty("_Surface", properties);
blendModeProp = FindProperty("_Blend", properties);
culling = FindProperty("_Cull", properties);
alphaClip = FindProperty("_AlphaClip", properties);
mainTexProp = FindProperty("_MainTex", properties);
mainColorProp = FindProperty("_Color", properties);
alphaCutoffProp = FindProperty("_Cutoff", properties);

{
EditorGUI.BeginChangeCheck();
{
DoPopup(Styles.renderingModeLabel, blendModeProp, Styles.blendNames);
int modeValue = (int)blendModeProp.floatValue;
DoPopup(Styles.surfaceTypeLabel, surfaceTypeProp, Styles.surfaceNames);
int surfaceTypeValue = (int)surfaceTypeProp.floatValue;
if((SurfaceType)surfaceTypeValue == SurfaceType.Transparent)
DoPopup(Styles.blendingModeLabel, blendModeProp, Styles.blendNames);
EditorGUI.BeginChangeCheck();
bool twoSidedEnabled = EditorGUILayout.Toggle(Styles.twoSidedLabel, culling.floatValue == 0);
if (EditorGUI.EndChangeCheck())
culling.floatValue = twoSidedEnabled ? 0 : 2;
EditorGUI.BeginChangeCheck();
bool alphaClipEnabled = EditorGUILayout.Toggle(Styles.alphaClipLabel, alphaClip.floatValue == 1);
if (EditorGUI.EndChangeCheck())
alphaClip.floatValue = alphaClipEnabled ? 1 : 0;
GUIContent mainTexLabel = Styles.mainTexLabels[Math.Min(modeValue, 1)];
GUIContent mainTexLabel = Styles.mainTexLabels[Math.Min(surfaceTypeValue, 1)];
m_MaterialEditor.TextureScaleOffsetProperty(mainTexProp);
if ((UpgradeBlendMode)modeValue == UpgradeBlendMode.Cutout)
m_MaterialEditor.RangeProperty(alphaCutoffProp, Styles.alphaCutoffLabel);
if (alphaClipEnabled)
m_MaterialEditor.ShaderProperty(alphaCutoffProp, Styles.clipThresholdLabel, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
m_MaterialEditor.TextureScaleOffsetProperty(mainTexProp);
EditorGUILayout.Space();
m_MaterialEditor.ShaderProperty(sampleGIProp, Styles.sampleGILabel);

{
material.shaderKeywords = null;
bool sampleGI = material.GetFloat("_SampleGI") >= 1.0f;
SetupMaterialBlendMode(material);
bool alphaClip = material.GetFloat("_AlphaClip") == 1;
if(alphaClip)
material.EnableKeyword("_ALPHATEST_ON");
else
material.DisableKeyword("_ALPHATEST_ON");
SurfaceType surfaceType = (SurfaceType)material.GetFloat("_Surface");
if(surfaceType == SurfaceType.Opaque)
{
material.SetOverrideTag("RenderType", "");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = -1;
material.SetShaderPassEnabled("ShadowCaster", true);
}
else
{
UnlitBlendMode blendMode = (UnlitBlendMode)material.GetFloat("_Blend");
switch (blendMode)
{
case UnlitBlendMode.Alpha:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
material.SetShaderPassEnabled("ShadowCaster", false);
break;
case UnlitBlendMode.Additive:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
material.SetShaderPassEnabled("ShadowCaster", false);
break;
case UnlitBlendMode.Multiply:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.DstColor);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
material.SetShaderPassEnabled("ShadowCaster", false);
break;
}
}
}
}

15
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/UpgradeCommon.cs


namespace UnityEditor.Experimental.Rendering.LightweightPipeline
{
public enum UpgradeSurfaceType
{
Opaque,
Transparent
}
Opaque,
Cutout,
Alpha
Alpha,
Premultiply,
Additive,
Multiply
}
public enum SpecularSource

public struct UpgradeParams
{
public UpgradeSurfaceType surfaceType;
public bool alphaClip;
public SpecularSource specularSource;
public GlossinessSource glosinessSource;
}

106
ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs


RenderPipeline.BeginCameraRendering(camera);
bool sceneViewCamera = camera.cameraType == CameraType.SceneView;
bool stereoEnabled = XRSettings.isDeviceActive && !sceneViewCamera;
bool stereoEnabled = XRSettings.isDeviceActive && !sceneViewCamera && (camera.stereoTargetEye == StereoTargetEyeMask.Both);
m_CurrCamera = camera;
m_IsOffscreenCamera = m_CurrCamera.targetTexture != null && m_CurrCamera.cameraType != CameraType.SceneView;

if (LightweightUtils.HasFlag(frameRenderingConfiguration, FrameRenderingConfiguration.DepthPrePass))
{
DepthPass(ref context);
DepthPass(ref context, frameRenderingConfiguration);
ShadowCollectPass(visibleLights, ref context, ref lightData);
ShadowCollectPass(visibleLights, ref context, ref lightData, frameRenderingConfiguration);
}
if (!shadows)

return false;
}
private void ShadowCollectPass(List<VisibleLight> visibleLights, ref ScriptableRenderContext context, ref LightData lightData)
private void ShadowCollectPass(List<VisibleLight> visibleLights, ref ScriptableRenderContext context, ref LightData lightData, FrameRenderingConfiguration frameRenderingConfiguration)
{
CommandBuffer cmd = CommandBufferPool.Get("Collect Shadows");

cmd.GetTemporaryRT(m_ScreenSpaceShadowMapRTID, m_CurrCamera.pixelWidth, m_CurrCamera.pixelHeight, 0, FilterMode.Bilinear, RenderTextureFormat.R8);
cmd.Blit(null, m_ScreenSpaceShadowMapRT, m_ScreenSpaceShadowsMaterial);
// TODO: Support RenderScale for the SSSM target. Should probably move allocation elsewhere, or at
// least propogate RenderTextureDescriptor generation
if (LightweightUtils.HasFlag(frameRenderingConfiguration, FrameRenderingConfiguration.Stereo))
{
var desc = XRSettings.eyeTextureDesc;
desc.depthBufferBits = 0;
desc.colorFormat = RenderTextureFormat.R8;
cmd.GetTemporaryRT(m_ScreenSpaceShadowMapRTID, desc, FilterMode.Bilinear);
}
else
{
cmd.GetTemporaryRT(m_ScreenSpaceShadowMapRTID, m_CurrCamera.pixelWidth, m_CurrCamera.pixelHeight, 0, FilterMode.Bilinear, RenderTextureFormat.R8);
}
// Note: The source isn't actually 'used', but there's an engine peculiarity (bug) that
// doesn't like null sources when trying to determine a stereo-ized blit. So for proper
// stereo functionality, we use the screen-space shadow map as the source (until we have
// a better solution).
// An alternative would be DrawProcedural, but that would require further changes in the shader.
cmd.Blit(m_ScreenSpaceShadowMapRT, m_ScreenSpaceShadowMapRT, m_ScreenSpaceShadowsMaterial);
StartStereoRendering(ref context, frameRenderingConfiguration);
StopStereoRendering(ref context, frameRenderingConfiguration);
private void DepthPass(ref ScriptableRenderContext context)
private void DepthPass(ref ScriptableRenderContext context, FrameRenderingConfiguration frameRenderingConfiguration)
{
CommandBuffer cmd = CommandBufferPool.Get("Depth Prepass");
SetRenderTarget(cmd, m_DepthRT, ClearFlag.Depth);

renderQueueRange = RenderQueueRange.opaque
};
StartStereoRendering(ref context, frameRenderingConfiguration);
StopStereoRendering(ref context, frameRenderingConfiguration);
}
private void ForwardPass(List<VisibleLight> visibleLights, FrameRenderingConfiguration frameRenderingConfiguration, ref ScriptableRenderContext context, ref LightData lightData, bool stereoEnabled)

m_CurrCameraColorRT = BuiltinRenderTextureType.CameraTarget;
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture))
{
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Stereo))
SetupIntermediateResourcesStereo(cmd, msaaSamples);
else
SetupIntermediateResourcesSingle(cmd, renderingConfig, msaaSamples);
}
SetupIntermediateRenderTextures(cmd, renderingConfig, msaaSamples);
private void SetupIntermediateResourcesSingle(CommandBuffer cmd, FrameRenderingConfiguration renderingConfig, int msaaSamples)
private void SetupIntermediateRenderTextures(CommandBuffer cmd, FrameRenderingConfiguration renderingConfig, int msaaSamples)
RenderTextureDescriptor baseDesc;
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Stereo))
baseDesc = XRSettings.eyeTextureDesc;
else
baseDesc = new RenderTextureDescriptor(m_CurrCamera.pixelWidth, m_CurrCamera.pixelHeight);
int rtWidth = (int)((float)m_CurrCamera.pixelWidth * renderScale);
int rtHeight = (int)((float)m_CurrCamera.pixelHeight * renderScale);
baseDesc.width = (int)((float)baseDesc.width * renderScale);
baseDesc.height = (int)((float)baseDesc.height * renderScale);
// TODO: Might be worth caching baseDesc for allocation of other targets (Screen-space Shadow Map?)
RenderTextureDescriptor depthRTDesc = new RenderTextureDescriptor(rtWidth, rtHeight, RenderTextureFormat.Depth, kDepthStencilBufferBits);
var depthRTDesc = baseDesc;
depthRTDesc.colorFormat = RenderTextureFormat.Depth;
depthRTDesc.depthBufferBits = kDepthStencilBufferBits;
cmd.GetTemporaryRT(CameraRenderTargetID.depth, depthRTDesc, FilterMode.Bilinear);
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.DepthCopy))

RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(rtWidth, rtHeight, m_ColorFormat, kDepthStencilBufferBits);
var colorRTDesc = baseDesc;
colorRTDesc.colorFormat = m_ColorFormat;
colorRTDesc.depthBufferBits = kDepthStencilBufferBits; // TODO: does the color RT always need depth?
colorRTDesc.sRGB = true;
colorRTDesc.msaaSamples = msaaSamples;
colorRTDesc.enableRandomWrite = false;

// color RT to blit the effect.
if (m_RequireCopyColor)
cmd.GetTemporaryRT(CameraRenderTargetID.copyColor, colorRTDesc, FilterMode.Point);
}
private void SetupIntermediateResourcesStereo(CommandBuffer cmd, int msaaSamples)
{
RenderTextureDescriptor rtDesc = new RenderTextureDescriptor();
rtDesc = XRSettings.eyeTextureDesc;
rtDesc.colorFormat = m_ColorFormat;
rtDesc.msaaSamples = msaaSamples;
cmd.GetTemporaryRT(CameraRenderTargetID.color, rtDesc, FilterMode.Bilinear);
}
private void SetupShaderConstants(List<VisibleLight> visibleLights, ref ScriptableRenderContext context, ref LightData lightData)

var cmd = CommandBufferPool.Get("Prepare Shadowmap");
cmd.GetTemporaryRT(m_ShadowMapRTID, m_ShadowSettings.shadowAtlasWidth,
m_ShadowSettings.shadowAtlasHeight, kDepthStencilBufferBits, FilterMode.Bilinear, m_ShadowSettings.renderTextureFormat);
SetRenderTarget(cmd, m_ShadowMapRT, ClearFlag.Depth);
// LightweightPipeline.SetRenderTarget is meant to be used with camera targets, not shadowmaps
CoreUtils.SetRenderTarget(cmd, m_ShadowMapRT, ClearFlag.Depth, CoreUtils.ConvertSRGBToActiveColorSpace(m_CurrCamera.backgroundColor));
if (shadowLight.lightType == LightType.Spot)
{

RenderTargetIdentifier colorRT = BuiltinRenderTextureType.CameraTarget;
RenderTargetIdentifier depthRT = BuiltinRenderTextureType.None;
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Stereo))
context.StartMultiEye(m_CurrCamera);
StartStereoRendering(ref context, renderingConfig);
bool intermeaditeTexture = LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture);
if (intermeaditeTexture)
bool intermediateTexture = LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture);
if (intermediateTexture)
{
if (!m_IsOffscreenCamera)
colorRT = m_CurrCameraColorRT;

// If rendering to an intermediate RT we resolve viewport on blit due to offset not being supported
// while rendering to a RT.
if (!intermeaditeTexture && !LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.DefaultViewport))
if (!intermediateTexture && !LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.DefaultViewport))
cmd.SetViewport(m_CurrCamera.pixelRect);
context.ExecuteCommandBuffer(cmd);

cmd.CopyTexture(sourceRT, destRT);
else
cmd.Blit(sourceRT, destRT, copyMaterial);
}
private void StartStereoRendering(ref ScriptableRenderContext context, FrameRenderingConfiguration renderingConfiguration)
{
if (LightweightUtils.HasFlag(renderingConfiguration, FrameRenderingConfiguration.Stereo))
context.StartMultiEye(m_CurrCamera);
}
private void StopStereoRendering(ref ScriptableRenderContext context, FrameRenderingConfiguration renderingConfiguration)
{
if (LightweightUtils.HasFlag(renderingConfiguration, FrameRenderingConfiguration.Stereo))
context.StopMultiEye(m_CurrCamera);
}
}
}

25
ScriptableRenderPipeline/LightweightPipeline/LWRP/ShaderLibrary/Core.hlsl


ApplyFogColor(color, unity_FogColor.rgb, fogFactor);
}
// Stereo-related bits
#if defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
#define SCREENSPACE_TEXTURE TEXTURE2D_ARRAY
#else
#define SCREENSPACE_TEXTURE TEXTURE2D
#endif // defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
#if defined(UNITY_SINGLE_PASS_STEREO)
float2 TransformStereoScreenSpaceTex(float2 uv, float w)
{
// TODO: RVS support can be added here, if LWRP decides to support it
float4 scaleOffset = unity_StereoScaleOffset[unity_StereoEyeIndex];
return uv.xy * scaleOffset.xy + scaleOffset.zw * w;
}
float2 UnityStereoTransformScreenSpaceTex(float2 uv)
{
return TransformStereoScreenSpaceTex(saturate(uv), 1.0);
}
#else
#define UnityStereoTransformScreenSpaceTex(uv) uv
#endif // defined(UNITY_SINGLE_PASS_STEREO)
#endif

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


}
// Transforms position from object space to homogenous space
float4 TransformObjectToHClip(float3 positionWS)
float4 TransformObjectToHClip(float3 positionOS)
return mul(GetWorldToHClipMatrix(), mul(GetObjectToWorldMatrix(), float4(positionWS, 1.0)));
return mul(GetWorldToHClipMatrix(), mul(GetObjectToWorldMatrix(), float4(positionOS, 1.0)));
}
// Tranforms position from world space to homogenous space

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


// HDR environment map decode instructions
half4 unity_SpecCube0_HDR;
// HDR lightmap decode instructions
half4 unity_Lightmap_HDR;
// These are set internally by the engine upon request by RendererConfiguration.
// Check GetRendererSettings in LightweightPipeline.cs
half4 unity_LightIndicesOffsetAndCount;

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


#ifdef DIRLIGHTMAP_COMBINED
return SampleDirectionalLightmap(TEXTURE2D_PARAM(unity_Lightmap, samplerunity_Lightmap),
TEXTURE2D_PARAM(unity_LightmapInd, samplerunity_Lightmap),
lightmapUV, transformCoords, normalWS, encodedLightmap);
lightmapUV, transformCoords, normalWS, encodedLightmap, unity_Lightmap_HDR);
return SampleSingleLightmap(TEXTURE2D_PARAM(unity_Lightmap, samplerunity_Lightmap), lightmapUV, transformCoords, encodedLightmap);
return SampleSingleLightmap(TEXTURE2D_PARAM(unity_Lightmap, samplerunity_Lightmap), lightmapUV, transformCoords, encodedLightmap, unity_Lightmap_HDR);
#endif
}

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


float4 clipPos : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
void InitializeInputData(LightweightVertexOutput IN, half3 normalTS, out InputData inputData)

UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);

half alpha = diffuseAlpha.a * _Color.a;
AlphaDiscard(alpha, _Cutoff);
#ifdef _ALPHAPREMULTIPLY_ON
diffuse *= alpha;
#endif
#ifdef _NORMALMAP
half3 normalTS = Normal(uv);

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


// so use it in a very dummy way
vertex.z = vertex.z > 0 ? 1.0e-4f : 0.0f;
}
return TransformObjectToHClip(vertex.xyz);
return TransformWorldToHClip(vertex.xyz); // Need to transfer from world to clip compared to legacy
}
half4 MetaFragment(MetaInput IN)

unity_OneOverOutputBoost = saturate(unity_OneOverOutputBoost);
// Apply Albedo Boost from LightmapSettings.
res.rgb = clamp(pow(res.rgb, unity_OneOverOutputBoost), 0, unity_MaxOutputValue);
res.rgb = clamp(PositivePow(res.rgb, unity_OneOverOutputBoost), 0, unity_MaxOutputValue);
}
if (unity_MetaFragmentControl.y)
{

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


#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/Shadow/ShadowSamplingTent.hlsl"
#include "Core.hlsl"
TEXTURE2D(_ScreenSpaceShadowMap);
SCREENSPACE_TEXTURE(_ScreenSpaceShadowMap);
SAMPLER(sampler_ScreenSpaceShadowMap);
TEXTURE2D_SHADOW(_ShadowMap);

inline half SampleScreenSpaceShadowMap(float4 shadowCoord)
{
shadowCoord.xy /= shadowCoord.w;
// The stereo transform has to happen after the manual perspective divide
shadowCoord.xy = UnityStereoTransformScreenSpaceTex(shadowCoord.xy);
#if defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
half attenuation = SAMPLE_TEXTURE2D_ARRAY(_ScreenSpaceShadowMap, sampler_ScreenSpaceShadowMap, shadowCoord.xy, unity_StereoEyeIndex).x;
#else
#endif
// Apply shadow strength
return LerpWhiteTo(attenuation, GetShadowStrength());

float4 ComputeShadowCoord(float4 clipPos)
{
// TODO: This might have to be corrected for double-wide and texture arrays
return ComputeScreenPos(clipPos);
}

17
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightScreenSpaceShadows.shader


HLSLINCLUDE
#pragma prefer_hlslcc gles
//Keep compiler quiet about Shadows.hlsl.
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/EntityLighting.hlsl"

TEXTURE2D(_CameraDepthTexture);
SCREENSPACE_TEXTURE(_CameraDepthTexture);
SAMPLER(sampler_CameraDepthTexture);
struct VertexInput

half4 pos : SV_POSITION;
half4 texcoord : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
Interpolators Vertex(VertexInput i)

UNITY_TRANSFER_INSTANCE_ID(i, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.pos = TransformObjectToHClip(i.vertex.xyz);

o.texcoord.xy = i.texcoord;
o.texcoord.xy = UnityStereoTransformScreenSpaceTex(i.texcoord);
o.texcoord.zw = projPos.xy;
return o;

{
UNITY_SETUP_INSTANCE_ID(i);
#if !defined(UNITY_STEREO_INSTANCING_ENABLED)
// Completely unclear why i.stereoTargetEyeIndex doesn't work here, considering
// this has to be correct in order for the texture array slices to be rasterized to
// We can limit this workaround to stereo instancing for now.
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
#endif
#if defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
float deviceDepth = SAMPLE_TEXTURE2D_ARRAY(_CameraDepthTexture, sampler_CameraDepthTexture, i.texcoord.xy, unity_StereoEyeIndex).r;
#else
#endif
#if UNITY_REVERSED_Z
deviceDepth = 1 - deviceDepth;

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


[Enum(UV0,0,UV1,1)] _UVSec("UV Set for secondary textures", Float) = 0
// Blending state
[HideInInspector] _Mode("__mode", Float) = 0.0
[HideInInspector] _Surface("__surface", Float) = 0.0
[HideInInspector] _Blend("__blend", Float) = 0.0
[HideInInspector] _AlphaClip("__clip", Float) = 0.0
[HideInInspector] _Cull("__cull", Float) = 2.0
}
SubShader

Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]
Cull[_Cull]
HLSLPROGRAM
// Required to compile gles 2.0 with standard SRP library

// -------------------------------------
// Material Keywords
#pragma shader_feature _NORMALMAP
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHAPREMULTIPLY_ON
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICSPECGLOSSMAP
#pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A

ZWrite On
ZTest LEqual
Cull[_Cull]
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library

// -------------------------------------
// Material Keywords
#pragma shader_feature _NORMALMAP
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHAPREMULTIPLY_ON
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICSPECGLOSSMAP
#pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A

// -------------------------------------
// Material Keywords
#pragma shader_feature _NORMALMAP
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHAPREMULTIPLY_ON
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICSPECGLOSSMAP
#pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A

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


[Enum(UV0,0,UV1,1)] _UVSec("UV Set for secondary textures", Float) = 0
// Blending state
[HideInInspector] _Mode("__mode", Float) = 0.0
[HideInInspector] _Surface("__surface", Float) = 0.0
[HideInInspector] _Blend("__blend", Float) = 0.0
[HideInInspector] _AlphaClip("__clip", Float) = 0.0
[HideInInspector] _Cull("__cull", Float) = 2.0
}
SubShader

// Use same blending / depth states as Standard shader
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]
Cull[_Cull]
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library

// -------------------------------------
// Material Keywords
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHAPREMULTIPLY_ON
#pragma shader_feature _ _SPECGLOSSMAP _SPECULAR_COLOR
#pragma shader_feature _ _GLOSSINESS_FROM_BASE_ALPHA
#pragma shader_feature _NORMALMAP

ZWrite On
ZTest LEqual
Cull[_Cull]
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library

// -------------------------------------
// Material Keywords
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHAPREMULTIPLY_ON
#pragma shader_feature _ _SPECGLOSSMAP _SPECULAR_COLOR
#pragma shader_feature _ _GLOSSINESS_FROM_BASE_ALPHA
#pragma shader_feature _NORMALMAP

// -------------------------------------
// Material Keywords
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _ALPHAPREMULTIPLY_ON
#pragma shader_feature _ _SPECGLOSSMAP _SPECULAR_COLOR
#pragma shader_feature _ _GLOSSINESS_FROM_BASE_ALPHA
#pragma shader_feature _NORMALMAP

19
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardUnlit.shader


_BumpMap("Normal Map", 2D) = "bump" {}
// BlendMode
[HideInInspector] _Mode("Mode", Float) = 0.0
[HideInInspector] _Surface("__surface", Float) = 0.0
[HideInInspector] _Blend("__blend", Float) = 0.0
[HideInInspector] _AlphaClip("__clip", Float) = 0.0
[HideInInspector] _Cull("__cull", Float) = 2.0
}
SubShader
{

Blend [_SrcBlend][_DstBlend]
ZWrite [_ZWrite]
Cull [_Cull]
Pass
{

#pragma fragment frag
#pragma multi_compile_fog
#pragma shader_feature _SAMPLE_GI
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON
#pragma shader_feature _ALPHATEST_ON
#pragma multi_compile_instancing
// -------------------------------------

float4 vertex : SV_POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
VertexOutput vert(VertexInput v)

UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.vertex = TransformObjectToHClip(v.vertex.xyz);
o.uv0AndFogCoord.xy = TRANSFORM_TEX(v.uv, _MainTex);

half2 uv = IN.uv0AndFogCoord.xy;
half4 texColor = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv);
half3 color = texColor.rgb * _Color.rgb;
half alpha = texColor.a * _Color.a;
half alpha = texColor.a * _Color.a;
AlphaDiscard(alpha, _Cutoff);
#if _SAMPLE_GI

color *= SampleGI(IN.lightmapOrVertexSH, normalWS);
#endif
ApplyFog(color, IN.uv0AndFogCoord.z);
#ifdef _ALPHABLEND_ON
#else
return half4(color, 1.0);
#endif
}
ENDHLSL
}

48
build.py


sub_package_folders = {}
publish_order = []
packages = {
("com.unity.render-pipelines.core", os.path.join("ScriptableRenderPipeline", "Core")),
("com.unity.render-pipelines.high-definition", os.path.join("ScriptableRenderPipeline", "HDRenderPipeline")),
("com.unity.render-pipelines.lightweight", os.path.join("ScriptableRenderPipeline", "LightweightPipeline"))
}
def packages_list():
return [
("com.unity.render-pipelines.core", os.path.join("ScriptableRenderPipeline", "Core")),
("com.unity.render-pipelines.high-definition", os.path.join("ScriptableRenderPipeline", "HDRenderPipeline")),
("com.unity.render-pipelines.lightweight", os.path.join("ScriptableRenderPipeline", "LightweightPipeline"))
]
def prepare(logger):
file_path = os.path.join("./ScriptableRenderPipeline", "master-package.json")

with open(package_path, 'w') as file:
json.dump(sub_package, file, indent=4, sort_keys=True)
def packages_list():
package_list = []
import unity_package_build
package_list.append((name, sub_package_folders[name]))
return package_list
package_path = os.path.join(sub_package_folders[name])
unity_package_build.copy_file_to_project("LICENSE.md", ".", package_path, logger)
unity_package_build.copy_file_to_project("CHANGELOG.md", ".", package_path, logger)
def cleanup(logger):
logger.info("Removing temporary files:")

logger.info(" {}".format(file))
os.remove(file)
# helper function for preparations of tests
def copy_path_to_project(path, repo_path, project_target_path, logger):
logger.info("Copying {}".format(path))
if platform.system() == "Windows":
subprocess.call(["robocopy", os.path.join(repo_path, path), os.path.join(project_target_path, os.path.dirname(path)), "/e", "/np"])
else:
shutil.copytree(os.path.join(repo_path, path),os.path.join(project_target_path, path))
def copy_file_to_project(path, repo_path, project_target_path, logger):
logger.info("Copying {}".format(path))
if platform.system() == "Windows":
subprocess.call(["robocopy", os.path.join(repo_path, os.path.dirname(path)), os.path.join(project_target_path, os.path.dirname(path)), os.path.basename(path), "/np"])
else:
shutil.copy(os.path.join(repo_path, path), os.path.join(project_target_path, path))
import unity_package_build
copy_path_to_project("ImageTemplates", repo_path, dest_path, logger)
copy_path_to_project("Tests", repo_path, dest_path, logger)
copy_file_to_project("SRPMARKER", repo_path, dest_path, logger)
copy_file_to_project("SRPMARKER.meta", repo_path, dest_path, logger)
copy_file_to_project("ImageTemplates.meta", repo_path, dest_path, logger)
copy_file_to_project("Tests.meta", repo_path, dest_path, logger)
unity_package_build.copy_path_to_project("ImageTemplates", repo_path, dest_path, logger)
unity_package_build.copy_path_to_project("Tests", repo_path, dest_path, logger)
unity_package_build.copy_file_to_project("SRPMARKER", repo_path, dest_path, logger)
unity_package_build.copy_file_to_project("SRPMARKER.meta", repo_path, dest_path, logger)
unity_package_build.copy_file_to_project("ImageTemplates.meta", repo_path, dest_path, logger)
unity_package_build.copy_file_to_project("Tests.meta", repo_path, dest_path, logger)
if __name__ == "__main__":
import sys

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


Shader "Hidden/HDRenderPipeline/Sky/SkyHDRI"
Shader "Hidden/HDRenderPipeline/Sky/HDRISky"
{
HLSLINCLUDE

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/ProceduralSky/ProceduralSky.shader


// It's been ported to HDRP in order to have a basic procedural sky
// It has been left mostly untouched but has been adapted to run per-pixel instead of per vertex
// ==================================================================================================
Shader "Hidden/HDRenderPipeline/Sky/SkyProcedural"
Shader "Hidden/HDRenderPipeline/Sky/ProceduralSky"
{
HLSLINCLUDE

static const float kCameraHeight = 0.0001;
#define kRAYLEIGH (lerp(0.0, 0.0025, pow(_AtmosphereThickness,2.5))) // Rayleigh constant
#define kRAYLEIGH (lerp(0.0, 0.0025, PositivePow(_AtmosphereThickness,2.5))) // Rayleigh constant
#define kMIE 0.0010 // Mie constant
#define kSUN_BRIGHTNESS 20.0 // Sun brightness

float3 kScatteringWavelength = lerp (
kDefaultScatteringWavelength-kVariableRangeForScatteringWavelength,
kDefaultScatteringWavelength+kVariableRangeForScatteringWavelength,
float3(1,1,1) - _SkyTint); // using Tint in sRGB gamma allows for more visually linear interpolation and to keep (.5) at (128, gray in sRGB) point
float3 kInvWavelength = 1.0 / pow(kScatteringWavelength, 4);
float3(1,1,1) - _SkyTint.xyz); // using Tint in sRGB gamma allows for more visually linear interpolation and to keep (.5) at (128, gray in sRGB) point
float3 kInvWavelength = 1.0 / float3(PositivePow(kScatteringWavelength.x, 4), PositivePow(kScatteringWavelength.y, 4), PositivePow(kScatteringWavelength.z, 4));
float kKrESun = kRAYLEIGH * kSUN_BRIGHTNESS;
float kKr4PI = kRAYLEIGH * 4.0 * 3.14159265;

cIn = frontColor * (kInvWavelength * kKrESun + kKmESun);
cOut = clamp(attenuate, 0.0, 1.0);
groundColor = _SkyParam.y * (cIn + _GroundColor * _GroundColor * cOut);
groundColor = _SkyParam.y * (cIn + _GroundColor.rgb * _GroundColor.rgb * cOut);
}
float3 sunColor = float3(0.0, 0.0, 0.0);

11
CHANGELOG.md


# Changelog
All notable changes to this package will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [0.1.6] - 2018-xx-yy
### Changelog starting
Started Changelog

31
LICENSE.md


**Unity Companion Package License v1.0 ("_License_")**
Copyright © 2017 Unity Technologies ApS ("**_Unity_**")
Unity hereby grants to you a worldwide, non-exclusive, no-charge, and royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute the software that is made available with this License ("**_Software_**"), subject to the following terms and conditions:
1. *Unity Companion Use Only*. Exercise of the license granted herein is limited to exercise for the creation, use, and/or distribution of applications, software, or other content pursuant to a valid Unity development engine software license ("**_Engine License_**"). That means while use of the Software is not limited to use in the software licensed under the Engine License, the Software may not be used for any purpose other than the creation, use, and/or distribution of Engine License-dependent applications, software, or other content. No other exercise of the license granted herein is permitted.
1. *No Modification of Engine License*. Neither this License nor any exercise of the license granted herein modifies the Engine License in any way.
1. *Ownership & Grant Back to You*.
3.1. You own your content. In this License, "derivative works" means derivatives of the Software itself--works derived only from the Software by you under this License (for example, modifying the code of the Software itself to improve its efficacy); “derivative works” of the Software do not include, for example, games, apps, or content that you create using the Software. You keep all right, title, and interest to your own content.
3.2. Unity owns its content. While you keep all right, title, and interest to your own content per the above, as between Unity and you, Unity will own all right, title, and interest to all intellectual property rights (including patent, trademark, and copyright) in the Software and derivative works of the Software, and you hereby assign and agree to assign all such rights in those derivative works to Unity.
3.3. You have a license to those derivative works. Subject to this License, Unity grants to you the same worldwide, non-exclusive, no-charge, and royalty-free copyright license to derivative works of the Software you create as is granted to you for the Software under this License.
1. *Trademarks*. You are not granted any right or license under this License to use any trademarks, service marks, trade names, products names, or branding of Unity or its affiliates ("**_Trademarks_**"). Descriptive uses of Trademarks are permitted; see, for example, Unity’s Branding Usage Guidelines at [https://unity3d.com/public-relations/brand](https://unity3d.com/public-relations/brand).
1. *Notices & Third-Party Rights*. This License, including the copyright notice above, must be provided in all substantial portions of the Software and derivative works thereof (or, if that is impracticable, in any other location where such notices are customarily placed). Further, if the Software is accompanied by a Unity "third-party notices" or similar file, you acknowledge and agree that software identified in that file is governed by those separate license terms.
1. *DISCLAIMER, LIMITATION OF LIABILITY*. THE SOFTWARE AND ANY DERIVATIVE WORKS THEREOF IS PROVIDED ON AN "AS IS" BASIS, AND IS PROVIDED WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR NONINFRINGEMENT. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES (WHETHER DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL, INCLUDING PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS, AND BUSINESS INTERRUPTION), OR OTHER LIABILITY WHATSOEVER, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM OR OUT OF, OR IN CONNECTION WITH, THE SOFTWARE OR ANY DERIVATIVE WORKS THEREOF OR THE USE OF OR OTHER DEALINGS IN SAME, EVEN WHERE ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1. *USE IS ACCEPTANCE and License Versions*. Your receipt and use of the Software constitutes your acceptance of this License and its terms and conditions. Software released by Unity under this License may be modified or updated and the License with it; upon any such modification or update, you will comply with the terms of the updated License for any use of any of the Software under the updated License.
1. *Use in Compliance with Law and Termination*. Your exercise of the license granted herein will at all times be in compliance with applicable law and will not infringe any proprietary rights (including intellectual property rights); this License will terminate immediately on any breach by you of this License.
1. *Severability*. If any provision of this License is held to be unenforceable or invalid, that provision will be enforced to the maximum extent possible and the other provisions will remain in full force and effect.
1. *Governing Law and Venue*. This License is governed by and construed in accordance with the laws of Denmark, except for its conflict of laws rules; the United Nations Convention on Contracts for the International Sale of Goods will not apply. If you reside (or your principal place of business is) within the United States, you and Unity agree to submit to the personal and exclusive jurisdiction of and venue in the state and federal courts located in San Francisco County, California concerning any dispute arising out of this License ("**_Dispute_**"). If you reside (or your principal place of business is) outside the United States, you and Unity agree to submit to the personal and exclusive jurisdiction of and venue in the courts located in Copenhagen, Denmark concerning any Dispute.

7
LICENSE.md.meta


fileFormatVersion: 2
guid: 24e71c7cbf0534c148d042e33505be0a
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

11
ScriptableRenderPipeline/Core/CHANGELOG.md


# Changelog
All notable changes to this package will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [0.1.6] - 2018-xx-yy
### Changelog starting
Started Changelog

7
ScriptableRenderPipeline/Core/CHANGELOG.md.meta


fileFormatVersion: 2
guid: 20456a2cc8a214f9d9846725cff9fea4
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

8
ScriptableRenderPipeline/Core/Documentation.meta


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

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

正在加载...
取消
保存