浏览代码

Merge branch 'master' into lw/no_front_to_back_sorting_of_opaques_on_gpu_with_hsr

/main
GitHub 6 年前
当前提交
aae1a458
共有 183 个文件被更改,包括 6185 次插入4472 次删除
  1. 998
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1101_Unlit.png
  2. 6
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1101_Unlit.png.meta
  3. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1102_Unlit_Distortion.png
  4. 17
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1102_Unlit_Distortion.png.meta
  5. 998
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1103_Unlit_Distortion_DepthTest.png
  6. 6
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1103_Unlit_Distortion_DepthTest.png.meta
  7. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1205_Lit_Transparent_Refraction.png
  8. 6
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1205_Lit_Transparent_Refraction.png.meta
  9. 998
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1206_Lit_Transparent_Distortion.png
  10. 6
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1206_Lit_Transparent_Distortion.png.meta
  11. 3
      TestProjects/HDRP_Tests/ProjectSettings/EditorBuildSettings.asset
  12. 3
      TestProjects/LWGraphicsTest/ProjectSettings/EditorBuildSettings.asset
  13. 31
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Common.hlsl
  14. 57
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/UnityInstancing.hlsl
  15. 6
      com.unity.render-pipelines.core/CoreRP/Textures/DepthBits.cs
  16. 9
      com.unity.render-pipelines.high-definition/CHANGELOG.md
  17. 4
      com.unity.render-pipelines.high-definition/HDRP/Camera/HDCameraFrameHistoryType.cs
  18. 21
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.cs
  19. 1
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.hlsl
  20. 15
      com.unity.render-pipelines.high-definition/HDRP/Debug/MipMapDebug.cs
  21. 13
      com.unity.render-pipelines.high-definition/HDRP/Debug/MipMapDebug.cs.hlsl
  22. 60
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalProjectorComponentEditor.cs
  23. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/LitShaderPreprocessor.cs
  24. 3
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDEditorUtils.cs
  25. 3
      com.unity.render-pipelines.high-definition/HDRP/Editor/Upgraders/UpgradeMenuItem.cs
  26. 1
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/PlanarReflectionProbeCache.cs
  27. 7
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalProjectorComponent.cs
  28. 83
      com.unity.render-pipelines.high-definition/HDRP/Material/GGXConvolution/RuntimeFilterIBL.cs
  29. 2
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDCustomSamplerId.cs
  30. 120
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDRenderPipeline.cs
  31. 2
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDRenderPipelineAsset.cs
  32. 6
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDStringConstants.cs
  33. 9
      com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/ApplyDistorsion.compute
  34. 58
      com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/ColorPyramid.compute
  35. 62
      com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/DepthPyramid.compute
  36. 1
      com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset
  37. 1
      com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/RenderPipelineResources.cs
  38. 1
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassVelocity.hlsl
  39. 11
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/VertMesh.hlsl
  40. 19
      com.unity.render-pipelines.lightweight/CHANGELOG.md
  41. 56
      com.unity.render-pipelines.lightweight/LWRP/DefaultRendererSetup.cs
  42. 18
      com.unity.render-pipelines.lightweight/LWRP/Editor/LightweightRenderPipelineLightEditor.cs
  43. 2
      com.unity.render-pipelines.lightweight/LWRP/IAfterDepthPrePass.cs
  44. 2
      com.unity.render-pipelines.lightweight/LWRP/IAfterOpaquePass.cs
  45. 2
      com.unity.render-pipelines.lightweight/LWRP/IAfterOpaquePostProcess.cs
  46. 2
      com.unity.render-pipelines.lightweight/LWRP/IAfterRender.cs
  47. 2
      com.unity.render-pipelines.lightweight/LWRP/IAfterSkyboxPass.cs
  48. 2
      com.unity.render-pipelines.lightweight/LWRP/IAfterTransparentPass.cs
  49. 4
      com.unity.render-pipelines.lightweight/LWRP/IRendererSetup.cs
  50. 91
      com.unity.render-pipelines.lightweight/LWRP/LightweightPipeline.cs
  51. 91
      com.unity.render-pipelines.lightweight/LWRP/LightweightPipelineCore.cs
  52. 4
      com.unity.render-pipelines.lightweight/LWRP/LightweightShadowUtils.cs
  53. 2
      com.unity.render-pipelines.lightweight/LWRP/MaterialHandles.cs
  54. 6
      com.unity.render-pipelines.lightweight/LWRP/Passes/BeginXRRenderingPass.cs
  55. 16
      com.unity.render-pipelines.lightweight/LWRP/Passes/CopyColorPass.cs
  56. 14
      com.unity.render-pipelines.lightweight/LWRP/Passes/CopyDepthPass.cs
  57. 13
      com.unity.render-pipelines.lightweight/LWRP/Passes/CreateLightweightRenderTexturesPass.cs
  58. 10
      com.unity.render-pipelines.lightweight/LWRP/Passes/DepthOnlyPass.cs
  59. 23
      com.unity.render-pipelines.lightweight/LWRP/Passes/DirectionalShadowsPass.cs
  60. 19
      com.unity.render-pipelines.lightweight/LWRP/Passes/DrawSkyboxPass.cs
  61. 6
      com.unity.render-pipelines.lightweight/LWRP/Passes/EndXRRenderingPass.cs
  62. 8
      com.unity.render-pipelines.lightweight/LWRP/Passes/FinalBlitPass.cs
  63. 31
      com.unity.render-pipelines.lightweight/LWRP/Passes/LocalShadowsPass.cs
  64. 11
      com.unity.render-pipelines.lightweight/LWRP/Passes/OpaquePostProcessPass.cs
  65. 48
      com.unity.render-pipelines.lightweight/LWRP/Passes/RenderOpaqueForwardPass.cs
  66. 42
      com.unity.render-pipelines.lightweight/LWRP/Passes/RenderTransparentForwardPass.cs
  67. 4
      com.unity.render-pipelines.lightweight/LWRP/Passes/SceneViewDepthCopy.cs
  68. 18
      com.unity.render-pipelines.lightweight/LWRP/Passes/ScreenSpaceShadowResolvePass.cs
  69. 6
      com.unity.render-pipelines.lightweight/LWRP/Passes/ScriptableRenderPass.cs
  70. 4
      com.unity.render-pipelines.lightweight/LWRP/Passes/SetupForwardRenderingPass.cs
  71. 120
      com.unity.render-pipelines.lightweight/LWRP/Passes/SetupLightweightConstanstPass.cs
  72. 12
      com.unity.render-pipelines.lightweight/LWRP/Passes/TransparentPostProcessPass.cs
  73. 15
      com.unity.render-pipelines.lightweight/LWRP/RenderTargetHandle.cs
  74. 2
      com.unity.render-pipelines.lightweight/LWRP/RenderTargetHandles.cs
  75. 2
      com.unity.render-pipelines.lightweight/LWRP/SampleCount.cs
  76. 2
      com.unity.render-pipelines.lightweight/LWRP/SceneViewDrawMode.cs
  77. 214
      com.unity.render-pipelines.lightweight/LWRP/ScriptableRenderer.cs
  78. 3
      com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Input.hlsl
  79. 43
      com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Lighting.hlsl
  80. 2
      com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Terrain/InputSurfaceTerrain.hlsl
  81. 174
      com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Terrain/LightweightPassLitTerrain.hlsl
  82. 28
      com.unity.render-pipelines.lightweight/LWRP/Shaders/Terrain/LightweightStandardTerrain.shader
  83. 6
      com.unity.render-pipelines.lightweight/LWRP/Shaders/Terrain/LightweightStandardTerrainAddPass.shader
  84. 37
      com.unity.render-pipelines.lightweight/LWRP/Shaders/Terrain/LightweightStandardTerrainBase.shader
  85. 157
      com.unity.shadergraph/CHANGELOG.md
  86. 8
      com.unity.shadergraph/Editor/Data/Graphs/ColorShaderProperty.cs
  87. 9
      com.unity.shadergraph/Editor/Data/Graphs/VectorShaderProperty.cs
  88. 9
      com.unity.shadergraph/Editor/Drawing/MaterialGraphEditWindow.cs
  89. 999
      com.unity.testing.srp.lightweight/Tests/ReferenceImages/Linear/OSXEditor/Metal/053_UnlitShader.png
  90. 999
      com.unity.testing.srp.lightweight/Tests/ReferenceImages/Linear/WindowsEditor/Direct3D11/053_UnlitShader.png
  91. 4
      com.unity.testing.srp.lightweight/Tests/Scenes/035_Shader_TerrainShaders.unity
  92. 10
      com.unity.testing.srp.lightweight/Tests/Scenes/035_Shader_TerrainShaders/New Terrain.asset
  93. 8
      com.unity.testing.srp.lightweight/Tests/Scenes/035_Shader_TerrainShaders/Terrain.mat
  94. 12
      com.unity.testing.srp.lightweight/Tests/Scenes/045_CustomLWPipe/CustomLWPipe.cs
  95. 23
      com.unity.testing.srp.lightweight/Tests/Scenes/052_LWCallbacks/CameraCallbackTests.cs
  96. 8
      TestProjects/HDRP_Tests/Assets/GraphicTests/Scenes/1x_Materials/1601_TerrainLit.meta
  97. 539
      TestProjects/HDRP_Tests/Assets/GraphicTests/Scenes/1x_Materials/1601_TerrainLit.unity
  98. 7
      TestProjects/HDRP_Tests/Assets/GraphicTests/Scenes/1x_Materials/1601_TerrainLit.unity.meta
  99. 1001
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1601_TerrainLit.png

998
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1101_Unlit.png
文件差异内容过多而无法显示
查看文件

6
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1101_Unlit.png.meta


fileFormatVersion: 2
guid: a3f1cb86a1e031a44bd3380ab40642cf
guid: c14640e6cd052a54dbedd03d1de4b094
serializedVersion: 6
serializedVersion: 7
mipmaps:
mipMapMode: 0
enableMipMap: 0

edges: []
weights: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1102_Unlit_Distortion.png
文件差异内容过多而无法显示
查看文件

17
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1102_Unlit_Distortion.png.meta


fileFormatVersion: 2
guid: 74ce626098389e144ae57a1c9e1ad613
guid: 63d4d615f7b52154984007cacaf2f082
serializedVersion: 6
serializedVersion: 7
mipmaps:
mipMapMode: 0
enableMipMap: 0

allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []

edges: []
weights: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

998
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1103_Unlit_Distortion_DepthTest.png
文件差异内容过多而无法显示
查看文件

6
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1103_Unlit_Distortion_DepthTest.png.meta


fileFormatVersion: 2
guid: 5a59cd7fd9c84cb4ca0f998edbb72442
guid: 1e3e18c578889334ba442b1bdab350d1
serializedVersion: 6
serializedVersion: 7
mipmaps:
mipMapMode: 0
enableMipMap: 0

edges: []
weights: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1205_Lit_Transparent_Refraction.png
文件差异内容过多而无法显示
查看文件

6
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1205_Lit_Transparent_Refraction.png.meta


fileFormatVersion: 2
guid: 5812afd0981a5ff4392f8a3ad2fa1080
guid: 5909ed2ce8074034fa8a856ce381404f
serializedVersion: 6
serializedVersion: 7
mipmaps:
mipMapMode: 0
enableMipMap: 0

edges: []
weights: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

998
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1206_Lit_Transparent_Distortion.png
文件差异内容过多而无法显示
查看文件

6
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1206_Lit_Transparent_Distortion.png.meta


fileFormatVersion: 2
guid: b2dd9eeef86426449b5f1a674ab0a5cf
guid: e520e0ec1f31e394fbb8f6b074f6731a
serializedVersion: 6
serializedVersion: 7
mipmaps:
mipMapMode: 0
enableMipMap: 0

edges: []
weights: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

3
TestProjects/HDRP_Tests/ProjectSettings/EditorBuildSettings.asset


path: Assets/GraphicTests/Scenes/1x_Materials/1501_Fabric.unity
guid: ce2b258da0df8d245b659390b6c2ac51
- enabled: 1
path: Assets/GraphicTests/Scenes/1x_Materials/1601_TerrainLit.unity
guid: d52dbea61cf2f884fadf33f8cc6afc0c
- enabled: 1
path: Assets/GraphicTests/Scenes/2x_Lighting/2001_Dynamic_Directional.unity
guid: 09baf18a7e1f6584f86675e6a2141c66
- enabled: 1

3
TestProjects/LWGraphicsTest/ProjectSettings/EditorBuildSettings.asset


- enabled: 1
path: Packages/com.unity.testing.srp.lightweight/Tests/Scenes/053_UnlitShader.unity
guid: a28e1d48e6e3c0e42a4050ab4e770bf8
- enabled: 1
path: Packages/com.unity.testing.srp.lightweight/Tests/Scenes/054_Lighting_Attenuation.unity
guid: 93a99004f07ca6f4dbbc9ccb319c7698
m_configObjects: {}

31
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Common.hlsl


}
// ----------------------------------------------------------------------------
// Terrain/Brush heightmap encoding/decoding
// ----------------------------------------------------------------------------
#if defined(SHADER_API_VULKAN) || defined(SHADER_API_GLES) || defined(SHADER_API_GLES3)
real4 PackHeightmap(real height)
{
uint a = (uint)(65535.0 * height);
return real4((a >> 0) & 0xFF, (a >> 8) & 0xFF, 0, 0) / 255.0;
}
real UnpackHeightmap(real4 height)
{
return (height.r + height.g * 256.0) / 257.0; // (255.0 * height.r + 255.0 * 256.0 * height.g) / 65535.0
}
#else
real4 PackHeightmap(real height)
{
return real4(height, 0, 0, 0);
}
real UnpackHeightmap(real4 height)
{
return height.r;
}
#endif
// ----------------------------------------------------------------------------
// Misc utilities
// ----------------------------------------------------------------------------

57
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/UnityInstancing.hlsl


#define UNITY_SUPPORT_STEREO_INSTANCING
#endif
#if defined(SHADER_API_D3D11) || defined(SHADER_API_GLCORE) || defined(SHADER_API_GLES3) || defined(SHADER_API_VULKAN) || defined(SHADER_API_XBOXONE) || defined(SHADER_API_PSSL) || defined(SHADER_API_METAL) || defined(SHADER_API_SWITCH)
#define UNITY_INSTANCING_AOS
#endif
#if defined(SHADER_API_D3D11) || defined(SHADER_API_GLCORE) || defined(SHADER_API_GLES3) || defined(SHADER_API_METAL) || defined(SHADER_API_PSSL) || defined(SHADER_API_VULKAN)
#if defined(SHADER_API_D3D11) || defined(SHADER_API_GLCORE) || defined(SHADER_API_GLES3) || defined(SHADER_API_METAL) || defined(SHADER_API_PSSL) || defined(SHADER_API_VULKAN) || defined(SHADER_API_SWITCH)
#define UNITY_INSTANCING_SUPPORT_FLEXIBLE_ARRAY_SIZE
#endif

#endif
#endif
#ifdef UNITY_INSTANCING_AOS
#define UNITY_INSTANCING_BUFFER_START(buf) UNITY_INSTANCING_CBUFFER_SCOPE_BEGIN(UnityInstancing_##buf) struct {
#define UNITY_INSTANCING_BUFFER_END(arr) } arr##Array[UNITY_INSTANCED_ARRAY_SIZE]; UNITY_INSTANCING_CBUFFER_SCOPE_END
#define UNITY_DEFINE_INSTANCED_PROP(type, var) type var;
#define UNITY_ACCESS_INSTANCED_PROP(arr, var) arr##Array[unity_InstanceID].var
#else
#define UNITY_INSTANCING_BUFFER_START(buf) UNITY_INSTANCING_CBUFFER_SCOPE_BEGIN(UnityInstancing_##buf)
#define UNITY_INSTANCING_BUFFER_END(arr) UNITY_INSTANCING_CBUFFER_SCOPE_END
#define UNITY_DEFINE_INSTANCED_PROP(type, var) type var[UNITY_INSTANCED_ARRAY_SIZE];
#define UNITY_ACCESS_INSTANCED_PROP(arr, var) var[unity_InstanceID]
#endif
#define UNITY_INSTANCING_BUFFER_START(buf) UNITY_INSTANCING_CBUFFER_SCOPE_BEGIN(UnityInstancing_##buf) struct {
#define UNITY_INSTANCING_BUFFER_END(arr) } arr##Array[UNITY_INSTANCED_ARRAY_SIZE]; UNITY_INSTANCING_CBUFFER_SCOPE_END
#define UNITY_DEFINE_INSTANCED_PROP(type, var) type var;
#define UNITY_ACCESS_INSTANCED_PROP(arr, var) arr##Array[unity_InstanceID].var
// Put worldToObject array to a separate CB if UNITY_ASSUME_UNIFORM_SCALING is defined. Most of the time it will not be used.
#ifdef UNITY_ASSUME_UNIFORM_SCALING

#endif
UNITY_INSTANCING_BUFFER_START(PerDraw0)
UNITY_DEFINE_INSTANCED_PROP(float4x4, unity_ObjectToWorldArray)
#if UNITY_WORLDTOOBJECTARRAY_CB == 0
UNITY_DEFINE_INSTANCED_PROP(float4x4, unity_WorldToObjectArray)
#ifndef UNITY_DONT_INSTANCE_OBJECT_MATRICES
UNITY_DEFINE_INSTANCED_PROP(float4x4, unity_ObjectToWorldArray)
#if UNITY_WORLDTOOBJECTARRAY_CB == 0
UNITY_DEFINE_INSTANCED_PROP(float4x4, unity_WorldToObjectArray)
#endif
#endif
#if defined(UNITY_USE_LODFADE_ARRAY) && defined(UNITY_INSTANCING_SUPPORT_FLEXIBLE_ARRAY_SIZE)
UNITY_DEFINE_INSTANCED_PROP(float2, unity_LODFadeArray)

UNITY_INSTANCING_BUFFER_END(unity_Builtins0)
UNITY_INSTANCING_BUFFER_START(PerDraw1)
#if UNITY_WORLDTOOBJECTARRAY_CB == 1
#if !defined(UNITY_DONT_INSTANCE_OBJECT_MATRICES) && UNITY_WORLDTOOBJECTARRAY_CB == 1
UNITY_DEFINE_INSTANCED_PROP(float4x4, unity_WorldToObjectArray)
#endif
#if defined(UNITY_USE_LODFADE_ARRAY) && !defined(UNITY_INSTANCING_SUPPORT_FLEXIBLE_ARRAY_SIZE)

#endif
UNITY_INSTANCING_BUFFER_END(unity_Builtins2)
#undef UNITY_MATRIX_M
#ifdef MODIFY_MATRIX_FOR_CAMERA_RELATIVE_RENDERING
#define UNITY_MATRIX_M ApplyCameraTranslationToMatrix(UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, unity_ObjectToWorldArray))
#else
#define UNITY_MATRIX_M UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, unity_ObjectToWorldArray)
#endif
#define MERGE_UNITY_BUILTINS_INDEX(X) unity_Builtins##X
#undef UNITY_MATRIX_I_M
#ifdef MODIFY_MATRIX_FOR_CAMERA_RELATIVE_RENDERING
#define UNITY_MATRIX_I_M ApplyCameraTranslationToInverseMatrix(UNITY_ACCESS_INSTANCED_PROP(MERGE_UNITY_BUILTINS_INDEX(UNITY_WORLDTOOBJECTARRAY_CB), unity_WorldToObjectArray))
#else
#define UNITY_MATRIX_I_M UNITY_ACCESS_INSTANCED_PROP(MERGE_UNITY_BUILTINS_INDEX(UNITY_WORLDTOOBJECTARRAY_CB), unity_WorldToObjectArray)
#ifndef UNITY_DONT_INSTANCE_OBJECT_MATRICES
#undef UNITY_MATRIX_M
#undef UNITY_MATRIX_I_M
#define MERGE_UNITY_BUILTINS_INDEX(X) unity_Builtins##X
#ifdef MODIFY_MATRIX_FOR_CAMERA_RELATIVE_RENDERING
#define UNITY_MATRIX_M ApplyCameraTranslationToMatrix(UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, unity_ObjectToWorldArray))
#define UNITY_MATRIX_I_M ApplyCameraTranslationToInverseMatrix(UNITY_ACCESS_INSTANCED_PROP(MERGE_UNITY_BUILTINS_INDEX(UNITY_WORLDTOOBJECTARRAY_CB), unity_WorldToObjectArray))
#else
#define UNITY_MATRIX_M UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, unity_ObjectToWorldArray)
#define UNITY_MATRIX_I_M UNITY_ACCESS_INSTANCED_PROP(MERGE_UNITY_BUILTINS_INDEX(UNITY_WORLDTOOBJECTARRAY_CB), unity_WorldToObjectArray)
#endif
#endif
#else // UNITY_INSTANCING_ENABLED

6
com.unity.render-pipelines.core/CoreRP/Textures/DepthBits.cs


using System.Collections.Generic;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering
{
public enum DepthBits

Depth16 = 16,
Depth24 = 24
Depth24 = 24,
Depth32 = 32
}
}

9
com.unity.render-pipelines.high-definition/CHANGELOG.md


## [3.4.0-preview]
### Added
- Added a new TerrainLit shader that supports rendering of Unity terrains.
### Fixed
- Fixed an issue where sometimes the deferred shadow texture would not be valid, causing wrong rendering.
### Changed
- Changed the way depth & color pyramids are built to be faster and better quality, thus improving the look of distortion and refraction.
## [3.3.0-preview]
### Added

4
com.unity.render-pipelines.high-definition/HDRP/Camera/HDCameraFrameHistoryType.cs


using UnityEngine.Serialization;
DepthPyramid,
ColorPyramid,
VolumetricLighting,
Count
}

21
com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.cs


return mipMapDebugSettings.debugMipMapMode;
}
public DebugMipMapModeTerrainTexture GetDebugMipMapModeTerrainTexture()
{
return mipMapDebugSettings.terrainTexture;
}
public ColorPickerDebugMode GetDebugColorPickerMode()
{
return colorPickerDebugSettings.colorPickerMode;

widgetList.AddRange(new DebugUI.Widget[]
{
new DebugUI.EnumField { displayName = "Fullscreen Debug Mode", getter = () => (int)fullScreenDebugMode, setter = value => fullScreenDebugMode = (FullScreenDebugMode)value, enumNames = renderingFullScreenDebugStrings, enumValues = renderingFullScreenDebugValues },
new DebugUI.EnumField { displayName = "MipMaps", getter = () => (int)mipMapDebugSettings.debugMipMapMode, setter = value => SetMipMapMode((DebugMipMapMode)value), autoEnum = typeof(DebugMipMapMode) },
new DebugUI.EnumField { displayName = "MipMaps", getter = () => (int)mipMapDebugSettings.debugMipMapMode, setter = value => SetMipMapMode((DebugMipMapMode)value), autoEnum = typeof(DebugMipMapMode), onValueChanged = RefreshRenderingDebug },
});
if (mipMapDebugSettings.debugMipMapMode != DebugMipMapMode.None)
{
widgetList.Add(new DebugUI.Container
{
children =
{
new DebugUI.EnumField { displayName = "Terrain Texture", getter = ()=>(int)mipMapDebugSettings.terrainTexture, setter = value => mipMapDebugSettings.terrainTexture = (DebugMipMapModeTerrainTexture)value, autoEnum = typeof(DebugMipMapModeTerrainTexture) }
}
});
}
widgetList.AddRange(new []
{
new DebugUI.Container
{
displayName = "Color Picker",

1
com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.hlsl


int _DebugLightingSubMode;
int _DebugViewMaterial; // Contain the id (define in various materialXXX.cs.hlsl) of the property to display
int _DebugMipMapMode; // Match enum DebugMipMapMode
int _DebugMipMapModeTerrainTexture; // Match enum DebugMipMapModeTerrainTexture
int _ColorPickerMode; // Match enum ColorPickerDebugMode
int _DebugStep;
float4 _DebugLightingAlbedo; // x == bool override, yzw = albedo for diffuse

15
com.unity.render-pipelines.high-definition/HDRP/Debug/MipMapDebug.cs


StreamingMip
}
[GenerateHLSL]
public enum DebugMipMapModeTerrainTexture
{
Control,
Layer0,
Layer1,
Layer2,
Layer3,
Layer4,
Layer5,
Layer6,
Layer7
}
public DebugMipMapModeTerrainTexture terrainTexture = DebugMipMapModeTerrainTexture.Control;
public bool IsDebugDisplayEnabled()
{

13
com.unity.render-pipelines.high-definition/HDRP/Debug/MipMapDebug.cs.hlsl


#define DEBUGMIPMAPMODE_STREAMING_MIP_BUDGET (4)
#define DEBUGMIPMAPMODE_STREAMING_MIP (5)
//
// UnityEngine.Experimental.Rendering.HDPipeline.DebugMipMapModeTerrainTexture: static fields
//
#define DEBUGMIPMAPMODETERRAINTEXTURE_CONTROL (0)
#define DEBUGMIPMAPMODETERRAINTEXTURE_LAYER0 (1)
#define DEBUGMIPMAPMODETERRAINTEXTURE_LAYER1 (2)
#define DEBUGMIPMAPMODETERRAINTEXTURE_LAYER2 (3)
#define DEBUGMIPMAPMODETERRAINTEXTURE_LAYER3 (4)
#define DEBUGMIPMAPMODETERRAINTEXTURE_LAYER4 (5)
#define DEBUGMIPMAPMODETERRAINTEXTURE_LAYER5 (6)
#define DEBUGMIPMAPMODETERRAINTEXTURE_LAYER6 (7)
#define DEBUGMIPMAPMODETERRAINTEXTURE_LAYER7 (8)
#endif

60
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalProjectorComponentEditor.cs


private SerializedProperty m_UVScaleProperty;
private SerializedProperty m_UVBiasProperty;
private SerializedProperty m_AffectsTransparencyProperty;
private SerializedProperty m_Center;
private BoxBoundsHandle m_Handle = new BoxBoundsHandle();
private SerializedProperty m_IsCropModeEnabledProperty;
private DecalProjectorComponentHandle m_Handle = new DecalProjectorComponentHandle();
private void OnEnable()
{

m_UVScaleProperty = serializedObject.FindProperty("m_UVScale");
m_UVBiasProperty = serializedObject.FindProperty("m_UVBias");
m_AffectsTransparencyProperty = serializedObject.FindProperty("m_AffectsTransparency");
m_Center = serializedObject.FindProperty("m_Offset");
m_IsCropModeEnabledProperty = serializedObject.FindProperty("m_IsCropModeEnabled");
}
private void OnDisable()

}
void OnSceneGUI()
{
{
Handles.matrix = m_DecalProjectorComponent.transform.localToWorldMatrix;
Handles.matrix = m_DecalProjectorComponent.transform.localToWorldMatrix;
Vector3 boundsSizePreviousOS = m_Handle.size;
Vector3 boundsMinPreviousOS = m_Handle.size * -0.5f + m_Handle.center;
// adjust decal transform if handle changed
// Adjust decal transform if handle changed.
Undo.RecordObject(m_DecalProjectorComponent, "Decal Projector Change");
m_DecalProjectorComponent.m_Size = m_Handle.size;
m_DecalProjectorComponent.m_Size = m_Handle.size;
EditorUtility.SetDirty(m_DecalProjectorComponent);
Vector3 boundsSizeCurrentOS = m_Handle.size;
Vector3 boundsMinCurrentOS = m_Handle.size * -0.5f + m_Handle.center;
if (m_DecalProjectorComponent.m_IsCropModeEnabled)
{
// Treat decal projector bounds as a crop tool, rather than a scale tool.
// Compute a new uv scale and bias terms to pin decal projection pixels in world space, irrespective of projector bounds.
m_DecalProjectorComponent.m_UVScale.x *= Mathf.Max(1e-5f, boundsSizeCurrentOS.x) / Mathf.Max(1e-5f, boundsSizePreviousOS.x);
m_DecalProjectorComponent.m_UVScale.y *= Mathf.Max(1e-5f, boundsSizeCurrentOS.z) / Mathf.Max(1e-5f, boundsSizePreviousOS.z);
m_DecalProjectorComponent.m_UVBias.x += (boundsMinCurrentOS.x - boundsMinPreviousOS.x) / Mathf.Max(1e-5f, boundsSizeCurrentOS.x) * m_DecalProjectorComponent.m_UVScale.x;
m_DecalProjectorComponent.m_UVBias.y += (boundsMinCurrentOS.z - boundsMinPreviousOS.z) / Mathf.Max(1e-5f, boundsSizeCurrentOS.z) * m_DecalProjectorComponent.m_UVScale.y;
}
// Automatically recenter our transform component if necessary.
// In order to correctly handle world-space snapping, we only perform this recentering when the user is no longer interacting with the gizmo.
if ((GUIUtility.hotControl == 0) && (m_DecalProjectorComponent.m_Offset != Vector3.zero))
{
// Both the DecalProjectorComponent, and the transform will be modified.
// The undo system will automatically group all RecordObject() calls here into a single action.
Undo.RecordObject(m_DecalProjectorComponent.transform, "Decal Projector Change");
// Re-center the transform to the center of the decal projector bounds,
// while maintaining the world-space coordinates of the decal projector boundings vertices.
m_DecalProjectorComponent.transform.Translate(
Vector3.Scale(m_DecalProjectorComponent.m_Offset, m_DecalProjectorComponent.transform.localScale),
Space.Self
);
m_DecalProjectorComponent.m_Offset = Vector3.zero;
}
Handles.matrix = mat;
Handles.color = col;
}

EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_Center);
EditorGUILayout.PropertyField(m_IsCropModeEnabledProperty, new GUIContent("Crop Decal with Gizmo"));
EditorGUILayout.PropertyField(m_Size);
EditorGUILayout.PropertyField(m_MaterialProperty);
EditorGUILayout.PropertyField(m_DrawDistanceProperty);

EditorGUILayout.PropertyField(m_AffectsTransparencyProperty);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/LitShaderPreprocessor.cs


stripperFuncs.Add("HDRenderPipeline/LitTessellation", LitShaderStripper);
stripperFuncs.Add("HDRenderPipeline/LayeredLit", LitShaderStripper);
stripperFuncs.Add("HDRenderPipeline/LayeredLitTessellation", LitShaderStripper);
stripperFuncs.Add("HDRenderPipeline/TerrainLit", LitShaderStripper);
stripperFuncs.Add("Hidden/HDRenderPipeline/TerrainLit_Basemap", LitShaderStripper);
}
}
}

3
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDEditorUtils.cs


{ "HDRenderPipeline/LitTessellation", LitGUI.SetupMaterialKeywordsAndPass },
{ "HDRenderPipeline/Unlit", UnlitGUI.SetupMaterialKeywordsAndPass },
{ "HDRenderPipeline/Fabric", FabricGUI.SetupMaterialKeywordsAndPass },
{ "HDRenderPipeline/Decal", DecalUI.SetupMaterialKeywordsAndPass }
{ "HDRenderPipeline/Decal", DecalUI.SetupMaterialKeywordsAndPass },
{ "HDRenderPipeline/TerrainLit", TerrainLitGUI.SetupMaterialKeywordsAndPass }
};
public static T LoadAsset<T>(string relativePath) where T : UnityEngine.Object

3
com.unity.render-pipelines.high-definition/HDRP/Editor/Upgraders/UpgradeMenuItem.cs


mat.shader.name == "HDRenderPipeline/StackLit" ||
mat.shader.name == "HDRenderPipeline/Unlit" ||
mat.shader.name == "HDRenderPipeline/Fabric" ||
mat.shader.name == "HDRenderPipeline/Decal"
mat.shader.name == "HDRenderPipeline/Decal" ||
mat.shader.name == "HDRenderPipeline/TerrainLit"
)
{
// We don't handle embed material as we can't rewrite fbx files

1
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/PlanarReflectionProbeCache.cs


m_ConvolutionTargetTexture.useMipMap = true;
m_ConvolutionTargetTexture.autoGenerateMips = false;
m_ConvolutionTargetTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf, "PlanarReflectionConvolution", mips: true);
m_ConvolutionTargetTexture.enableRandomWrite = true;
m_ConvolutionTargetTexture.Create();
InitializeProbeBakingStates();

7
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalProjectorComponent.cs


public Vector3 m_Size = new Vector3(1, 1, 1);
private Material m_OldMaterial = null;
private DecalSystem.DecalHandle m_Handle = null;
public bool m_IsCropModeEnabled = false;
public DecalSystem.DecalHandle Handle
{

}
if (m_Handle != null)
{
{
DecalSystem.instance.RemoveDecal(m_Handle);
m_Handle = null;
}

public void OnDisable()
{
if (m_Handle != null)
{
{
DecalSystem.instance.RemoveDecal(m_Handle);
m_Handle = null;
}

public event OnMaterialChangeDelegate OnMaterialChange;
public void OnValidate()
{
{
if (m_Handle != null) // don't do anything if OnEnable hasn't been called yet when scene is loading.
{
Vector4 uvScaleBias = new Vector4(m_UVScale.x, m_UVScale.y, m_UVBias.x, m_UVBias.y);

83
com.unity.render-pipelines.high-definition/HDRP/Material/GGXConvolution/RuntimeFilterIBL.cs


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

Matrix4x4[] m_faceWorldToViewMatrixMatrices = new Matrix4x4[6];
BufferPyramidProcessor m_BufferPyramidProcessor;
List<RenderTexture> m_PlanarColorMips = new List<RenderTexture>();
MipGenerator m_MipGenerator;
public IBLFilterGGX(RenderPipelineResources renderPipelineResources, BufferPyramidProcessor processor)
public IBLFilterGGX(RenderPipelineResources renderPipelineResources, MipGenerator mipGenerator)
m_BufferPyramidProcessor = processor;
m_MipGenerator = mipGenerator;
}
public bool IsInitialized()

{
CoreUtils.Destroy(m_GgxConvolveMaterial);
CoreUtils.Destroy(m_GgxIblSampleData);
for (var i = 0; i < m_PlanarColorMips.Count; ++i)
m_PlanarColorMips[i].Release();
m_PlanarColorMips.Clear();
}
void FilterCubemapCommon(CommandBuffer cmd,

FilterCubemapCommon(cmd, source, target, m_faceWorldToViewMatrixMatrices);
}
public void FilterPlanarTexture(CommandBuffer cmd, Texture source, RenderTexture target)
public void FilterPlanarTexture(CommandBuffer cmd, RenderTexture source, RenderTexture target)
var lodCount = Mathf.Max(Mathf.FloorToInt(Mathf.Log(Mathf.Min(source.width, source.height), 2f)), 0);
for (var i = 0; i < lodCount - 0; ++i)
{
var width = target.width >> (i + 1);
var height = target.height >> (i + 1);
var rtHash = HashRenderTextureProperties(
width,
height,
target.depth,
target.format,
target.sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear
);
var lodIsMissing = i >= m_PlanarColorMips.Count;
RenderTexture rt = null;
var createRT = lodIsMissing
|| (rt = m_PlanarColorMips[i]) == null
|| rtHash != HashRenderTextureProperties(
rt.width, rt.height, rt.depth, rt.format, rt.sRGB
? RenderTextureReadWrite.sRGB
: RenderTextureReadWrite.Linear
);
if (createRT && rt)
rt.Release();
if (createRT)
{
rt = new RenderTexture(
width,
height,
target.depth,
target.format,
target.sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear
);
rt.enableRandomWrite = true;
rt.name = "Planar Convolution Tmp RT";
rt.hideFlags = HideFlags.HideAndDontSave;
rt.Create();
}
if (lodIsMissing)
m_PlanarColorMips.Add(rt);
else if (createRT)
m_PlanarColorMips[i] = rt;
}
m_BufferPyramidProcessor.RenderColorPyramid(
new RectInt(0, 0, source.width, source.height),
cmd,
source,
target,
m_PlanarColorMips,
lodCount
);
m_MipGenerator.RenderColorGaussianPyramid(cmd, new Vector2Int(source.width, source.height), source, target);
}
// Filters MIP map levels (other than 0) with GGX using multiple importance sampling.

m_GgxConvolveMaterial.SetTexture("_MarginalRowDensities", marginalRowCdf);
FilterCubemapCommon(cmd, source, target, m_faceWorldToViewMatrixMatrices);
}
int HashRenderTextureProperties(
int width,
int height,
int depth,
RenderTextureFormat format,
RenderTextureReadWrite sRGB)
{
return width.GetHashCode()
^ height.GetHashCode()
^ depth.GetHashCode()
^ format.GetHashCode()
^ sRGB.GetHashCode();
}
}
}

2
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDCustomSamplerId.cs


{
PushGlobalParameters,
CopySetDepthBuffer,
CopyDepthStencilbuffer,
CopyDepthBuffer,
HTileForSSS,
Forward,
RenderSSAO,

120
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDRenderPipeline.cs


Material m_CopyStencilForNoLighting;
Material m_CopyDepth;
GPUCopy m_GPUCopy;
BufferPyramid m_BufferPyramid;
MipGenerator m_MipGenerator;
IBLFilterGGX m_IBLFilterGGX = null;

// 'm_CameraColorBuffer' does not contain diffuse lighting of SSS materials until the SSS pass. It is stored within 'm_CameraSssDiffuseLightingBuffer'.
RTHandleSystem.RTHandle m_CameraColorBuffer;
RTHandleSystem.RTHandle m_CameraColorBufferMipChain;
RTHandleSystem.RTHandle m_CameraDepthBufferCopy;
RTHandleSystem.RTHandle m_CameraDepthBufferMipChain;
RTHandleSystem.RTHandle m_CameraStencilBufferCopy;
RTHandleSystem.RTHandle m_VelocityBuffer;

m_GPUCopy = new GPUCopy(asset.renderPipelineResources.copyChannelCS);
var bufferPyramidProcessor = new BufferPyramidProcessor(
asset.renderPipelineResources.colorPyramidCS,
asset.renderPipelineResources.depthPyramidCS,
m_GPUCopy,
new TexturePadding(asset.renderPipelineResources.texturePaddingCS)
);
m_BufferPyramid = new BufferPyramid(bufferPyramidProcessor);
m_MipGenerator = new MipGenerator(m_Asset);
EncodeBC6H.DefaultInstance = EncodeBC6H.DefaultInstance ?? new EncodeBC6H(asset.renderPipelineResources.encodeBC6HCS);

m_MaterialList.ForEach(material => material.Build(asset));
m_IBLFilterGGX = new IBLFilterGGX(asset.renderPipelineResources, bufferPyramidProcessor);
m_IBLFilterGGX = new IBLFilterGGX(asset.renderPipelineResources, m_MipGenerator);
m_LightLoop.Build(asset, m_ShadowSettings, m_IBLFilterGGX);

m_SSSBufferManager.InitSSSBuffers(m_GbufferManager, m_Asset.renderPipelineSettings);
m_NormalBufferManager.InitNormalBuffers(m_GbufferManager, m_Asset.renderPipelineSettings);
m_CameraColorBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, enableRandomWrite: true, enableMSAA: true, name: "CameraColor");
m_CameraColorBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, enableRandomWrite: true, enableMSAA: true, useMipMap: false, name: "CameraColor");
m_CameraColorBufferMipChain = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, enableRandomWrite: true, enableMSAA: false, useMipMap: true, autoGenerateMips: false, name: "CameraColorBufferMipChain");
m_CameraDepthStencilBuffer = RTHandles.Alloc(Vector2.one, depthBufferBits: DepthBits.Depth24, colorFormat: RenderTextureFormat.Depth, filterMode: FilterMode.Point, bindTextureMS: true, enableMSAA: true, name: "CameraDepthStencil");
m_CameraDepthStencilBuffer = RTHandles.Alloc(Vector2.one, depthBufferBits: DepthBits.Depth32, colorFormat: RenderTextureFormat.Depth, filterMode: FilterMode.Point, bindTextureMS: true, enableMSAA: true, name: "CameraDepthStencil");
m_CameraDepthBufferCopy = RTHandles.Alloc(Vector2.one, depthBufferBits: DepthBits.Depth24, colorFormat: RenderTextureFormat.Depth, filterMode: FilterMode.Point, bindTextureMS: true, enableMSAA: true, name: "CameraDepthStencilCopy");
m_CameraDepthBufferMipChain = RTHandles.Alloc(Vector2.one, colorFormat: RenderTextureFormat.RFloat, filterMode: FilterMode.Point, sRGB: false, bindTextureMS: true, enableMSAA: true, useMipMap: true, autoGenerateMips: false, enableRandomWrite: true, name: "CameraDepthBufferMipChain");
}
// Technically we won't need this buffer in some cases, but nothing that we can determine at init time.

{
m_GbufferManager.DestroyBuffers();
m_DbufferManager.DestroyBuffers();
m_BufferPyramid.DestroyBuffers();
m_MipGenerator.Release();
RTHandles.Release(m_CameraColorBufferMipChain);
RTHandles.Release(m_CameraDepthBufferCopy);
RTHandles.Release(m_CameraDepthBufferMipChain);
RTHandles.Release(m_CameraStencilBufferCopy);
RTHandles.Release(m_AmbientOcclusionBuffer);

PushGlobalRTHandle(
cmd,
hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.DepthPyramid),
m_CameraDepthBufferMipChain,
HDShaderIDs._DepthPyramidTexture,
HDShaderIDs._DepthPyramidSize,
HDShaderIDs._DepthPyramidScale

hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.ColorPyramid),
m_CameraColorBufferMipChain,
HDShaderIDs._ColorPyramidTexture,
HDShaderIDs._ColorPyramidSize,
HDShaderIDs._ColorPyramidScale

bool NeedDepthBufferCopy()
{
// For now we consider all console to be able to read from a bound depth buffer.
return !IsConsolePlatform();
// We always need it for SSR since depth textures do not support MIP maps.
return !IsConsolePlatform()
|| m_Asset.GetFrameSettings().enableRoughRefraction
|| m_Asset.GetFrameSettings().enableSSR;
}
bool NeedStencilBufferCopy()

RTHandleSystem.RTHandle GetDepthTexture()
{
return NeedDepthBufferCopy() ? m_CameraDepthBufferCopy : m_CameraDepthStencilBuffer;
return NeedDepthBufferCopy() ? m_CameraDepthBufferMipChain : m_CameraDepthStencilBuffer;
}
void CopyDepthBufferIfNeeded(CommandBuffer cmd)

if (NeedDepthBufferCopy())
{
using (new ProfilingSample(cmd, "Copy depth-stencil buffer", CustomSamplerId.CopyDepthStencilbuffer.GetSampler()))
using (new ProfilingSample(cmd, "Copy depth buffer", CustomSamplerId.CopyDepthBuffer.GetSampler()))
cmd.CopyTexture(m_CameraDepthStencilBuffer, m_CameraDepthBufferCopy);
// TODO: maybe we don't actually need the top MIP level?
// That way we could avoid making the copy, and build the MIP hierarchy directly.
// The downside is that our SSR tracing accuracy would decrease a little bit.
// But since we never render SSR at full resolution, this may be acceptable.
m_GPUCopy.SampleCopyChannel_xyzw2x(cmd, m_CameraDepthStencilBuffer, m_CameraDepthBufferMipChain, new RectInt(0, 0, m_CurrentWidth, m_CurrentHeight));
}
}
}

// Depth texture is now ready, bind it (Depth buffer could have been bind before if DBuffer is enable)
cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, GetDepthTexture());
RenderDepthPyramid(hdCamera, cmd, renderContext, FullScreenDebugMode.DepthPyramid);
RenderDepthPyramid(hdCamera, cmd, FullScreenDebugMode.DepthPyramid);
// TODO: In the future we will render object velocity at the same time as depth prepass (we need C++ modification for this)
// Once the C++ change is here we will first render all object without motion vector then motion vector object

HDUtils.SetRenderTarget(cmd, hdCamera, m_ScreenSpaceShadowsBuffer, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}
// In some cases when loading a project for the first time in the editor, the internal resource is destroyed.
// When used as render target, the C++ code will re-create the resource automatically. Since here it's used directly as an UAV, we need to check manually/
if (!m_ScreenSpaceShadowsBuffer.rt.IsCreated())
m_ScreenSpaceShadowsBuffer.rt.Create();
m_LightLoop.RenderScreenSpaceShadows(hdCamera, m_ScreenSpaceShadowsBuffer, GetDepthTexture(), cmd);
PushFullScreenDebugTexture(hdCamera, cmd, m_ScreenSpaceShadowsBuffer, FullScreenDebugMode.ScreenSpaceShadows);
}

// Render pre refraction objects
RenderForward(m_CullResults, hdCamera, renderContext, cmd, ForwardPass.PreRefraction);
RenderColorPyramid(hdCamera, cmd, renderContext, true);
RenderColorPyramid(hdCamera, cmd, true);
// Render all type of transparent forward (unlit, lit, complex (hair...)) to keep the sorting between transparent objects.
RenderForward(m_CullResults, hdCamera, renderContext, cmd, ForwardPass.Transparent);

// Fill depth buffer to reduce artifact for transparent object during postprocess
RenderTransparentDepthPostpass(m_CullResults, hdCamera, renderContext, cmd);
RenderColorPyramid(hdCamera, cmd, renderContext, false);
RenderColorPyramid(hdCamera, cmd, false);
RenderDistortion(hdCamera, cmd, m_Asset.renderPipelineResources);
RenderDistortion(hdCamera, cmd);
StopStereoRendering(renderContext, hdCamera);

}
}
void RenderDistortion(HDCamera hdCamera, CommandBuffer cmd, RenderPipelineResources resources)
void RenderDistortion(HDCamera hdCamera, CommandBuffer cmd)
{
if (!hdCamera.frameSettings.enableDistortion)
return;

var colorPyramidRT = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ColorPyramid);
var pyramidScale = m_BufferPyramid.GetPyramidToScreenScale(hdCamera, colorPyramidRT);
// Need to account for the fact that the gaussian pyramid is actually rendered inside the camera viewport in a square texture so we mutiply by the PyramidToScreen scale
var size = new Vector4(hdCamera.screenSize.x, hdCamera.screenSize.y, pyramidScale.x / hdCamera.screenSize.x, pyramidScale.y / hdCamera.screenSize.y);
var size = new Vector4(hdCamera.actualWidth, hdCamera.actualHeight, 1f / hdCamera.actualWidth, 1f / hdCamera.actualHeight);
cmd.SetComputeTextureParam(m_applyDistortionCS, m_applyDistortionKernel, HDShaderIDs._ColorPyramidTexture, colorPyramidRT);
cmd.SetComputeTextureParam(m_applyDistortionCS, m_applyDistortionKernel, HDShaderIDs._CameraColorTexture, m_CameraColorBuffer);
cmd.SetComputeTextureParam(m_applyDistortionCS, m_applyDistortionKernel, HDShaderIDs._ColorPyramidTexture, m_CameraColorBufferMipChain);
cmd.SetComputeTextureParam(m_applyDistortionCS, m_applyDistortionKernel, HDShaderIDs._Destination, m_CameraColorBuffer);
cmd.SetComputeVectorParam(m_applyDistortionCS, HDShaderIDs._Size, size);
cmd.DispatchCompute(m_applyDistortionCS, m_applyDistortionKernel, Mathf.CeilToInt(size.x / x), Mathf.CeilToInt(size.y / y), 1);

}
}
void RenderColorPyramid(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, bool isPreRefraction)
void RenderColorPyramid(HDCamera hdCamera, CommandBuffer cmd, bool isPreRefraction)
{
if (isPreRefraction)
{

return;
}
// TODO: Move allocation in separate method call in start of the render loop
var cameraRT = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ColorPyramid)
?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.ColorPyramid, m_BufferPyramid.AllocColorRT);
int lodCount;
using (new ProfilingSample(cmd, "Color Pyramid", CustomSamplerId.ColorPyramid.GetSampler()))
m_BufferPyramid.RenderColorPyramid(hdCamera, cmd, renderContext, m_CameraColorBuffer, cameraRT);
Vector2 pyramidScale = m_BufferPyramid.GetPyramidToScreenScale(hdCamera, cameraRT);
PushFullScreenDebugTextureMip(hdCamera, cmd, cameraRT, m_BufferPyramid.GetPyramidLodCount(new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight)), new Vector4(pyramidScale.x, pyramidScale.y, 0.0f, 0.0f), isPreRefraction ? FullScreenDebugMode.PreRefractionColorPyramid : FullScreenDebugMode.FinalColorPyramid);
using (new ProfilingSample(cmd, "Color Gaussian MIP Chain", CustomSamplerId.ColorPyramid))
{
var size = new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight);
lodCount = m_MipGenerator.RenderColorGaussianPyramid(cmd, size, m_CameraColorBuffer, m_CameraColorBufferMipChain);
}
float scaleX = hdCamera.actualWidth / (float)m_CameraColorBufferMipChain.rt.width;
float scaleY = hdCamera.actualHeight / (float)m_CameraColorBufferMipChain.rt.height;
cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, m_CameraColorBufferMipChain);
cmd.SetGlobalVector(HDShaderIDs._ColorPyramidSize, new Vector4(hdCamera.actualWidth, hdCamera.actualHeight, 1f / hdCamera.actualWidth, 1f / hdCamera.actualHeight));
cmd.SetGlobalVector(HDShaderIDs._ColorPyramidScale, new Vector4(scaleX, scaleY, lodCount, 0.0f));
PushFullScreenDebugTextureMip(hdCamera, cmd, m_CameraColorBufferMipChain, lodCount, new Vector4(scaleX, scaleY, 0f, 0f), isPreRefraction ? FullScreenDebugMode.PreRefractionColorPyramid : FullScreenDebugMode.FinalColorPyramid);
void RenderDepthPyramid(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, FullScreenDebugMode debugMode)
void RenderDepthPyramid(HDCamera hdCamera, CommandBuffer cmd, FullScreenDebugMode debugMode)
if (!hdCamera.frameSettings.enableRoughRefraction)
if (!hdCamera.frameSettings.enableRoughRefraction && !hdCamera.frameSettings.enableSSR)
// TODO: Move allocation in separate method call in start of the render loop
var cameraRT = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.DepthPyramid)
?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.DepthPyramid, m_BufferPyramid.AllocDepthRT);
int lodCount;
using (new ProfilingSample(cmd, "Depth Pyramid", CustomSamplerId.DepthPyramid.GetSampler()))
m_BufferPyramid.RenderDepthPyramid(hdCamera, cmd, renderContext, GetDepthTexture(), cameraRT);
using (new ProfilingSample(cmd, "Depth Buffer MIP Chain", CustomSamplerId.DepthPyramid))
{
var size = new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight);
lodCount = m_MipGenerator.RenderMinDepthPyramid(cmd, size, m_CameraDepthBufferMipChain);
}
Vector2 pyramidScale = m_BufferPyramid.GetPyramidToScreenScale(hdCamera, cameraRT);
PushFullScreenDebugTextureMip(hdCamera, cmd, cameraRT, m_BufferPyramid.GetPyramidLodCount(new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight)), new Vector4(pyramidScale.x, pyramidScale.y, 0.0f, 0.0f), debugMode);
float scaleX = hdCamera.actualWidth / (float)m_CameraDepthBufferMipChain.rt.width;
float scaleY = hdCamera.actualHeight / (float)m_CameraDepthBufferMipChain.rt.height;
cmd.SetGlobalTexture(HDShaderIDs._DepthPyramidTexture, m_CameraDepthBufferMipChain);
cmd.SetGlobalVector(HDShaderIDs._DepthPyramidSize, new Vector4(hdCamera.actualWidth, hdCamera.actualHeight, 1f / hdCamera.actualWidth, 1f / hdCamera.actualHeight));
cmd.SetGlobalVector(HDShaderIDs._DepthPyramidScale, new Vector4(scaleX, scaleY, lodCount, 0.0f));
PushFullScreenDebugTextureMip(hdCamera, cmd, m_CameraDepthBufferMipChain, lodCount, new Vector4(scaleX, scaleY, 0f, 0f), debugMode);
}
void RenderPostProcess(HDCamera hdcamera, CommandBuffer cmd, PostProcessLayer layer)

cmd.SetGlobalInt(HDShaderIDs._DebugLightingMode, (int)m_CurrentDebugDisplaySettings.GetDebugLightingMode());
cmd.SetGlobalInt(HDShaderIDs._DebugLightingSubMode, (int)m_CurrentDebugDisplaySettings.GetDebugLightingSubMode());
cmd.SetGlobalInt(HDShaderIDs._DebugMipMapMode, (int)m_CurrentDebugDisplaySettings.GetDebugMipMapMode());
cmd.SetGlobalInt(HDShaderIDs._DebugMipMapModeTerrainTexture, (int)m_CurrentDebugDisplaySettings.GetDebugMipMapModeTerrainTexture());
cmd.SetGlobalInt(HDShaderIDs._ColorPickerMode, (int)m_CurrentDebugDisplaySettings.GetDebugColorPickerMode());
cmd.SetGlobalVector(HDShaderIDs._DebugLightingAlbedo, debugAlbedo);

2
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDRenderPipelineAsset.cs


public override Material GetDefaultTerrainMaterial()
{
return null;
return m_RenderPipelineResources.defaultTerrainMaterial;
}
public override Material GetDefaultUIMaterial()

6
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDStringConstants.cs


public static readonly int _DebugLightingSpecularColor = Shader.PropertyToID("_DebugLightingSpecularColor");
public static readonly int _AmbientOcclusionTexture = Shader.PropertyToID("_AmbientOcclusionTexture");
public static readonly int _DebugMipMapMode = Shader.PropertyToID("_DebugMipMapMode");
public static readonly int _DebugMipMapModeTerrainTexture = Shader.PropertyToID("_DebugMipMapModeTerrainTexture");
public static readonly int _UseTileLightList = Shader.PropertyToID("_UseTileLightList");

public static readonly int _PixelCoordToViewDirWS = Shader.PropertyToID("_PixelCoordToViewDirWS");
public static readonly int _Size = Shader.PropertyToID("_Size");
public static readonly int _Source4 = Shader.PropertyToID("_Source4");
public static readonly int _Result1 = Shader.PropertyToID("_Result1");
public static readonly int _Source = Shader.PropertyToID("_Source");
public static readonly int _Destination = Shader.PropertyToID("_Destination");
public static readonly int _Mip0 = Shader.PropertyToID("_Mip0");
public static readonly int _AtmosphericScatteringType = Shader.PropertyToID("_AtmosphericScatteringType");
public static readonly int _AmbientProbeCoeffs = Shader.PropertyToID("_AmbientProbeCoeffs");

9
com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/ApplyDistorsion.compute


#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "HDRP/Material/Builtin/BuiltinData.hlsl"
#include "HDRP/ShaderVariables.hlsl"
TEXTURE2D(_ColorPyramidTexture);
RW_TEXTURE2D(float4, _CameraColorTexture);
RW_TEXTURE2D(float4, _Destination);
float4 _ColorPyramidScale;
CBUFFER_END
#pragma kernel KMain

return;
// Get source pixel for distortion
float2 distordedUV = float2(dispatchThreadId + int2(distortion * _FetchBias)) * _Size.zw;
float2 distordedUV = float2(dispatchThreadId + int2(distortion * _FetchBias)) * _Size.zw * _ScreenToTargetScale.xy;
_CameraColorTexture[dispatchThreadId] = sampled;
_Destination[dispatchThreadId] = sampled;
}

58
com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/ColorPyramid.compute


#pragma only_renderers d3d11 ps4 xboxone vulkan metal switch
#pragma kernel KColorGaussian KERNEL_SIZE=8 MAIN_GAUSSIAN=KColorGaussian
#pragma kernel KColorDownsample KERNEL_SIZE=8 MAIN_DOWNSAMPLE=KColorDownsample
#pragma kernel KColorDownsampleCopyMip0 KERNEL_SIZE=8 MAIN_DOWNSAMPLE=KColorDownsampleCopyMip0 COPY_MIP_0
#if COPY_MIP_0
RWTexture2D<float4> _Result;
RWTexture2D<float4> _Mip0;
#else
RWTexture2D<float4> _Source;
#endif
RWTexture2D<float4> _Destination;
float4 _Size;
float4 _Size; // x: src width, y: src height, zw: unused
CBUFFER_END
// 16x16 pixels with an 8x8 center that we will be blurring writing out. Each uint is two color

float4 blurred = BlurPixels(s0, s1, s2, s3, s4, s5, s6, s7, s8);
// Write to the final target
_Result[pixelCoord] = blurred;
_Destination[pixelCoord] = blurred;
#pragma kernel KMain
[numthreads(8, 8, 1)]
void KMain(uint2 groupId : SV_GroupID, uint2 groupThreadId : SV_GroupThreadID, uint2 dispatchThreadId : SV_DispatchThreadID)
[numthreads(KERNEL_SIZE, KERNEL_SIZE, 1)]
void MAIN_GAUSSIAN(uint2 groupId : SV_GroupID, uint2 groupThreadId : SV_GroupThreadID, uint2 dispatchThreadId : SV_DispatchThreadID)
// Downsample the block
float2 offset = float2(threadUL);
float4 p00 = _Source.SampleLevel(sampler_LinearClamp, (offset + 0.5) * _Size.zw, 0.0);
float4 p10 = _Source.SampleLevel(sampler_LinearClamp, (offset + float2(1.0, 0.0) + 0.5) * _Size.zw, 0.0);
float4 p01 = _Source.SampleLevel(sampler_LinearClamp, (offset + float2(0.0, 1.0) + 0.5) * _Size.zw, 0.0);
float4 p11 = _Source.SampleLevel(sampler_LinearClamp, (offset + float2(1.0, 1.0) + 0.5) * _Size.zw, 0.0);
uint2 size = uint2(_Size.xy) - 1u;
float4 p00 = _Source[clamp(threadUL + uint2(0u, 0u), 0u, size)];
float4 p10 = _Source[clamp(threadUL + uint2(1u, 0u), 0u, size)];
float4 p11 = _Source[clamp(threadUL + uint2(1u, 1u), 0u, size)];
float4 p01 = _Source[clamp(threadUL + uint2(0u, 1u), 0u, size)];
// Store the 4 downsampled pixels in LDS
uint destIdx = groupThreadId.x + (groupThreadId.y << 4u);

// Vertically blur the pixels in LDS and write the result to memory
BlurVertically(dispatchThreadId, (groupThreadId.y << 3u) + groupThreadId.x);
}
[numthreads(KERNEL_SIZE, KERNEL_SIZE, 1)]
void MAIN_DOWNSAMPLE(uint2 dispatchThreadId : SV_DispatchThreadID)
{
uint2 offset = dispatchThreadId * 2u;
uint2 size = uint2(_Size.xy) - 1u;
uint2 c00 = clamp(offset + uint2(0u, 0u), 0u, size);
uint2 c10 = clamp(offset + uint2(1u, 0u), 0u, size);
uint2 c11 = clamp(offset + uint2(1u, 1u), 0u, size);
uint2 c01 = clamp(offset + uint2(0u, 1u), 0u, size);
float4 p00 = _Source[c00];
float4 p10 = _Source[c10];
float4 p11 = _Source[c11];
float4 p01 = _Source[c01];
#if COPY_MIP_0
_Mip0[c00] = p00;
_Mip0[c10] = p10;
_Mip0[c11] = p11;
_Mip0[c01] = p01;
#endif
_Destination[dispatchThreadId] = (p00 + p01 + p11 + p10) * 0.25;
}

62
com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/DepthPyramid.compute


#include "CoreRP/ShaderLibrary/Common.hlsl"
// ------------------------------------------------
// Algorithm
// ------------------------------------------------
// Downsample a depth texture by taking min value of sampled pixels
// ------------------------------------------------
// Variants
// ------------------------------------------------
#pragma kernel KDepthDownSample8 KERNEL_SIZE=8 KERNEL_NAME=KDepthDownSample8
#pragma kernel KDepthDownSample1 KERNEL_SIZE=1 KERNEL_NAME=KDepthDownSample1
// ------------------------------------------------
// Texture buffers
// ------------------------------------------------
#pragma kernel KDepthDownsample8DualUav KERNEL_SIZE=8 KERNEL_NAME=KDepthDownsample8DualUav
Texture2D<float2> _Source;
RW_TEXTURE2D(float2, _Result);
SamplerState sampler_PointClamp; //TODO: could we use min-sampler instead of using ALU?
RW_TEXTURE2D(float, _Destination);
RW_TEXTURE2D(float, _Source);
// ------------------------------------------------
// Constant buffers
// ------------------------------------------------
float4 _SrcSize;
int2 _RectOffset; // Offset in source texture
float4 _Size; // x: src width, y: src height, zw: unused
// ------------------------------------------------
// Kernel
// ------------------------------------------------
# define MAX_DEPTH(l, r) min(l, r)
# define MAX_DEPTH(l, r) max(l, r)
// Downsample a depth texture by taking the min value of sampled pixels
// The size of the dispatch is (DstMipSize / KernelSize).
void KERNEL_NAME(uint2 groupId : SV_GroupID, uint2 groupThreadId : SV_GroupThreadID, uint2 dispatchThreadId : SV_DispatchThreadID)
void KERNEL_NAME(uint2 dispatchThreadId : SV_DispatchThreadID)
uint2 srcPixelUL = _RectOffset + (dispatchThreadId << 1);
// Offset by 0.5 so sampling get the proper pixels
float2 offset = float2(srcPixelUL) + 0.5;
uint2 srcPixelUL = dispatchThreadId << 1;
#if defined(PLATFORM_SUPPORT_GATHER)
float4 depths = GATHER_RED_TEXTURE2D(_Source, sampler_PointClamp, offset * _SrcSize.zw).wzxy;
#else
float p00 = SAMPLE_TEXTURE2D_LOD(_Source, sampler_PointClamp, (offset) * _SrcSize.zw, 0.0).x;
float p10 = SAMPLE_TEXTURE2D_LOD(_Source, sampler_PointClamp, (offset + float2(1.0, 0.0)) * _SrcSize.zw, 0.0).x;
float p01 = SAMPLE_TEXTURE2D_LOD(_Source, sampler_PointClamp, (offset + float2(0.0, 1.0)) * _SrcSize.zw, 0.0).x;
float p11 = SAMPLE_TEXTURE2D_LOD(_Source, sampler_PointClamp, (offset + float2(1.0, 1.0)) * _SrcSize.zw, 0.0).x;
// '_Source' and '_Destination' are two different MIP levels of the same texture.
// TODO: Use Gather here instead of 4 loads
uint2 size = uint2(_Size.xy) - 1u;
float p00 = _Source[min(srcPixelUL + uint2(0u, 0u), size)];
float p10 = _Source[min(srcPixelUL + uint2(1u, 0u), size)];
float p01 = _Source[min(srcPixelUL + uint2(0u, 1u), size)];
float p11 = _Source[min(srcPixelUL + uint2(1u, 1u), size)];
#endif
float maxDepth = MAX_DEPTH(MAX_DEPTH(depths.x, depths.y), MAX_DEPTH(depths.z, depths.w));
uint2 dstPixel = (_RectOffset >> 1) + dispatchThreadId;
_Result[dstPixel] = float2(minDepth, maxDepth);
_Destination[dispatchThreadId] = minDepth;
#undef MAX_DEPTH

1
com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset


defaultDiffuseMaterial: {fileID: 2100000, guid: 73c176f402d2c2f4d929aa5da7585d17, type: 2}
defaultMirrorMaterial: {fileID: 2100000, guid: 6b17274157b33bc45b6a40e7d4ff51fe, type: 2}
defaultDecalMaterial: {fileID: 2100000, guid: 500e733574922d04ea961553b1b26a63, type: 2}
defaultTerrainMaterial: {fileID: 2100000, guid: 22ff8771d87ef27429e670136399094b, type: 2}
defaultShader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
debugFontTexture: {fileID: 2800000, guid: a3ad2df0e49aaa341a3b3a80f93b3f66, type: 3}
debugDisplayLatlongShader: {fileID: 4800000, guid: c1d1d149a043a5349ba367da6c2051ba, type: 3}

1
com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/RenderPipelineResources.cs


public Material defaultDiffuseMaterial;
public Material defaultMirrorMaterial;
public Material defaultDecalMaterial;
public Material defaultTerrainMaterial;
public Shader defaultShader;
// Debug

1
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassVelocity.hlsl


return normalize(mul((float3x3)unity_MatrixPreviousM, normalOS));
#else
// Normal need to be multiply by inverse transpose
// mul(IT_M, norm) => mul(norm, I_M) => {dot(norm, I_M.col0), dot(norm, I_M.col1), dot(norm, I_M.col2)}
return normalize(mul(normalOS, (float3x3)unity_MatrixPreviousMI));
#endif
}

11
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/VertMesh.hlsl


#endif
// TODO: Here we will also have all the vertex deformation (GPU skinning, vertex animation, morph target...) or we will need to generate a compute shaders instead (better! but require work to deal with unpacking like fp16)
// Make it inout so that VelocityPass can get the modified input values later.
#if defined(HAVE_MESH_MODIFICATION)
input = ApplyMeshModification(input);
#endif
#if defined(HAVE_MESH_MODIFICATION)
input = ApplyMeshModification(input);
#endif
// This return the camera relative position (if enable)
float3 positionRWS = TransformObjectToWorld(input.positionOS);
#ifdef ATTRIBUTES_NEED_NORMAL

#endif
#ifdef ATTRIBUTES_NEED_TANGENT
float4 tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
float4 tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
#endif
// Do vertex modification in camera relative space (if enable)

19
com.unity.render-pipelines.lightweight/CHANGELOG.md


## [3.4.0-preview]
### Added
- When you have enabled Gizmos, they now appear correctly in the Game view.
- Added requiresDepthPrepass field to RenderingData struct to tell if the runtime platform requires a depth prepass to generate a camera depth texture.
- The `RenderingData` struct now holds a reference to `CullResults`.
- When __HDR__ is enabled in the Camera but disabled in the Asset, an information box in the Camera Inspector informs you about it.
- When __MSAA__ is enabled in the Camera but disabled in the Asset, an information box in the Camera Inspector informs you about it.
- Enabled instancing on the terrain shader.
### Changed
- The `RenderingData` struct is now read-only.
- `ScriptableRenderer`always perform a Clear before calling `IRendererSetup::Setup.`
- `ScriptableRenderPass::Execute` no longer takes `CullResults` as input. Instead, use `RenderingData`as input, since that references `CullResults`.
- `IRendererSetup_Setup` no longer takes `ScriptableRenderContext` and `CullResults` as input.
- Reduced GC pressure by removing several per-frame memory allocations.
- The tooltip for the the camera __MSAA__ property now appears correctly.
- Add callbacks to LWRP that can be attached to a camera (IBeforeCameraRender, IAfterDepthPrePass, IAfterOpaquePass, IAfterOpaquePostProcess, IAfterSkyboxPass, IAfterTransparentPass, IAfterRender)
- Added callbacks to LWRP that can be attached to a camera (IBeforeCameraRender, IAfterDepthPrePass, IAfterOpaquePass, IAfterOpaquePostProcess, IAfterSkyboxPass, IAfterTransparentPass, IAfterRender)
###Changed
- Clean up LWRP creation of render textures. If we are not going straight to screen ensure that we create both depth and color targets.

### Fixed
- Lightweight Unlit shader UI doesn't throw an error about missing receive shadow property anymore.
### Changed
- Change real-time attenuation to inverse square.
- Change attenuation for baked GI to inverse square, to match real-time attenuation.
- Small optimization in light attenuation shader code.
## [3.2.0-preview]
### Changed

56
com.unity.render-pipelines.lightweight/LWRP/DefaultRendererSetup.cs


using System;
using System;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.LightweightPipeline

m_Initialized = true;
}
public void Setup(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults, ref RenderingData renderingData)
public void Setup(ScriptableRenderer renderer, ref RenderingData renderingData)
renderer.Clear();
renderer.SetupPerObjectLightIndices(ref cullResults, ref renderingData.lightData);
RenderTextureDescriptor baseDescriptor = ScriptableRenderer.CreateRTDesc(ref renderingData.cameraData);
renderer.SetupPerObjectLightIndices(ref renderingData.cullResults, ref renderingData.lightData);
RenderTextureDescriptor baseDescriptor = ScriptableRenderer.CreateRenderTextureDescriptor(ref renderingData.cameraData);
bool requiresCameraDepth = renderingData.cameraData.requiresDepthTexture;
bool requiresDepthPrepass = renderingData.shadowData.requiresScreenSpaceShadowResolve
|| renderingData.cameraData.isSceneViewCamera
|| (requiresCameraDepth && !ScriptableRenderer.CanCopyDepth(ref renderingData.cameraData));
bool requiresDepthPrepass = renderingData.shadowData.requiresScreenSpaceShadowResolve || renderingData.cameraData.isSceneViewCamera ||
(renderingData.cameraData.requiresDepthTexture && !CanCopyDepth(ref renderingData.cameraData));
// For now VR requires a depth prepass until we figure out how to properly resolve texture2DMS in stereo
requiresDepthPrepass |= renderingData.cameraData.isStereoEnabled;

renderer.EnqueuePass(m_ScreenSpaceShadowResolvePass);
}
bool requiresRenderToTexture =
ScriptableRenderer.RequiresIntermediateColorTexture(
ref renderingData.cameraData,
baseDescriptor);
bool requiresRenderToTexture = ScriptableRenderer.RequiresIntermediateColorTexture(ref renderingData.cameraData, baseDescriptor);
RenderTargetHandle colorHandle = RenderTargetHandle.CameraTarget;
RenderTargetHandle depthHandle = RenderTargetHandle.CameraTarget;

depthHandle = DepthAttachment;
}
}
bool dynamicBatching = renderingData.supportsDynamicBatching;
m_RenderOpaqueForwardPass.Setup(baseDescriptor, colorHandle, depthHandle, ScriptableRenderer.GetCameraClearFlag(camera), camera.backgroundColor, rendererConfiguration, dynamicBatching);
m_RenderOpaqueForwardPass.Setup(baseDescriptor, colorHandle, depthHandle, ScriptableRenderer.GetCameraClearFlag(camera), camera.backgroundColor, rendererConfiguration);
renderingData.cameraData.postProcessLayer.HasOpaqueOnlyEffects(renderer.postProcessRenderContext))
renderingData.cameraData.postProcessLayer.HasOpaqueOnlyEffects(renderer.postProcessingContext))
m_OpaquePostProcessPass.Setup(renderer.postProcessRenderContext, baseDescriptor, colorHandle);
m_OpaquePostProcessPass.Setup(renderer.postProcessingContext, baseDescriptor, colorHandle);
renderer.EnqueuePass(m_OpaquePostProcessPass);
foreach (var pass in camera.GetComponents<IAfterOpaquePostProcess>())

foreach (var pass in camera.GetComponents<IAfterSkyboxPass>())
renderer.EnqueuePass(pass.GetPassToEnqueue(baseDescriptor, colorHandle, depthHandle));
if (requiresCameraDepth && !requiresDepthPrepass)
if (renderingData.cameraData.requiresDepthTexture && !requiresDepthPrepass)
{
m_CopyDepthPass.Setup(depthHandle, DepthTexture);
renderer.EnqueuePass(m_CopyDepthPass);

renderer.EnqueuePass(m_CopyColorPass);
}
m_RenderTransparentForwardPass.Setup(baseDescriptor, colorHandle, depthHandle, ClearFlag.None, camera.backgroundColor, rendererConfiguration, dynamicBatching);
m_RenderTransparentForwardPass.Setup(baseDescriptor, colorHandle, depthHandle, rendererConfiguration);
renderer.EnqueuePass(m_RenderTransparentForwardPass);
foreach (var pass in camera.GetComponents<IAfterTransparentPass>())

{
m_TransparentPostProcessPass.Setup(renderer.postProcessRenderContext, baseDescriptor, colorHandle, BuiltinRenderTextureType.CameraTarget);
m_TransparentPostProcessPass.Setup(renderer.postProcessingContext, baseDescriptor, colorHandle, BuiltinRenderTextureType.CameraTarget);
renderer.EnqueuePass(m_TransparentPostProcessPass);
}
else if (!renderingData.cameraData.isOffscreenRender && colorHandle != RenderTargetHandle.CameraTarget)

renderer.EnqueuePass(m_SceneViewDepthCopyPass);
}
#endif
}
bool CanCopyDepth(ref CameraData cameraData)
{
bool msaaEnabledForCamera = (int)cameraData.msaaSamples > 1;
bool supportsTextureCopy = SystemInfo.copyTextureSupport != CopyTextureSupport.None;
bool supportsDepthTarget = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.Depth);
bool supportsDepthCopy = !msaaEnabledForCamera && (supportsDepthTarget || supportsTextureCopy);
// TODO: We don't have support to highp Texture2DMS currently and this breaks depth precision.
// currently disabling it until shader changes kick in.
//bool msaaDepthResolve = msaaEnabledForCamera && SystemInfo.supportsMultisampledTextures != 0;
bool msaaDepthResolve = false;
return supportsDepthCopy || msaaDepthResolve;
}
}
}

18
com.unity.render-pipelines.lightweight/LWRP/Editor/LightweightRenderPipelineLightEditor.cs


{
[CanEditMultipleObjects]
[CustomEditorForRenderPipeline(typeof(Light), typeof(LightweightPipelineAsset))]
class LightweightLightEditor : LightEditor
internal class LightweightRenderPipelineLightEditor : LightEditor
{
AnimBool m_AnimSpotOptions = new AnimBool();
AnimBool m_AnimPointOptions = new AnimBool();

class Styles
{
public readonly GUIContent SpotAngle = new GUIContent("Spot Angle", "Controls the angle in degrees at the base of a Spot light's cone.");
public readonly GUIContent Cookie = new GUIContent("Cookie", "Specifies the Texture mask to cast shadows, create silhouettes, or patterned illumination for the light.");
public readonly GUIContent CookieSize = new GUIContent("Cookie Size", "Controls the size of the cookie mask currently assigned to the light.");
public readonly GUIContent SpotAngle = EditorGUIUtility.TrTextContent("Spot Angle", "Controls the angle in degrees at the base of a Spot light's cone.");
public readonly GUIStyle invisibleButton = "InvisibleButton";
public readonly GUIContent Cookie = EditorGUIUtility.TrTextContent("Cookie", "Specifies the Texture mask to cast shadows, create silhouettes, or patterned illumination for the light.");
public readonly GUIContent CookieSize = EditorGUIUtility.TrTextContent("Cookie Size", "Controls the size of the cookie mask currently assigned to the light.");
public readonly GUIContent BakingWarning = new GUIContent("Light mode is currently overridden to Realtime mode. Enable Baked Global Illumination to use Mixed or Baked light modes.");
public readonly GUIContent CookieWarning = new GUIContent("Cookie textures for spot lights should be set to clamp, not repeat, to avoid artifacts.");
public readonly GUIContent DisabledLightWarning = new GUIContent("Lighting has been disabled in at least one Scene view. Any changes applied to lights in the Scene will not be updated in these views until Lighting has been enabled again.");
public readonly GUIContent BakingWarning = EditorGUIUtility.TrTextContent("Light mode is currently overridden to Realtime mode. Enable Baked Global Illumination to use Mixed or Baked light modes.");
public readonly GUIContent CookieWarning = EditorGUIUtility.TrTextContent("Cookie textures for spot lights should be set to clamp, not repeat, to avoid artifacts.");
public readonly GUIContent DisabledLightWarning = EditorGUIUtility.TrTextContent("Lighting has been disabled in at least one Scene view. Any changes applied to lights in the Scene will not be updated in these views until Lighting has been enabled again.");
public readonly GUIContent ShadowsNotSupportedWarning = new GUIContent("Realtime shadows for point lights are not supported. Either disable shadows or set the light mode to Baked.");
public readonly GUIContent ShadowsNotSupportedWarning = EditorGUIUtility.TrTextContent("Realtime shadows for point lights are not supported. Either disable shadows or set the light mode to Baked.");
}
static Styles s_Styles;

2
com.unity.render-pipelines.lightweight/LWRP/IAfterDepthPrePass.cs


{
ScriptableRenderPass GetPassToEnqueue(RenderTextureDescriptor baseDescriptor, RenderTargetHandle depthAttachmentHandle);
}
}
}

2
com.unity.render-pipelines.lightweight/LWRP/IAfterOpaquePass.cs


RenderTargetHandle colorAttachmentHandle,
RenderTargetHandle depthAttachmentHandle);
}
}
}

2
com.unity.render-pipelines.lightweight/LWRP/IAfterOpaquePostProcess.cs


ScriptableRenderPass GetPassToEnqueue(RenderTextureDescriptor baseDescriptor, RenderTargetHandle colorHandle,
RenderTargetHandle depthHandle);
}
}
}

2
com.unity.render-pipelines.lightweight/LWRP/IAfterRender.cs


{
ScriptableRenderPass GetPassToEnqueue();
}
}
}

2
com.unity.render-pipelines.lightweight/LWRP/IAfterSkyboxPass.cs


{
ScriptableRenderPass GetPassToEnqueue(RenderTextureDescriptor baseDescriptor, RenderTargetHandle colorHandle, RenderTargetHandle depthHandle);
}
}
}

2
com.unity.render-pipelines.lightweight/LWRP/IAfterTransparentPass.cs


{
ScriptableRenderPass GetPassToEnqueue(RenderTextureDescriptor baseDescriptor, RenderTargetHandle colorHandle, RenderTargetHandle depthHandle);
}
}
}

4
com.unity.render-pipelines.lightweight/LWRP/IRendererSetup.cs


{
public interface IRendererSetup
{
void Setup(ScriptableRenderer renderer, ref ScriptableRenderContext context, ref CullResults cullResults, ref RenderingData renderingData);
void Setup(ScriptableRenderer renderer, ref RenderingData renderingData);
}
}

91
com.unity.render-pipelines.lightweight/LWRP/LightweightPipeline.cs


using System;
using System.Collections.Generic;
using Unity.Collections;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Experimental.Rendering.LightweightPipeline;

using UnityEditor.Experimental.Rendering;
using UnityEngine;
using UnityEngine.Experimental.GlobalIllumination;
using Lightmapping = UnityEngine.Experimental.GlobalIllumination.Lightmapping;
public partial class LightweightPipeline : RenderPipeline
public sealed partial class LightweightPipeline : RenderPipeline
{
static class PerFrameBuffer
{

public LightweightPipelineAsset pipelineAsset { get; private set; }
private static IRendererSetup m_DefaultRendererSetup;
private static IRendererSetup defaultRendererSetup
{

}
}
CameraComparer m_CameraComparer = new CameraComparer();
const string k_RenderCameraTag = "Render Camera";
private PipelineSettings m_PipelineSettings;
PipelineSettings m_PipelineSettings;
public struct PipelineSettings
{

QualitySettings.antiAliasing = m_PipelineSettings.msaaSampleCount;
Shader.globalRenderPipeline = "LightweightPipeline";
Lightmapping.SetDelegate(lightsDelegate);
}
public override void Dispose()

#endif
m_Renderer.Dispose();
Lightmapping.ResetDelegate();
public interface IBeforeCameraRender
{
void ExecuteBeforeCameraRender(ScriptableRenderContext context, Camera camera, PipelineSettings pipelineSettings, ScriptableRenderer renderer);

GraphicsSettings.lightsUseLinearIntensity = true;
SetupPerFrameShaderConstants();
// Sort cameras array by camera depth
Array.Sort(cameras, m_CameraComparer);
SortCameras(cameras);
foreach (Camera camera in cameras)
{
BeginCameraRendering(camera);

public static void RenderSingleCamera(ScriptableRenderContext context, PipelineSettings settings, Camera camera, ref CullResults cullResults, IRendererSetup setup, ScriptableRenderer renderer)
{
string renderCameraTag = camera.name;
CommandBuffer cmd = CommandBufferPool.Get(renderCameraTag);
using (new ProfilingSample(cmd, renderCameraTag))
CommandBuffer cmd = CommandBufferPool.Get(k_RenderCameraTag);
using (new ProfilingSample(cmd, k_RenderCameraTag))
{
CameraData cameraData;
InitializeCameraData(settings, camera, out cameraData);

ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
#endif
CullResults.Cull(ref cullingParameters, context, ref cullResults);
List<VisibleLight> visibleLights = cullResults.visibleLights;
InitializeRenderingData(settings, ref cameraData, visibleLights,
renderer.maxSupportedLocalLightsPerPass, renderer.maxSupportedVertexLights,
out renderingData);
InitializeRenderingData(settings, ref cameraData, ref cullResults,
renderer.maxSupportedLocalLightsPerPass, renderer.maxSupportedVertexLights, out renderingData);
setupToUse.Setup(renderer, ref context, ref cullResults, ref renderingData);
renderer.Execute(ref context, ref cullResults, ref renderingData);
renderer.Clear();
setupToUse.Setup(renderer, ref renderingData);
renderer.Execute(context, ref renderingData);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);

Rect cameraRect = camera.rect;
cameraData.isDefaultViewport = (!(Math.Abs(cameraRect.x) > 0.0f || Math.Abs(cameraRect.y) > 0.0f ||
Math.Abs(cameraRect.width) < 1.0f || Math.Abs(cameraRect.height) < 1.0f));
Math.Abs(cameraRect.width) < 1.0f || Math.Abs(cameraRect.height) < 1.0f));
// If XR is enabled, use XR renderScale.
// If XR is enabled, use XR renderScale.
// Discard variations lesser than kRenderScaleThreshold.
// Scale is only enabled for gameview.
float usedRenderScale = XRGraphicsConfig.enabled ? settings.savedXRGraphicsConfig.renderScale : settings.renderScale;

cameraData.defaultOpaqueSortFlags = canSkipFrontToBackSorting ? noFrontToBackOpaqueFlags : commonOpaqueFlags;
}
static void InitializeRenderingData(PipelineSettings settings, ref CameraData cameraData,
List<VisibleLight> visibleLights, int maxSupportedLocalLightsPerPass, int maxSupportedVertexLights,
static void InitializeRenderingData(PipelineSettings settings, ref CameraData cameraData, ref CullResults cullResults,
int maxSupportedLocalLightsPerPass, int maxSupportedVertexLights,
List<VisibleLight> visibleLights = cullResults.visibleLights;
bool hasDirectionalShadowCastingLight = false;
bool hasLocalShadowCastingLight = false;

}
}
renderingData.cullResults = cullResults;
renderingData.cameraData = cameraData;
InitializeLightData(settings, visibleLights, maxSupportedLocalLightsPerPass, maxSupportedVertexLights, localLightIndices, out renderingData.lightData);
InitializeShadowData(settings, hasDirectionalShadowCastingLight, hasLocalShadowCastingLight, out renderingData.shadowData);

shadowData.localShadowAtlasWidth = shadowData.localShadowAtlasHeight = settings.localShadowAtlasResolution;
shadowData.supportsSoftShadows = settings.supportsSoftShadows;
shadowData.bufferBitCount = 16;
shadowData.renderedDirectionalShadowQuality = LightShadows.None;
shadowData.renderedLocalShadowQuality = LightShadows.None;
}
static void InitializeLightData(PipelineSettings settings, List<VisibleLight> visibleLights,

Matrix4x4 invViewProjMatrix = Matrix4x4.Inverse(viewProjMatrix);
Shader.SetGlobalMatrix(PerCameraBuffer._InvCameraViewProj, invViewProjMatrix);
}
public static Lightmapping.RequestLightsDelegate lightsDelegate = (Light[] requests, NativeArray<LightDataGI> lightsOutput) =>
{
LightDataGI lightData = new LightDataGI();
for (int i = 0; i < requests.Length; i++)
{
Light light = requests[i];
switch (light.type)
{
case LightType.Directional:
DirectionalLight directionalLight = new DirectionalLight();
LightmapperUtils.Extract(light, ref directionalLight); lightData.Init(ref directionalLight);
break;
case LightType.Point:
PointLight pointLight = new PointLight();
LightmapperUtils.Extract(light, ref pointLight); lightData.Init(ref pointLight);
break;
case LightType.Spot:
SpotLight spotLight = new SpotLight();
LightmapperUtils.Extract(light, ref spotLight); lightData.Init(ref spotLight);
break;
case LightType.Area:
RectangleLight rectangleLight = new RectangleLight();
LightmapperUtils.Extract(light, ref rectangleLight); lightData.Init(ref rectangleLight);
break;
default:
lightData.InitNoBake(light.GetInstanceID());
break;
}
lightData.falloff = FalloffType.InverseSquared;
lightsOutput[i] = lightData;
}
};
}
}

91
com.unity.render-pipelines.lightweight/LWRP/LightweightPipelineCore.cs


public struct RenderingData
{
public CullResults cullResults;
public CameraData cameraData;
public LightData lightData;
public ShadowData shadowData;

public int localShadowAtlasHeight;
public bool supportsSoftShadows;
public int bufferBitCount;
public LightShadows renderedDirectionalShadowQuality;
public LightShadows renderedLocalShadowQuality;
}
public class CameraComparer : IComparer<Camera>
{
public int Compare(Camera lhs, Camera rhs)
{
return (int)(lhs.depth - rhs.depth);
}
}
public static class LightweightKeywordStrings

public static readonly string DepthNoMsaa = "_DEPTH_NO_MSAA";
public static readonly string DepthMsaa2 = "_DEPTH_MSAA_2";
public static readonly string DepthMsaa4 = "_DEPTH_MSAA_4";
public static readonly string SoftParticles = "SOFTPARTICLES_ON";
public partial class LightweightPipeline
public sealed partial class LightweightPipeline
static Mesh s_FullscreenMesh = null;
public static Mesh fullscreenMesh
{
get
{
if (s_FullscreenMesh != null)
return s_FullscreenMesh;
float topV = 1.0f;
float bottomV = 0.0f;
Mesh mesh = new Mesh { name = "Fullscreen Quad" };
mesh.SetVertices(new List<Vector3>
{
new Vector3(-1.0f, -1.0f, 0.0f),
new Vector3(-1.0f, 1.0f, 0.0f),
new Vector3(1.0f, -1.0f, 0.0f),
new Vector3(1.0f, 1.0f, 0.0f)
});
mesh.SetUVs(0, new List<Vector2>
{
new Vector2(0.0f, bottomV),
new Vector2(0.0f, topV),
new Vector2(1.0f, bottomV),
new Vector2(1.0f, topV)
});
mesh.SetIndices(new[] { 0, 1, 2, 2, 1, 3 }, MeshTopology.Triangles, 0, false);
mesh.UploadMeshData(true);
return mesh;
}
}
}
public void SortCameras(Camera[] cameras)
{
Array.Sort(cameras, (lhs, rhs) => (int)(lhs.depth - rhs.depth));
}
static void SetPipelineCapabilities(LightweightPipelineAsset pipelineAsset)

if (pipelineAsset.keepSoftShadowVariants)
s_PipelineCapabilities |= PipelineCapabilities.SoftShadows;
}
}
public static void DrawFullScreen(CommandBuffer commandBuffer, Material material,
MaterialPropertyBlock properties = null, int shaderPassId = 0)
{
commandBuffer.DrawMesh(fullscreenMesh, Matrix4x4.identity, material, 0, shaderPassId, properties);
}
public static void GetLightCookieMatrix(VisibleLight light, out Matrix4x4 cookieMatrix)

// Remaining light types don't support cookies
}
public static void CopyTexture(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier dest, Material material)
{
// TODO: In order to issue a copyTexture we need to also check if source and dest have same size
//if (SystemInfo.copyTextureSupport != CopyTextureSupport.None)
// cmd.CopyTexture(source, dest);
//else
cmd.Blit(source, dest, material);
}
public static bool IsSupportedShadowType(LightType lightType)
{
return lightType == LightType.Directional || lightType == LightType.Spot;
}
public static bool IsSupportedCookieType(LightType lightType)
{
return lightType == LightType.Directional || lightType == LightType.Spot;

{
bool isSceneViewCamera = camera.cameraType == CameraType.SceneView;
return XRGraphicsConfig.enabled && !isSceneViewCamera && (camera.stereoTargetEye == StereoTargetEyeMask.Both);
}
public static void RenderPostProcess(CommandBuffer cmd, PostProcessRenderContext context, ref CameraData cameraData, RenderTextureFormat colorFormat, RenderTargetIdentifier source, RenderTargetIdentifier dest, bool opaqueOnly)
{
Camera camera = cameraData.camera;
context.Reset();
context.camera = camera;
context.source = source;
context.sourceFormat = colorFormat;
context.destination = dest;
context.command = cmd;
context.flip = !IsStereoEnabled(camera) && camera.targetTexture == null;
if (opaqueOnly)
cameraData.postProcessLayer.RenderOpaqueOnly(context);
else
cameraData.postProcessLayer.Render(context);
}
}
}

4
com.unity.render-pipelines.lightweight/LWRP/LightweightShadowUtils.cs


{
ShadowSplitData splitData;
bool success = cullResults.ComputeDirectionalShadowMatricesAndCullingPrimitives(shadowLightIndex,
cascadeIndex, shadowData.directionalLightCascadeCount, shadowData.directionalLightCascades, shadowResolution, shadowNearPlane, out viewMatrix, out projMatrix,
out splitData);
cascadeIndex, shadowData.directionalLightCascadeCount, shadowData.directionalLightCascades, shadowResolution, shadowNearPlane, out viewMatrix, out projMatrix,
out splitData);
cascadeSplitDistance = splitData.cullingSphere;
shadowSliceData.offsetX = (cascadeIndex % 2) * shadowResolution;

2
com.unity.render-pipelines.lightweight/LWRP/MaterialHandles.cs


ScrenSpaceShadow,
Count,
}
}
}

6
com.unity.render-pipelines.lightweight/LWRP/Passes/BeginXRRenderingPass.cs


{
public class BeginXRRenderingPass : ScriptableRenderPass
{
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
}
}

16
com.unity.render-pipelines.lightweight/LWRP/Passes/CopyColorPass.cs


{
public class CopyColorPass : ScriptableRenderPass
{
const string k_CopyColorTag = "Copy Color";
public CopyColorPass()
{
m_SampleOffsetShaderHandle = Shader.PropertyToID("_SampleOffset");

this.destination = destination;
}
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
CommandBuffer cmd = CommandBufferPool.Get("Copy Color");
CommandBuffer cmd = CommandBufferPool.Get(k_CopyColorTag);
RenderTextureDescriptor opaqueDesc = ScriptableRenderer.CreateRTDesc(ref renderingData.cameraData, opaqueScaler);
RenderTextureDescriptor opaqueDesc = ScriptableRenderer.CreateRenderTextureDescriptor(ref renderingData.cameraData, opaqueScaler);
RenderTargetIdentifier colorRT = source.Identifier();
RenderTargetIdentifier opaqueColorRT = destination.Identifier();

context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
public override void FrameCleanup(CommandBuffer cmd)
{
if (destination != RenderTargetHandle.CameraTarget)

}
}
}
}

14
com.unity.render-pipelines.lightweight/LWRP/Passes/CopyDepthPass.cs


this.destination = destination;
}
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
{
CommandBuffer cmd = CommandBufferPool.Get(k_DepthCopyTag);
RenderTargetIdentifier depthSurface = source.Identifier();

RenderTextureDescriptor descriptor = ScriptableRenderer.CreateRTDesc(ref renderingData.cameraData);
RenderTextureDescriptor descriptor = ScriptableRenderer.CreateRenderTextureDescriptor(ref renderingData.cameraData);
if (renderingData.cameraData.msaaSamples > 1)
{
cmd.DisableShaderKeyword(LightweightKeywordStrings.DepthNoMsaa);

cmd.EnableShaderKeyword(LightweightKeywordStrings.DepthNoMsaa);
cmd.DisableShaderKeyword(LightweightKeywordStrings.DepthMsaa2);
cmd.DisableShaderKeyword(LightweightKeywordStrings.DepthMsaa4);
LightweightPipeline.CopyTexture(cmd, depthSurface, copyDepthSurface, depthCopyMaterial);
ScriptableRenderer.CopyTexture(cmd, depthSurface, copyDepthSurface, depthCopyMaterial);
public override void FrameCleanup(CommandBuffer cmd)
{
if (destination != RenderTargetHandle.CameraTarget)

13
com.unity.render-pipelines.lightweight/LWRP/Passes/CreateLightweightRenderTexturesPass.cs


{
public class CreateLightweightRenderTexturesPass : ScriptableRenderPass
{
const string k_CreateRenderTexturesTag = "Create Render Textures";
const int k_DepthStencilBufferBits = 32;
private RenderTargetHandle colorAttachmentHandle { get; set; }
private RenderTargetHandle depthAttachmentHandle { get; set; }

descriptor = baseDescriptor;
}
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
CommandBuffer cmd = CommandBufferPool.Get("");
CommandBuffer cmd = CommandBufferPool.Get(k_CreateRenderTexturesTag);
colorDescriptor.msaaSamples = (int) samples;
colorDescriptor.msaaSamples = (int)samples;
cmd.GetTemporaryRT(colorAttachmentHandle.id, colorDescriptor, FilterMode.Bilinear);
}

depthDescriptor.colorFormat = RenderTextureFormat.Depth;
depthDescriptor.depthBufferBits = k_DepthStencilBufferBits;
depthDescriptor.msaaSamples = (int) samples;
depthDescriptor.bindMS = (int) samples > 1;
depthDescriptor.msaaSamples = (int)samples;
depthDescriptor.bindMS = (int)samples > 1;
cmd.GetTemporaryRT(depthAttachmentHandle.id, depthDescriptor, FilterMode.Point);
}

10
com.unity.render-pipelines.lightweight/LWRP/Passes/DepthOnlyPass.cs


};
}
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
{
CommandBuffer cmd = CommandBufferPool.Get(k_DepthPrepassTag);
using (new ProfilingSample(cmd, k_DepthPrepassTag))

{
Camera camera = renderingData.cameraData.camera;
context.StartMultiEye(camera);
context.DrawRenderers(cullResults.visibleRenderers, ref drawSettings, opaqueFilterSettings);
context.DrawRenderers(renderingData.cullResults.visibleRenderers, ref drawSettings, opaqueFilterSettings);
context.DrawRenderers(cullResults.visibleRenderers, ref drawSettings, opaqueFilterSettings);
context.DrawRenderers(renderingData.cullResults.visibleRenderers, ref drawSettings, opaqueFilterSettings);
public override void FrameCleanup(CommandBuffer cmd)
{

depthAttachmentHandle = RenderTargetHandle.CameraTarget;
}
}
}
}

23
com.unity.render-pipelines.lightweight/LWRP/Passes/DirectionalShadowsPass.cs


public static int _ShadowOffset3;
public static int _ShadowmapSize;
}
const int k_MaxCascades = 4;
const int k_ShadowmapBufferBits = 16;
int m_ShadowCasterCascadesCount;

Vector4[] m_CascadeSplitDistances;
const string k_RenderDirectionalShadowmapTag = "Render Directional Shadowmap";
private RenderTargetHandle destination { get; set; }
public DirectionalShadowsPass()

{
this.destination = destination;
}
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
RenderDirectionalCascadeShadowmap(ref context, ref cullResults, ref renderingData.lightData, ref renderingData.shadowData);
RenderDirectionalCascadeShadowmap(ref context, ref renderingData.cullResults, ref renderingData.lightData, ref renderingData.shadowData);
}
}

void RenderDirectionalCascadeShadowmap(ref ScriptableRenderContext context, ref CullResults cullResults, ref LightData lightData, ref ShadowData shadowData)
{
LightShadows shadowQuality = LightShadows.None;
int shadowLightIndex = lightData.mainLightIndex;
if (shadowLightIndex == -1)
return;

var settings = new DrawShadowsSettings(cullResults, shadowLightIndex);
m_DirectionalShadowmapTexture = RenderTexture.GetTemporary(shadowData.directionalShadowAtlasWidth,
shadowData.directionalShadowAtlasHeight, k_ShadowmapBufferBits, m_ShadowmapFormat);
shadowData.directionalShadowAtlasHeight, k_ShadowmapBufferBits, m_ShadowmapFormat);
m_DirectionalShadowmapTexture.filterMode = FilterMode.Bilinear;
m_DirectionalShadowmapTexture.wrapMode = TextureWrapMode.Clamp;
SetRenderTarget(cmd, m_DirectionalShadowmapTexture, RenderBufferLoadAction.DontCare,

}
if (success)
{
shadowQuality = (shadowData.supportsSoftShadows) ? light.shadows : LightShadows.Hard;
}
// TODO: We should have RenderingData as a readonly but currently we need this to pass shadow rendering to litpass
shadowData.renderedDirectionalShadowQuality = shadowQuality;
}
void SetupDirectionalShadowReceiverConstants(CommandBuffer cmd, ref ShadowData shadowData, VisibleLight shadowLight)

cmd.SetGlobalVector(DirectionalShadowConstantBuffer._ShadowOffset2, new Vector4(-invHalfShadowAtlasWidth, invHalfShadowAtlasHeight, 0.0f, 0.0f));
cmd.SetGlobalVector(DirectionalShadowConstantBuffer._ShadowOffset3, new Vector4(invHalfShadowAtlasWidth, invHalfShadowAtlasHeight, 0.0f, 0.0f));
cmd.SetGlobalVector(DirectionalShadowConstantBuffer._ShadowmapSize, new Vector4(invShadowAtlasWidth, invShadowAtlasHeight,
shadowData.directionalShadowAtlasWidth, shadowData.directionalShadowAtlasHeight));
shadowData.directionalShadowAtlasWidth, shadowData.directionalShadowAtlasHeight));
}
};
}

19
com.unity.render-pipelines.lightweight/LWRP/Passes/DrawSkyboxPass.cs


using UnityEngine.Rendering;
using UnityEngine.Rendering;
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
if(renderingData.cameraData.isStereoEnabled && XRGraphicsConfig.eyeTextureDesc.dimension == TextureDimension.Tex2DArray)
if (renderingData.cameraData.isStereoEnabled && XRGraphicsConfig.eyeTextureDesc.dimension == TextureDimension.Tex2DArray)
{
cmd.SetRenderTarget(colorAttachmentHandle.Identifier(), depthAttachmentHandle.Identifier(), 0, CubemapFace.Unknown, -1);
}

context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
}

6
com.unity.render-pipelines.lightweight/LWRP/Passes/EndXRRenderingPass.cs


{
public class EndXRRenderingPass : ScriptableRenderPass
{
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
{
Camera camera = renderingData.cameraData.camera;
context.StopMultiEye(camera);

}
}

8
com.unity.render-pipelines.lightweight/LWRP/Passes/FinalBlitPass.cs


private RenderTargetHandle colorAttachmentHandle { get; set; }
private RenderTextureDescriptor descriptor { get; set; }
public void Setup(RenderTextureDescriptor baseDescriptor, RenderTargetHandle colorAttachmentHandle)
{
this.colorAttachmentHandle = colorAttachmentHandle;

public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
{
Material material = renderingData.cameraData.isStereoEnabled ? null : renderer.GetMaterial(MaterialHandles.Blit);
RenderTargetIdentifier sourceRT = colorAttachmentHandle.Identifier();

cmd.SetViewProjectionMatrices(Matrix4x4.identity, Matrix4x4.identity);
cmd.SetViewport(renderingData.cameraData.camera.pixelRect);
LightweightPipeline.DrawFullScreen(cmd, material);
ScriptableRenderer.RenderFullscreenQuad(cmd, material);
}
else
{

31
com.unity.render-pipelines.lightweight/LWRP/Passes/LocalShadowsPass.cs


public static int _LocalShadowOffset3;
public static int _LocalShadowmapSize;
}
const int k_ShadowmapBufferBits = 16;
RenderTexture m_LocalShadowmapTexture;
RenderTextureFormat m_LocalShadowmapFormat;

float[] m_LocalShadowStrength;
const string k_RenderLocalShadows = "Render Local Shadows";
private RenderTargetHandle destination { get; set; }
public LocalShadowsPass()

? RenderTextureFormat.Shadowmap
: RenderTextureFormat.Depth;
}
if (m_LocalShadowMatrices.Length != maxVisibleLocalLights)
{
m_LocalShadowMatrices = new Matrix4x4[maxVisibleLocalLights];

}
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
RenderLocalShadowmapAtlas(ref context, ref cullResults, ref renderingData.lightData, ref renderingData.shadowData);
RenderLocalShadowmapAtlas(ref context, ref renderingData.cullResults, ref renderingData.lightData, ref renderingData.shadowData);
}
}

Matrix4x4 view, proj;
Bounds bounds;
int shadowSampling = 0;
CommandBuffer cmd = CommandBufferPool.Get(k_RenderLocalShadows);
using (new ProfilingSample(cmd, k_RenderLocalShadows))

int sliceResolution = LightweightShadowUtils.GetMaxTileResolutionInAtlas(atlasWidth, atlasHeight, shadowCastingLightsCount);
m_LocalShadowmapTexture = RenderTexture.GetTemporary(shadowData.localShadowAtlasWidth,
shadowData.localShadowAtlasHeight, k_ShadowmapBufferBits, m_LocalShadowmapFormat);
shadowData.localShadowAtlasHeight, k_ShadowmapBufferBits, m_LocalShadowmapFormat);
m_LocalShadowmapTexture.filterMode = FilterMode.Bilinear;
m_LocalShadowmapTexture.wrapMode = TextureWrapMode.Clamp;

Matrix4x4 shadowTransform;
bool success = LightweightShadowUtils.ExtractSpotLightMatrix(ref cullResults, ref shadowData,
shadowLightIndex, out shadowTransform, out view, out proj);
shadowLightIndex, out shadowTransform, out view, out proj);
if (success)
{

m_LocalLightSlices[i].shadowTransform = shadowTransform;
m_LocalShadowStrength[i] = light.shadowStrength;
shadowSampling = Math.Max(shadowSampling, (int)light.shadows);
if (shadowCastingLightsCount > 1)
LightweightShadowUtils.ApplySliceTransform(ref m_LocalLightSlices[i], atlasWidth, atlasHeight);

}
}
SetupLocalLightsShadowReceiverConstants(ref context, cmd, ref shadowData);
SetupLocalLightsShadowReceiverConstants(cmd, ref shadowData);
// TODO: We should have RenderingData as a readonly but currently we need this to pass shadow rendering to litpass
shadowData.renderedLocalShadowQuality = (shadowData.supportsSoftShadows) ? (LightShadows)shadowSampling : LightShadows.Hard;
void SetupLocalLightsShadowReceiverConstants(ref ScriptableRenderContext context, CommandBuffer cmd, ref ShadowData shadowData)
void SetupLocalLightsShadowReceiverConstants(CommandBuffer cmd, ref ShadowData shadowData)
{
for (int i = 0; i < m_LocalLightSlices.Length; ++i)
m_LocalShadowMatrices[i] = m_LocalLightSlices[i].shadowTransform;

cmd.SetGlobalVector(LocalShadowConstantBuffer._LocalShadowOffset2, new Vector4(-invHalfShadowAtlasWidth, invHalfShadowAtlasHeight, 0.0f, 0.0f));
cmd.SetGlobalVector(LocalShadowConstantBuffer._LocalShadowOffset3, new Vector4(invHalfShadowAtlasWidth, invHalfShadowAtlasHeight, 0.0f, 0.0f));
cmd.SetGlobalVector(LocalShadowConstantBuffer._LocalShadowmapSize, new Vector4(invShadowAtlasWidth, invShadowAtlasHeight,
shadowData.localShadowAtlasWidth, shadowData.localShadowAtlasHeight));
shadowData.localShadowAtlasWidth, shadowData.localShadowAtlasHeight));
}
}
}

11
com.unity.render-pipelines.lightweight/LWRP/Passes/OpaquePostProcessPass.cs


{
public class OpaquePostProcessPass : ScriptableRenderPass
{
const string k_OpaquePostProcessTag = "Render Opaque PostProcess Effects";
private PostProcessRenderContext postContext { get; set; }
public void Setup(
PostProcessRenderContext postProcessRenderContext,

this.colorAttachmentHandle = colorAttachmentHandle;
this.postContext = postProcessRenderContext;
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
CommandBuffer cmd = CommandBufferPool.Get("Render Opaque PostProcess Effects");
CommandBuffer cmd = CommandBufferPool.Get(k_OpaquePostProcessTag);
LightweightPipeline.RenderPostProcess(cmd, postContext, ref renderingData.cameraData, descriptor.colorFormat, source, colorAttachmentHandle.Identifier(), true);
renderer.RenderPostProcess(cmd, ref renderingData.cameraData, descriptor.colorFormat, source, colorAttachmentHandle.Identifier(), true);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}

48
com.unity.render-pipelines.lightweight/LWRP/Passes/RenderOpaqueForwardPass.cs


namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{
public class RenderOpaqueForwardPass : LightweightForwardPass
public class RenderOpaqueForwardPass : ScriptableRenderPass
public FilterRenderersSettings opaqueFilterSettings { get; private set; }
FilterRenderersSettings m_OpaqueFilterSettings;
RenderTargetHandle colorAttachmentHandle { get; set; }
RenderTargetHandle depthAttachmentHandle { get; set; }
RenderTextureDescriptor descriptor { get; set; }
ClearFlag clearFlag { get; set; }
Color clearColor { get; set; }
RendererConfiguration rendererConfiguration;
opaqueFilterSettings = new FilterRenderersSettings(true)
RegisterShaderPassName("LightweightForward");
RegisterShaderPassName("SRPDefaultUnlit");
m_OpaqueFilterSettings = new FilterRenderersSettings(true)
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public void Setup(
RenderTextureDescriptor baseDescriptor,
RenderTargetHandle colorAttachmentHandle,
RenderTargetHandle depthAttachmentHandle,
ClearFlag clearFlag,
Color clearColor,
RendererConfiguration configuration)
{
this.colorAttachmentHandle = colorAttachmentHandle;
this.depthAttachmentHandle = depthAttachmentHandle;
this.clearColor = CoreUtils.ConvertSRGBToActiveColorSpace(clearColor);
this.clearFlag = clearFlag;
descriptor = baseDescriptor;
this.rendererConfiguration = configuration;
}
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
SetRenderTarget(cmd, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, clearFlag, CoreUtils.ConvertSRGBToActiveColorSpace(clearColor));
RenderBufferLoadAction loadOp = RenderBufferLoadAction.DontCare;
RenderBufferStoreAction storeOp = RenderBufferStoreAction.Store;
SetRenderTarget(cmd, colorAttachmentHandle.Identifier(), loadOp, storeOp,
depthAttachmentHandle.Identifier(), loadOp, storeOp, clearFlag, clearColor, descriptor.dimension);
// TODO: We need a proper way to handle multiple camera/ camera stack. Issue is: multiple cameras can share a same RT
// (e.g, split screen games). However devs have to be dilligent with it and know when to clear/preserve color.

Camera camera = renderingData.cameraData.camera;
var sortFlags = renderingData.cameraData.defaultOpaqueSortFlags;
var drawSettings = CreateDrawRendererSettings(camera, sortFlags, rendererConfiguration, dynamicBatching);
context.DrawRenderers(cullResults.visibleRenderers, ref drawSettings, opaqueFilterSettings);
var drawSettings = CreateDrawRendererSettings(camera, sortFlags, rendererConfiguration, renderingData.supportsDynamicBatching);
context.DrawRenderers(renderingData.cullResults.visibleRenderers, ref drawSettings, m_OpaqueFilterSettings);
RenderObjectsWithError(renderer, ref context, ref cullResults, camera, opaqueFilterSettings, SortFlags.None);
renderer.RenderObjectsWithError(context, ref renderingData.cullResults, camera, m_OpaqueFilterSettings, SortFlags.None);
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);

42
com.unity.render-pipelines.lightweight/LWRP/Passes/RenderTransparentForwardPass.cs


namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{
public class RenderTransparentForwardPass : LightweightForwardPass
public class RenderTransparentForwardPass : ScriptableRenderPass
private FilterRenderersSettings transparentFilterSettings { get; set; }
FilterRenderersSettings m_TransparentFilterSettings;
RenderTargetHandle colorAttachmentHandle { get; set; }
RenderTargetHandle depthAttachmentHandle { get; set; }
RenderTextureDescriptor descriptor { get; set; }
RendererConfiguration rendererConfiguration;
transparentFilterSettings = new FilterRenderersSettings(true)
RegisterShaderPassName("LightweightForward");
RegisterShaderPassName("SRPDefaultUnlit");
m_TransparentFilterSettings = new FilterRenderersSettings(true)
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public void Setup(
RenderTextureDescriptor baseDescriptor,
RenderTargetHandle colorAttachmentHandle,
RenderTargetHandle depthAttachmentHandle,
RendererConfiguration configuration)
{
this.colorAttachmentHandle = colorAttachmentHandle;
this.depthAttachmentHandle = depthAttachmentHandle;
descriptor = baseDescriptor;
rendererConfiguration = configuration;
}
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
SetRenderTarget(cmd, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, clearFlag, CoreUtils.ConvertSRGBToActiveColorSpace(clearColor));
RenderBufferLoadAction loadOp = RenderBufferLoadAction.Load;
RenderBufferStoreAction storeOp = RenderBufferStoreAction.Store;
SetRenderTarget(cmd, colorAttachmentHandle.Identifier(), loadOp, storeOp,
depthAttachmentHandle.Identifier(), loadOp, storeOp, ClearFlag.None, Color.black, descriptor.dimension);
var drawSettings = CreateDrawRendererSettings(camera, SortFlags.CommonTransparent, rendererConfiguration, dynamicBatching);
context.DrawRenderers(cullResults.visibleRenderers, ref drawSettings, transparentFilterSettings);
var drawSettings = CreateDrawRendererSettings(camera, SortFlags.CommonTransparent, rendererConfiguration, renderingData.supportsDynamicBatching);
context.DrawRenderers(renderingData.cullResults.visibleRenderers, ref drawSettings, m_TransparentFilterSettings);
RenderObjectsWithError(renderer, ref context, ref cullResults, camera, transparentFilterSettings, SortFlags.None);
renderer.RenderObjectsWithError(context, ref renderingData.cullResults, camera, m_TransparentFilterSettings, SortFlags.None);
}
context.ExecuteCommandBuffer(cmd);

4
com.unity.render-pipelines.lightweight/LWRP/Passes/SceneViewDepthCopy.cs


this.source = source;
}
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
{
// Restore Render target for additional editor rendering.
// Note: Scene view camera always perform depth prepass

18
com.unity.render-pipelines.lightweight/LWRP/Passes/ScreenSpaceShadowResolvePass.cs


namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{
const string k_CollectShadowsTag = "Collect Shadows";
RenderTextureFormat m_ColorFormat;
public ScreenSpaceShadowResolvePass()

descriptor = baseDescriptor;
}
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
if (renderingData.shadowData.renderedDirectionalShadowQuality == LightShadows.None)
if (renderingData.lightData.mainLightIndex == -1)
CommandBuffer cmd = CommandBufferPool.Get("Collect Shadows");
CommandBuffer cmd = CommandBufferPool.Get(k_CollectShadowsTag);
SetShadowCollectPassKeywords(cmd, ref renderingData.shadowData);
VisibleLight shadowLight = renderingData.lightData.visibleLights[renderingData.lightData.mainLightIndex];
SetShadowCollectPassKeywords(cmd, ref shadowLight, ref renderingData.shadowData);
// 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

}
}
void SetShadowCollectPassKeywords(CommandBuffer cmd, ref ShadowData shadowData)
void SetShadowCollectPassKeywords(CommandBuffer cmd, ref VisibleLight shadowLight, ref ShadowData shadowData)
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.SoftShadows, shadowData.renderedDirectionalShadowQuality == LightShadows.Soft);
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.SoftShadows, shadowData.supportsSoftShadows && shadowLight.light.shadows == LightShadows.Soft);
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.CascadeShadows, shadowData.directionalLightCascadeCount > 1);
}
}

6
com.unity.render-pipelines.lightweight/LWRP/Passes/ScriptableRenderPass.cs


public virtual void FrameCleanup(CommandBuffer cmd)
{}
public abstract void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData);
public abstract void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData);
protected void RegisterShaderPassName(string passName)
{

4
com.unity.render-pipelines.lightweight/LWRP/Passes/SetupForwardRenderingPass.cs


{
public class SetupForwardRenderingPass : ScriptableRenderPass
{
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
{
// SetupCameraProperties does the following:
// Setup Camera RenderTarget and Viewport

120
com.unity.render-pipelines.lightweight/LWRP/Passes/SetupLightweightConstanstPass.cs


public static int _AdditionalLightCount;
public static int _AdditionalLightPosition;
public static int _AdditionalLightColor;
public static int _AdditionalLightDistanceAttenuation;
public static int _AdditionalLightAttenuation;
public static int _AdditionalLightSpotAttenuation;
const string k_SetupLightConstants = "Setup Light Constants";
Vector4 k_DefaultLightAttenuation = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
Vector4 k_DefaultLightAttenuation = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
Vector4 k_DefaultLightSpotAttenuation = new Vector4(0.0f, 1.0f, 0.0f, 0.0f);
Vector4[] m_LightDistanceAttenuations;
Vector4[] m_LightAttenuations;
Vector4[] m_LightSpotAttenuations;
private int maxVisibleLocalLights { get; set; }
private ComputeBuffer perObjectLightIndices { get; set; }

LightConstantBuffer._AdditionalLightCount = Shader.PropertyToID("_AdditionalLightCount");
LightConstantBuffer._AdditionalLightPosition = Shader.PropertyToID("_AdditionalLightPosition");
LightConstantBuffer._AdditionalLightColor = Shader.PropertyToID("_AdditionalLightColor");
LightConstantBuffer._AdditionalLightDistanceAttenuation = Shader.PropertyToID("_AdditionalLightDistanceAttenuation");
LightConstantBuffer._AdditionalLightAttenuation = Shader.PropertyToID("_AdditionalLightAttenuation");
LightConstantBuffer._AdditionalLightSpotAttenuation = Shader.PropertyToID("_AdditionalLightSpotAttenuation");
m_LightDistanceAttenuations = new Vector4[0];
m_LightAttenuations = new Vector4[0];
m_LightSpotAttenuations = new Vector4[0];
}
public void Setup(int maxVisibleLocalLights, ComputeBuffer perObjectLightIndices)

m_LightDistanceAttenuations = new Vector4[maxVisibleLocalLights];
m_LightAttenuations = new Vector4[maxVisibleLocalLights];
m_LightSpotAttenuations = new Vector4[maxVisibleLocalLights];
void InitializeLightConstants(List<VisibleLight> lights, int lightIndex, out Vector4 lightPos, out Vector4 lightColor, out Vector4 lightDistanceAttenuation, out Vector4 lightSpotDir,
out Vector4 lightSpotAttenuation)
void InitializeLightConstants(List<VisibleLight> lights, int lightIndex, out Vector4 lightPos, out Vector4 lightColor, out Vector4 lightAttenuation, out Vector4 lightSpotDir)
lightDistanceAttenuation = k_DefaultLightSpotAttenuation;
lightAttenuation = k_DefaultLightAttenuation;
lightSpotAttenuation = k_DefaultLightAttenuation;
float subtractiveMixedLighting = 0.0f;
// When no lights are visible, main light will be set to -1.
// In this case we initialize it to default values and return

else
{
Vector4 pos = lightData.localToWorld.GetColumn(3);
lightPos = new Vector4(pos.x, pos.y, pos.z, 1.0f);
lightPos = new Vector4(pos.x, pos.y, pos.z, 0.0f);
}
// VisibleLight.finalColor already returns color in active color space

if (lightData.lightType != LightType.Directional)
{
// Light attenuation in lightweight matches the unity vanilla one.
// attenuation = 1.0 / 1.0 + distanceToLightSqr * quadraticAttenuation
// then a smooth factor is applied to linearly fade attenuation to light range
// the attenuation smooth factor starts having effect at 80% of light range
// attenuation = 1.0 / distanceToLightSqr
// We offer two different smoothing factors.
// The smoothing factors make sure that the light intensity is zero at the light range limit.
// The first smoothing factor is a linear fade starting at 80 % of the light range.
// The other smoothing factor matches the one used in the Unity lightmapper but is slower than the linear one.
// smoothFactor = (1.0 - saturate((distanceSqr * 1.0 / lightrangeSqr)^2))^2
float quadAtten = 25.0f / lightRangeSqr;
lightDistanceAttenuation = new Vector4(quadAtten, oneOverFadeRangeSqr, lightRangeSqrOverFadeRangeSqr, 1.0f);
float oneOverLightRangeSqr = 1.0f / Mathf.Max(0.0001f, lightData.range * lightData.range);
// On mobile: Use the faster linear smoothing factor.
// On other devices: Use the smoothing factor that matches the GI.
lightAttenuation.x = Application.isMobilePlatform ? oneOverFadeRangeSqr : oneOverLightRangeSqr;
lightAttenuation.y = lightRangeSqrOverFadeRangeSqr;
subtractiveMixedLighting = 1.0f;
}
if (lightData.lightType == LightType.Spot)

float smoothAngleRange = Mathf.Max(0.001f, cosInnerAngle - cosOuterAngle);
float invAngleRange = 1.0f / smoothAngleRange;
float add = -cosOuterAngle * invAngleRange;
lightSpotAttenuation = new Vector4(invAngleRange, add, 0.0f);
lightAttenuation.z = invAngleRange;
lightAttenuation.w = add;
}
Light light = lightData.light;

if (m_MixedLightingSetup == MixedLightingSetup.None && lightData.light.shadows != LightShadows.None)
{
m_MixedLightingSetup = MixedLightingSetup.Subtractive;
lightDistanceAttenuation.w = 0.0f;
subtractiveMixedLighting = 0.0f;
// Use the w component of the light position to indicate subtractive mixed light mode.
// The only directional light is the main light, and the rest are punctual lights.
// The main light will always have w = 0 and the additional lights have w = 1.
lightPos.w = subtractiveMixedLighting;
}
void SetupShaderLightConstants(CommandBuffer cmd, ref LightData lightData)

InitializeLightConstants(lightData.visibleLights, -1, out m_LightPositions[i],
out m_LightColors[i],
out m_LightDistanceAttenuations[i],
out m_LightSpotDirections[i],
out m_LightSpotAttenuations[i]);
out m_LightAttenuations[i],
out m_LightSpotDirections[i]);
m_MixedLightingSetup = MixedLightingSetup.None;

void SetupMainLightConstants(CommandBuffer cmd, ref LightData lightData)
{
Vector4 lightPos, lightColor, lightDistanceAttenuation, lightSpotDir, lightSpotAttenuation;
Vector4 lightPos, lightColor, lightAttenuation, lightSpotDir;
InitializeLightConstants(lightData.visibleLights, lightData.mainLightIndex, out lightPos, out lightColor, out lightDistanceAttenuation, out lightSpotDir, out lightSpotAttenuation);
InitializeLightConstants(lightData.visibleLights, lightData.mainLightIndex, out lightPos, out lightColor, out lightAttenuation, out lightSpotDir);
if (lightData.mainLightIndex >= 0)
{

}
}
cmd.SetGlobalVector(LightConstantBuffer._MainLightPosition, new Vector4(lightPos.x, lightPos.y, lightPos.z, lightDistanceAttenuation.w));
cmd.SetGlobalVector(LightConstantBuffer._MainLightPosition, lightPos);
cmd.SetGlobalVector(LightConstantBuffer._MainLightColor, lightColor);
}

{
InitializeLightConstants(lights, i, out m_LightPositions[localLightsCount],
out m_LightColors[localLightsCount],
out m_LightDistanceAttenuations[localLightsCount],
out m_LightSpotDirections[localLightsCount],
out m_LightSpotAttenuations[localLightsCount]);
out m_LightAttenuations[localLightsCount],
out m_LightSpotDirections[localLightsCount]);
localLightsCount++;
}
}

// if not using a compute buffer, engine will set indices in 2 vec4 constants
// unity_4LightIndices0 and unity_4LightIndices1
if (perObjectLightIndices != null)
cmd.SetGlobalBuffer("_LightIndexBuffer", perObjectLightIndices);
cmd.SetGlobalBuffer(LightConstantBuffer._LightIndexBuffer, perObjectLightIndices);
}
else
{

cmd.SetGlobalVectorArray(LightConstantBuffer._AdditionalLightPosition, m_LightPositions);
cmd.SetGlobalVectorArray(LightConstantBuffer._AdditionalLightColor, m_LightColors);
cmd.SetGlobalVectorArray(LightConstantBuffer._AdditionalLightDistanceAttenuation, m_LightDistanceAttenuations);
cmd.SetGlobalVectorArray(LightConstantBuffer._AdditionalLightAttenuation, m_LightAttenuations);
cmd.SetGlobalVectorArray(LightConstantBuffer._AdditionalLightSpotAttenuation, m_LightSpotAttenuations);
}
void SetShaderKeywords(CommandBuffer cmd, ref CameraData cameraData, ref LightData lightData, ref ShadowData shadowData)

// TODO: We have to discuss cookie approach on LWRP.
// CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.MainLightCookieText, mainLightIndex != -1 && LightweightUtils.IsSupportedCookieType(visibleLights[mainLightIndex].lightType) && visibleLights[mainLightIndex].light.cookie != null);
LightShadows directionalShadowQuality = shadowData.renderedDirectionalShadowQuality;
LightShadows localShadowQuality = shadowData.renderedLocalShadowQuality;
List<VisibleLight> visibleLights = lightData.visibleLights;
// If shadows were resolved in screen space we don't sample shadowmap in lit shader. In that case we just set softDirectionalShadows to false.
bool softDirectionalShadows = shadowData.renderDirectionalShadows && !shadowData.requiresScreenSpaceShadowResolve &&
shadowData.supportsSoftShadows && lightData.mainLightIndex != -1 &&
visibleLights[lightData.mainLightIndex].light.shadows == LightShadows.Soft;
bool softLocalShadows = false;
if (shadowData.renderLocalShadows && shadowData.supportsSoftShadows)
{
List<int> visibleLocalLightIndices = lightData.visibleLocalLightIndices;
for (int i = 0; i < visibleLocalLightIndices.Count; ++i)
{
if (visibleLights[visibleLocalLightIndices[i]].light.shadows == LightShadows.Soft)
{
softLocalShadows = true;
break;
}
}
}
bool hasSoftShadows = (directionalShadowQuality == LightShadows.Soft || localShadowQuality == LightShadows.Soft) &&
shadowData.supportsSoftShadows;
bool hasSoftShadows = softDirectionalShadows || softLocalShadows;
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.DirectionalShadows, directionalShadowQuality != LightShadows.None);
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.LocalShadows, localShadowQuality != LightShadows.None);
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.DirectionalShadows, shadowData.renderDirectionalShadows);
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.LocalShadows, shadowData.renderLocalShadows);
CoreUtils.SetKeyword(cmd, "SOFTPARTICLES_ON", cameraData.requiresSoftParticles);
CoreUtils.SetKeyword(cmd, LightweightKeywordStrings.SoftParticles, cameraData.requiresSoftParticles);
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
CommandBuffer cmd = CommandBufferPool.Get("SetupShaderConstants");
CommandBuffer cmd = CommandBufferPool.Get(k_SetupLightConstants);
SetupShaderLightConstants(cmd, ref renderingData.lightData);
SetShaderKeywords(cmd, ref renderingData.cameraData, ref renderingData.lightData, ref renderingData.shadowData);
context.ExecuteCommandBuffer(cmd);

12
com.unity.render-pipelines.lightweight/LWRP/Passes/TransparentPostProcessPass.cs


{
public class TransparentPostProcessPass : ScriptableRenderPass
{
const string k_PostProcessingTag = "Render PostProcess Effects";
private PostProcessRenderContext postContext { get; set; }
private RenderTargetIdentifier destination { get; set; }
public void Setup(

RenderTargetIdentifier destination)
{
this.colorAttachmentHandle = colorAttachmentHandle;
this.postContext = postProcessRenderContext;
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
CommandBuffer cmd = CommandBufferPool.Get("Render PostProcess Effects");
LightweightPipeline.RenderPostProcess(cmd, postContext, ref renderingData.cameraData, descriptor.colorFormat, colorAttachmentHandle.Identifier(), destination, false);
CommandBuffer cmd = CommandBufferPool.Get(k_PostProcessingTag);
renderer.RenderPostProcess(cmd, ref renderingData.cameraData, descriptor.colorFormat, colorAttachmentHandle.Identifier(), destination, false);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}

15
com.unity.render-pipelines.lightweight/LWRP/RenderTargetHandle.cs


public struct RenderTargetHandle
{
public int id { private set; get; }
public static readonly RenderTargetHandle CameraTarget = new RenderTargetHandle {id = -1};
public void Init(string shaderProperty)

public RenderTargetIdentifier Identifier()
{
if (id == -1)

return new RenderTargetIdentifier(id);
}
public bool Equals(RenderTargetHandle other)
{
return id == other.id;

{
if (ReferenceEquals(null, obj)) return false;
return obj is RenderTargetHandle && Equals((RenderTargetHandle) obj);
return obj is RenderTargetHandle && Equals((RenderTargetHandle)obj);
}
public override int GetHashCode()

public static bool operator ==(RenderTargetHandle c1, RenderTargetHandle c2)
public static bool operator==(RenderTargetHandle c1, RenderTargetHandle c2)
public static bool operator !=(RenderTargetHandle c1, RenderTargetHandle c2)
public static bool operator!=(RenderTargetHandle c1, RenderTargetHandle c2)
}
}

2
com.unity.render-pipelines.lightweight/LWRP/RenderTargetHandles.cs


{
}*/
}
}

2
com.unity.render-pipelines.lightweight/LWRP/SampleCount.cs


Two = 2,
Four = 4,
}
}
}

2
com.unity.render-pipelines.lightweight/LWRP/SceneViewDrawMode.cs


cameraMode.drawMode == DrawCameraMode.ValidateMetalSpecular ||
cameraMode.drawMode == DrawCameraMode.ShadowMasks ||
cameraMode.drawMode == DrawCameraMode.LightOverlap
)
)
return false;
return true;

214
com.unity.render-pipelines.lightweight/LWRP/ScriptableRenderer.cs


using System;
using System.Collections.Generic;
using System.Diagnostics;
public class ScriptableRenderer
public sealed class ScriptableRenderer
{
// Lights are culled per-object. In platforms that don't use StructuredBuffer
// the engine will set 4 light indices in the following constant unity_4LightIndices0

{
get
{
// TODO: Graphics Emulation are breaking StructuredBuffers disabling it for now until
// TODO: Graphics Emulation are breaking StructuredBuffers disabling it for now until
// we have a fix for it
return false;
// return SystemInfo.supportsComputeShaders &&

public int maxSupportedVertexLights { get { return k_MaxVertexLights; } }
public PostProcessRenderContext postProcessRenderContext { get; private set; }
public PostProcessRenderContext postProcessingContext { get; private set; }
static Mesh s_FullscreenMesh = null;
static Mesh fullscreenMesh
{
get
{
if (s_FullscreenMesh != null)
return s_FullscreenMesh;
float topV = 1.0f;
float bottomV = 0.0f;
Mesh mesh = new Mesh { name = "Fullscreen Quad" };
mesh.SetVertices(new List<Vector3>
{
new Vector3(-1.0f, -1.0f, 0.0f),
new Vector3(-1.0f, 1.0f, 0.0f),
new Vector3(1.0f, -1.0f, 0.0f),
new Vector3(1.0f, 1.0f, 0.0f)
});
mesh.SetUVs(0, new List<Vector2>
{
new Vector2(0.0f, bottomV),
new Vector2(0.0f, topV),
new Vector2(1.0f, bottomV),
new Vector2(1.0f, topV)
});
mesh.SetIndices(new[] { 0, 1, 2, 2, 1, 3 }, MeshTopology.Triangles, 0, false);
mesh.UploadMeshData(true);
return mesh;
}
}
List<ShaderPassName> m_LegacyShaderPassNames = new List<ShaderPassName>()
{
new ShaderPassName("Always"),
new ShaderPassName("ForwardBase"),
new ShaderPassName("PrepassBase"),
new ShaderPassName("Vertex"),
new ShaderPassName("VertexLMRGBM"),
new ShaderPassName("VertexLM"),
};
const string k_ReleaseResourcesTag = "Release Resources";
public ScriptableRenderer(LightweightPipelineAsset pipelineAsset)
{
m_Materials = new[]

CoreUtils.CreateEngineMaterial(pipelineAsset.screenSpaceShadowShader),
};
postProcessRenderContext = new PostProcessRenderContext();
postProcessingContext = new PostProcessRenderContext();
}
public void Dispose()

CoreUtils.Destroy(m_Materials[i]);
}
public static RenderTextureDescriptor CreateRTDesc(ref CameraData cameraData, float scaler = 1.0f)
{
Camera camera = cameraData.camera;
RenderTextureDescriptor desc;
float renderScale = cameraData.renderScale;
if (cameraData.isStereoEnabled)
{
return XRGraphicsConfig.eyeTextureDesc;
}
else
{
desc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
}
desc.colorFormat = cameraData.isHdrEnabled ? RenderTextureFormat.DefaultHDR :
RenderTextureFormat.Default;
desc.enableRandomWrite = false;
desc.sRGB = true;
desc.width = (int)((float)desc.width * renderScale * scaler);
desc.height = (int)((float)desc.height * renderScale * scaler);
return desc;
}
public void Execute(ref ScriptableRenderContext context, ref CullResults cullResults, ref RenderingData renderingData)
public void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
m_ActiveRenderPassQueue[i].Execute(this, ref context, ref cullResults, ref renderingData);
m_ActiveRenderPassQueue[i].Execute(this, context, ref renderingData);
DisposePasses(ref context);
}

if (handleID >= m_Materials.Length)
{
Debug.LogError(string.Format("Material {0} is not registered.",
Enum.GetName(typeof(MaterialHandles), handleID)));
Enum.GetName(typeof(MaterialHandles), handleID)));
public void Clear()
{

m_ActiveRenderPassQueue.Add(pass);
}
public static bool RequiresIntermediateColorTexture(ref CameraData cameraData, RenderTextureDescriptor baseDescriptor)
{
if (cameraData.isOffscreenRender)
return false;
bool isScaledRender = !Mathf.Approximately(cameraData.renderScale, 1.0f);
bool isTargetTexture2DArray = baseDescriptor.dimension == TextureDimension.Tex2DArray;
return cameraData.isSceneViewCamera || isScaledRender || cameraData.isHdrEnabled ||
cameraData.postProcessEnabled || cameraData.requiresOpaqueTexture || isTargetTexture2DArray || !cameraData.isDefaultViewport;
}
public static bool CanCopyDepth(ref CameraData cameraData)
{
bool msaaEnabledForCamera = (int)cameraData.msaaSamples > 1;
bool supportsTextureCopy = SystemInfo.copyTextureSupport != CopyTextureSupport.None;
bool supportsDepthTarget = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.Depth);
bool supportsDepthCopy = !msaaEnabledForCamera && (supportsDepthTarget || supportsTextureCopy);
// TODO: We don't have support to highp Texture2DMS currently and this breaks depth precision.
// currently disabling it until shader changes kick in.
//bool msaaDepthResolve = msaaEnabledForCamera && SystemInfo.supportsMultisampledTextures != 0;
bool msaaDepthResolve = false;
return supportsDepthCopy || msaaDepthResolve;
}
void DisposePasses(ref ScriptableRenderContext context)
{
CommandBuffer cmd = CommandBufferPool.Get("Release Resources");
for (int i = 0; i < m_ActiveRenderPassQueue.Count; ++i)
m_ActiveRenderPassQueue[i].FrameCleanup(cmd);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
public void SetupPerObjectLightIndices(ref CullResults cullResults, ref LightData lightData)
{
if (lightData.totalAdditionalLightsCount == 0)

}
}
public void RenderPostProcess(CommandBuffer cmd, ref CameraData cameraData, RenderTextureFormat colorFormat, RenderTargetIdentifier source, RenderTargetIdentifier dest, bool opaqueOnly)
{
Camera camera = cameraData.camera;
postProcessingContext.Reset();
postProcessingContext.camera = camera;
postProcessingContext.source = source;
postProcessingContext.sourceFormat = colorFormat;
postProcessingContext.destination = dest;
postProcessingContext.command = cmd;
postProcessingContext.flip = !cameraData.isStereoEnabled && camera.targetTexture == null;
if (opaqueOnly)
cameraData.postProcessLayer.RenderOpaqueOnly(postProcessingContext);
else
cameraData.postProcessLayer.Render(postProcessingContext);
}
[Conditional("DEVELOPMENT_BUILD"), Conditional("UNITY_EDITOR")]
public void RenderObjectsWithError(ScriptableRenderContext context, ref CullResults cullResults, Camera camera, FilterRenderersSettings filterSettings, SortFlags sortFlags)
{
Material errorMaterial = GetMaterial(MaterialHandles.Error);
if (errorMaterial != null)
{
DrawRendererSettings errorSettings = new DrawRendererSettings(camera, m_LegacyShaderPassNames[0]);
for (int i = 1; i < m_LegacyShaderPassNames.Count; ++i)
errorSettings.SetShaderPassName(i, m_LegacyShaderPassNames[i]);
errorSettings.sorting.flags = sortFlags;
errorSettings.rendererConfiguration = RendererConfiguration.None;
errorSettings.SetOverrideMaterial(errorMaterial, 0);
context.DrawRenderers(cullResults.visibleRenderers, ref errorSettings, filterSettings);
}
}
public static RenderTextureDescriptor CreateRenderTextureDescriptor(ref CameraData cameraData, float scaler = 1.0f)
{
Camera camera = cameraData.camera;
RenderTextureDescriptor desc;
float renderScale = cameraData.renderScale;
if (cameraData.isStereoEnabled)
{
return XRGraphicsConfig.eyeTextureDesc;
}
else
{
desc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
}
desc.colorFormat = cameraData.isHdrEnabled ? RenderTextureFormat.DefaultHDR :
RenderTextureFormat.Default;
desc.enableRandomWrite = false;
desc.sRGB = true;
desc.width = (int)((float)desc.width * renderScale * scaler);
desc.height = (int)((float)desc.height * renderScale * scaler);
return desc;
}
public static bool RequiresIntermediateColorTexture(ref CameraData cameraData, RenderTextureDescriptor baseDescriptor)
{
if (cameraData.isOffscreenRender)
return false;
bool isScaledRender = !Mathf.Approximately(cameraData.renderScale, 1.0f);
bool isTargetTexture2DArray = baseDescriptor.dimension == TextureDimension.Tex2DArray;
return cameraData.isSceneViewCamera || isScaledRender || cameraData.isHdrEnabled ||
cameraData.postProcessEnabled || cameraData.requiresOpaqueTexture || isTargetTexture2DArray || !cameraData.isDefaultViewport;
}
public static ClearFlag GetCameraClearFlag(Camera camera)
{
ClearFlag clearFlag = ClearFlag.None;

}
return configuration;
}
public static void RenderFullscreenQuad(CommandBuffer cmd, Material material, MaterialPropertyBlock properties = null, int shaderPassId = 0)
{
cmd.DrawMesh(fullscreenMesh, Matrix4x4.identity, material, 0, shaderPassId, properties);
}
public static void CopyTexture(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier dest, Material material)
{
// TODO: In order to issue a copyTexture we need to also check if source and dest have same size
//if (SystemInfo.copyTextureSupport != CopyTextureSupport.None)
// cmd.CopyTexture(source, dest);
//else
cmd.Blit(source, dest, material);
}
void DisposePasses(ref ScriptableRenderContext context)
{
CommandBuffer cmd = CommandBufferPool.Get(k_ReleaseResourcesTag);
for (int i = 0; i < m_ActiveRenderPassQueue.Count; ++i)
m_ActiveRenderPassQueue[i].FrameCleanup(cmd);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
}
}

3
com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Input.hlsl


half4 _AdditionalLightCount;
float4 _AdditionalLightPosition[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightColor[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightDistanceAttenuation[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightAttenuation[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightSpotAttenuation[MAX_VISIBLE_LIGHTS];
CBUFFER_END
#if USE_STRUCTURED_BUFFER_FOR_LIGHT_DATA

43
com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Lighting.hlsl


{
float4 position;
half3 color;
half4 distanceAttenuation;
half4 distanceAndSpotAttenuation;
half4 spotAttenuation;
};
// Abstraction over Light shading data.

// Matches Unity Vanila attenuation
// Attenuation smoothly decreases to light range.
half DistanceAttenuation(half distanceSqr, half3 distanceAttenuation)
half DistanceAttenuation(half distanceSqr, half2 distanceAttenuation)
half quadFalloff = distanceAttenuation.x;
half denom = distanceSqr * quadFalloff + 1.0h;
half lightAtten = 1.0h / denom;
half lightAtten = 1.0h / distanceSqr;
#if defined(SHADER_HINT_NICE_QUALITY)
// Use the smoothing factor also used in the Unity lightmapper.
half factor = distanceSqr * distanceAttenuation.x;
half smoothFactor = saturate(1.0h - factor * factor);
smoothFactor = smoothFactor * smoothFactor;
#else
// We need to smoothly fade attenuation to light range. We start fading linearly at 80% of light range
// Therefore:
// fadeDistance = (0.8 * 0.8 * lightRangeSq)

// distanceSqr * distanceAttenuation.y + distanceAttenuation.z
half smoothFactor = saturate(distanceSqr * distanceAttenuation.y + distanceAttenuation.z);
half smoothFactor = saturate(distanceSqr * distanceAttenuation.x + distanceAttenuation.y);
#endif
half SpotAttenuation(half3 spotDirection, half3 lightDirection, half4 spotAttenuation)
half SpotAttenuation(half3 spotDirection, half3 lightDirection, half2 spotAttenuation)
{
// Spot Attenuation with a linear falloff can be defined as
// (SdotL - cosOuterAngle) / (cosInnerAngle - cosOuterAngle)

float distanceSqr = max(dot(posToLightVec, posToLightVec), FLT_MIN);
directionAndAttenuation.xyz = half3(posToLightVec * rsqrt(distanceSqr));
directionAndAttenuation.w = DistanceAttenuation(distanceSqr, lightInput.distanceAttenuation.xyz);
directionAndAttenuation.w *= SpotAttenuation(lightInput.spotDirection.xyz, directionAndAttenuation.xyz, lightInput.spotAttenuation);
return directionAndAttenuation;
}
half4 GetMainLightDirectionAndAttenuation(LightInput lightInput, float3 positionWS)
{
half4 directionAndAttenuation = GetLightDirectionAndAttenuation(lightInput, positionWS);
// Cookies disabled for now due to amount of shader variants
//directionAndAttenuation.w *= CookieAttenuation(positionWS);
directionAndAttenuation.w = DistanceAttenuation(distanceSqr, lightInput.distanceAndSpotAttenuation.xy);
directionAndAttenuation.w *= SpotAttenuation(lightInput.spotDirection.xyz, directionAndAttenuation.xyz, lightInput.distanceAndSpotAttenuation.zw);
return directionAndAttenuation;
}

// dynamic indexing. Ideally we need to configure light data at a cluster of
// objects granularity level. We will only be able to do that when scriptable culling kicks in.
// TODO: Use StructuredBuffer on PC/Console and profile access speed on mobile that support it.
lightInput.position = _AdditionalLightPosition[lightIndex];
float4 positionAndSubtractiveLightMode = _AdditionalLightPosition[lightIndex];
lightInput.position = float4(positionAndSubtractiveLightMode.xyz, 1.);
lightInput.distanceAttenuation = _AdditionalLightDistanceAttenuation[lightIndex];
lightInput.distanceAndSpotAttenuation = _AdditionalLightAttenuation[lightIndex];
lightInput.spotAttenuation = _AdditionalLightSpotAttenuation[lightIndex];
half4 directionAndRealtimeAttenuation = GetLightDirectionAndAttenuation(lightInput, positionWS);

light.attenuation = directionAndRealtimeAttenuation.w;
light.subtractiveModeAttenuation = lightInput.distanceAttenuation.w;
light.subtractiveModeAttenuation = positionAndSubtractiveLightMode.w;
light.color = lightInput.color;
return light;

2
com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Terrain/InputSurfaceTerrain.hlsl


TEXTURE2D(_Splat2);
TEXTURE2D(_Splat3);
#ifdef _TERRAIN_NORMAL_MAP
#ifdef _NORMALMAP
TEXTURE2D(_Normal0); SAMPLER(sampler_Normal0);
TEXTURE2D(_Normal1);
TEXTURE2D(_Normal2);

174
com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Terrain/LightweightPassLitTerrain.hlsl


#include "LWRP/ShaderLibrary/Lighting.hlsl"
#if defined(UNITY_INSTANCING_ENABLED) && defined(_TERRAIN_INSTANCED_PERPIXEL_NORMAL)
#define ENABLE_TERRAIN_PERPIXEL_NORMAL
#endif
#ifdef UNITY_INSTANCING_ENABLED
TEXTURE2D(_TerrainHeightmapTexture);
TEXTURE2D(_TerrainNormalmapTexture);
SAMPLER(sampler_TerrainNormalmapTexture);
float4 _TerrainHeightmapRecipSize; // float4(1.0f/width, 1.0f/height, 1.0f/(width-1), 1.0f/(height-1))
float4 _TerrainHeightmapScale; // float4(hmScale.x, hmScale.y / (float)(kMaxHeight), hmScale.z, 0.0f)
#endif
UNITY_INSTANCING_BUFFER_START(Terrain)
UNITY_DEFINE_INSTANCED_PROP(float4, _TerrainPatchInstanceData) // float4(xBase, yBase, skipScale, ~)
UNITY_INSTANCING_BUFFER_END(Terrain)
float4 tangent : TANGENT;
float2 texcoord1 : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
float4 uvSplat01 : TEXCOORD0; // xy: splat0, zw: splat1
float4 uvSplat23 : TEXCOORD1; // xy: splat2, zw: splat3
float4 uvControlAndLM : TEXCOORD2; // xy: control, zw: lightmap
float4 uvMainAndLM : TEXCOORD0; // xy: control, zw: lightmap
#ifndef TERRAIN_SPLAT_BASEPASS
float4 uvSplat01 : TEXCOORD1; // xy: splat0, zw: splat1
float4 uvSplat23 : TEXCOORD2; // xy: splat2, zw: splat3
#endif
#if _TERRAIN_NORMAL_MAP
#if defined(_NORMALMAP) && !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)
half4 normal : TEXCOORD3; // xyz: normal, w: viewDir.x
half4 tangent : TEXCOORD4; // xyz: tangent, w: viewDir.y
half4 binormal : TEXCOORD5; // xyz: binormal, w: viewDir.z

input.positionWS = IN.positionWS;
#ifdef _TERRAIN_NORMAL_MAP
#if defined(_NORMALMAP) && !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)
#elif defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)
half3 viewDir = IN.viewDir;
float2 sampleCoords = (IN.uvMainAndLM.xy / _TerrainHeightmapRecipSize.zw + 0.5f) * _TerrainHeightmapRecipSize.xy;
half3 normalWS = TransformObjectToWorldNormal(normalize(SAMPLE_TEXTURE2D(_TerrainNormalmapTexture, sampler_TerrainNormalmapTexture, sampleCoords).rgb * 2 - 1));
half3 tangentWS = cross(GetObjectToWorldMatrix()._13_23_33, normalWS);
input.normalWS = TangentToWorldNormal(normalTS, tangentWS, cross(normalWS, tangentWS), normalWS);
#else
half3 viewDir = IN.viewDir;
input.normalWS = FragmentNormalWS(IN.normal);

input.vertexLighting = IN.fogFactorAndVertexLight.yzw;
#ifdef LIGHTMAP_ON
input.bakedGI = SampleLightmap(IN.uvControlAndLM.zw, input.normalWS);
input.bakedGI = SampleLightmap(IN.uvMainAndLM.zw, input.normalWS);
#ifndef TERRAIN_SPLAT_BASEPASS
splatControl = SAMPLE_TEXTURE2D(_Control, sampler_Control, IN.uvControlAndLM.xy);
splatControl = SAMPLE_TEXTURE2D(_Control, sampler_Control, IN.uvMainAndLM.xy);
weight = dot(splatControl, 1.0h);
#if !defined(SHADER_API_MOBILE) && defined(TERRAIN_SPLAT_ADDPASS)

mixedDiffuse += SAMPLE_TEXTURE2D(_Splat2, sampler_Splat0, IN.uvSplat23.xy) * half4(splatControl.bbb, alpha.b);
mixedDiffuse += SAMPLE_TEXTURE2D(_Splat3, sampler_Splat0, IN.uvSplat23.zw) * half4(splatControl.aaa, alpha.a);
#ifdef _TERRAIN_NORMAL_MAP
#ifdef _NORMALMAP
half4 nrm = 0.0f;
nrm += SAMPLE_TEXTURE2D(_Normal0, sampler_Normal0, IN.uvSplat01.xy) * splatControl.r;
nrm += SAMPLE_TEXTURE2D(_Normal1, sampler_Normal0, IN.uvSplat01.zw) * splatControl.g;

#else
mixedNormal = half3(0.0h, 0.0h, 1.0h);
#endif
#ifdef TERRAIN_SPLAT_ADDPASS
ApplyFogColor(color.rgb, half3(0.0h, 0.0h, 0.0h), fogCoord);
#else
ApplyFog(color.rgb, fogCoord);
#ifdef TERRAIN_SPLAT_ADDPASS
ApplyFogColor(color.rgb, half3(0,0,0), fogCoord);
#else
ApplyFog(color.rgb, fogCoord);
#endif
}
void TerrainInstancing(inout float4 vertex, inout float3 normal, inout float2 uv)
{
#ifdef UNITY_INSTANCING_ENABLED
float2 patchVertex = vertex.xy;
float4 instanceData = UNITY_ACCESS_INSTANCED_PROP(Terrain, _TerrainPatchInstanceData);
float2 sampleCoords = (patchVertex.xy + instanceData.xy) * instanceData.z; // (xy + float2(xBase,yBase)) * skipScale
float height = UnpackHeightmap(_TerrainHeightmapTexture.Load(int3(sampleCoords, 0)));
vertex.xz = sampleCoords * _TerrainHeightmapScale.xz;
vertex.y = height * _TerrainHeightmapScale.y;
#ifdef ENABLE_TERRAIN_PERPIXEL_NORMAL
normal = float3(0, 1, 0);
#else
normal = _TerrainNormalmapTexture.Load(int3(sampleCoords, 0)).rgb * 2 - 1;
#endif
uv = sampleCoords * _TerrainHeightmapRecipSize.zw;
}
void TerrainInstancing(inout float4 vertex, inout float3 normal)
{
float2 uv = { 0, 0 };
TerrainInstancing(vertex, normal, uv);
}
///////////////////////////////////////////////////////////////////////////////

VertexOutput SplatmapVert(VertexInput v)
{
VertexOutput o = (VertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
TerrainInstancing(v.vertex, v.normal, v.texcoord);
o.uvMainAndLM.xy = v.texcoord;
o.uvMainAndLM.zw = v.texcoord * unity_LightmapST.xy + unity_LightmapST.zw;
#ifndef TERRAIN_SPLAT_BASEPASS
o.uvControlAndLM.xy = TRANSFORM_TEX(v.texcoord, _Control);
o.uvControlAndLM.zw = v.texcoord1 * unity_LightmapST.xy + unity_LightmapST.zw;
#endif
#ifdef _TERRAIN_NORMAL_MAP
float4 vertexTangent = float4(cross(v.normal, float3(0, 0, 1)), -1.0);
#if defined(_NORMALMAP) && !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)
float4 vertexTangent = float4(cross(float3(0, 0, 1), v.normal), 1.0);
OutputTangentToWorld(vertexTangent, v.normal, o.tangent.xyz, o.binormal.xyz, o.normal.xyz);
o.normal.w = viewDir.x;

return o;
}
TEXTURE2D(_MetallicTex); SAMPLER(sampler_MetallicTex);
half4 SpatmapFragment(VertexOutput IN) : SV_TARGET
half4 SplatmapFragment(VertexOutput IN) : SV_TARGET
half3 normalTS = half3(0.0h, 0.0h, 1.0h);
#ifdef TERRAIN_SPLAT_BASEPASS
half3 albedo = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, IN.uvMainAndLM.xy).rgb;
half smoothness = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, IN.uvMainAndLM.xy).a;
half metallic = SAMPLE_TEXTURE2D(_MetallicTex, sampler_MetallicTex, IN.uvMainAndLM.xy).r;
half alpha = 1;
#else
half3 normalTS;
half3 specular = half3(0.0h, 0.0h, 0.0h);
#endif
half4 color = LightweightFragmentPBR(inputData, albedo, metallic, specular, smoothness, /* occlusion */ 1.0h, /* emission */ half3(0.0h, 0.0h, 0.0h), alpha);
half4 color = LightweightFragmentPBR(inputData, albedo, metallic, half3(0.0h, 0.0h, 0.0h), smoothness, /* occlusion */ 1.0, /* emission */ half3(0, 0, 0), alpha);
}
// Shadow pass
// x: global clip space bias, y: normal world space bias
float4 _ShadowBias;
float3 _LightDirection;
struct VertexInputLean
{
float4 position : POSITION;
float3 normal : NORMAL;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
float4 ShadowPassVertex(VertexInputLean v) : SV_POSITION
{
VertexOutput o;
UNITY_SETUP_INSTANCE_ID(v);
TerrainInstancing(v.position, v.normal);
float3 positionWS = TransformObjectToWorld(v.position.xyz);
float3 normalWS = TransformObjectToWorldDir(v.normal);
float invNdotL = 1.0 - saturate(dot(_LightDirection, normalWS));
float scale = invNdotL * _ShadowBias.y;
// normal bias is negative since we want to apply an inset normal offset
positionWS = normalWS * scale.xxx + positionWS;
float4 clipPos = TransformWorldToHClip(positionWS);
// _ShadowBias.x sign depens on if platform has reversed z buffer
clipPos.z += _ShadowBias.x;
#if UNITY_REVERSED_Z
clipPos.z = min(clipPos.z, clipPos.w * UNITY_NEAR_CLIP_VALUE);
#else
clipPos.z = max(clipPos.z, clipPos.w * UNITY_NEAR_CLIP_VALUE);
#endif
return clipPos;
}
half4 ShadowPassFragment() : SV_TARGET
{
return 0;
}
// Depth pass
float4 DepthOnlyVertex(VertexInputLean v) : SV_POSITION
{
VertexOutput o = (VertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
TerrainInstancing(v.position, v.normal);
return TransformObjectToHClip(v.position.xyz);
}
half4 DepthOnlyFragment() : SV_TARGET
{
return 0;
}
#endif // LIGHTWEIGHT_PASS_LIT_TERRAIN_INCLUDED

28
com.unity.render-pipelines.lightweight/LWRP/Shaders/Terrain/LightweightStandardTerrain.shader


// used in fallback on old cards & base map
[HideInInspector] _MainTex("BaseMap (RGB)", 2D) = "grey" {}
[HideInInspector] _Color("Main Color", Color) = (1,1,1,1)
// TODO: Implement ShaderGUI for the shader and display the checkbox only when instancing is enabled.
[Toggle(_TERRAIN_INSTANCED_PERPIXEL_NORMAL)] _TERRAIN_INSTANCED_PERPIXEL_NORMAL("Enable Instanced Per-pixel Normal", Float) = 0
}
SubShader

#pragma target 3.0
#pragma vertex SplatmapVert
#pragma fragment SpatmapFragment
#pragma fragment SplatmapFragment
#define _METALLICSPECGLOSSMAP 1
#define _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A 1

#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile_fog
#pragma multi_compile_instancing
#pragma instancing_options assumeuniformscaling nomatrices nolightprobe nolightmap
#pragma multi_compile __ _TERRAIN_NORMAL_MAP
#pragma shader_feature _NORMALMAP
// Sample normal in pixel shader when doing instancing
#pragma shader_feature _TERRAIN_INSTANCED_PERPIXEL_NORMAL
#include "LWRP/ShaderLibrary/Terrain/InputSurfaceTerrain.hlsl"
#include "LWRP/ShaderLibrary/Terrain/LightweightPassLitTerrain.hlsl"

#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "LWRP/ShaderLibrary/InputSurfacePBR.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassShadow.hlsl"
#pragma multi_compile_instancing
#pragma instancing_options assumeuniformscaling nomatrices nolightprobe nolightmap
#include "LWRP/ShaderLibrary/Terrain/InputSurfaceTerrain.hlsl"
#include "LWRP/ShaderLibrary/Terrain/LightweightPassLitTerrain.hlsl"
ENDHLSL
}

#pragma vertex DepthOnlyVertex
#pragma fragment DepthOnlyFragment
#include "LWRP/ShaderLibrary/InputSurfacePBR.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassDepthOnly.hlsl"
#pragma multi_compile_instancing
#pragma instancing_options assumeuniformscaling nomatrices nolightprobe nolightmap
#include "LWRP/ShaderLibrary/Terrain/InputSurfaceTerrain.hlsl"
#include "LWRP/ShaderLibrary/Terrain/LightweightPassLitTerrain.hlsl"
UsePass "Hidden/Nature/Terrain/Utilities/PICKING"
UsePass "Hidden/Nature/Terrain/Utilities/SELECTION"
}
Dependency "AddPassShader" = "Hidden/LightweightPipeline/Terrain/Standard Terrain Add Pass"
Dependency "BaseMapShader" = "Hidden/LightweightPipeline/Terrain/Standard Terrain Base"

6
com.unity.render-pipelines.lightweight/LWRP/Shaders/Terrain/LightweightStandardTerrainAddPass.shader


#pragma target 3.0
#pragma vertex SplatmapVert
#pragma fragment SpatmapFragment
#pragma fragment SplatmapFragment
// -------------------------------------
// Lightweight Pipeline keywords

#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile_fog
#pragma multi_compile_instancing
#pragma instancing_options assumeuniformscaling nomatrices nolightprobe nolightmap
#pragma multi_compile __ _TERRAIN_NORMAL_MAP
#pragma shader_feature _NORMALMAP
#define TERRAIN_SPLAT_ADDPASS 1
#include "LWRP/ShaderLibrary/Terrain/InputSurfaceTerrain.hlsl"

37
com.unity.render-pipelines.lightweight/LWRP/Shaders/Terrain/LightweightStandardTerrainBase.shader


#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile_fog
#pragma multi_compile_instancing
#pragma instancing_options assumeuniformscaling nomatrices nolightprobe nolightmap
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
#pragma vertex SplatmapVert
#pragma fragment SplatmapFragment
#pragma vertex LitPassVertex
#pragma fragment LitPassFragment
#pragma shader_feature _NORMALMAP
// Sample normal in pixel shader when doing instancing
#pragma shader_feature _TERRAIN_INSTANCED_PERPIXEL_NORMAL
#define TERRAIN_SPLAT_BASEPASS 1
#include "LWRP/ShaderLibrary/Terrain/InputSurfaceTerrainBase.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassLit.hlsl"
#include "LWRP/ShaderLibrary/Terrain/InputSurfaceTerrain.hlsl"
#include "LWRP/ShaderLibrary/Terrain/LightweightPassLitTerrain.hlsl"
ENDHLSL
}

#pragma exclude_renderers d3d11_9x
#pragma target 2.0
//--------------------------------------
// GPU Instancing
#define _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A 1
#pragma instancing_options assumeuniformscaling nomatrices nolightprobe nolightmap
#include "LWRP/ShaderLibrary/Terrain/InputSurfaceTerrainBase.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassShadow.hlsl"
#include "LWRP/ShaderLibrary/Terrain/InputSurfaceTerrain.hlsl"
#include "LWRP/ShaderLibrary/Terrain/LightweightPassLitTerrain.hlsl"
ENDHLSL
}

#pragma vertex DepthOnlyVertex
#pragma fragment DepthOnlyFragment
#define _METALLICSPECGLOSSMAP 1
#define _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A 1
//--------------------------------------
// GPU Instancing
#pragma instancing_options assumeuniformscaling nomatrices nolightprobe nolightmap
#include "LWRP/ShaderLibrary/Terrain/InputSurfaceTerrainBase.hlsl"
#include "LWRP/ShaderLibrary/LightweightPassDepthOnly.hlsl"
#include "LWRP/ShaderLibrary/Terrain/InputSurfaceTerrain.hlsl"
#include "LWRP/ShaderLibrary/Terrain/LightweightPassLitTerrain.hlsl"
ENDHLSL
}

ENDHLSL
}
UsePass "Hidden/Nature/Terrain/Utilities/PICKING"
UsePass "Hidden/Nature/Terrain/Utilities/SELECTION"
}
FallBack "Hidden/InternalErrorShader"
CustomEditor "LightweightStandardGUI"

157
com.unity.shadergraph/CHANGELOG.md


## [3.4.0]
# Changelog
All notable changes to this package are documented in this file.
## [3.3.0]
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).
## [3.2.0]
## [3.4.0-preview]
### Added
- Shader Graph now supports the High Definition Render Pipeline with both PBR and Unlit Master nodes. Shaders built with Shader Graph work with both the Lightweight and HD render pipelines.
- You can now modify vertex position via the Position slot on the PBR and Unlit Master nodes. By default, the input to this node is object space position. Custom inputs to this slot should specify the absolute local position of a given vertex. Certain nodes (such as Procedural Shapes) are not viable in the vertex shader. Such nodes are incompatible with this slot.
- You can now edit the Reference name for a property. To do so, select the property and type a new name next to Reference. If you want to reset to the default name, right-click Reference, and select Reset reference.
- In the expanded property window, you can now toggle whether the property is exposed.
- You can now change the path of Shader Graphs and Sub Graphs. When you change the path of a Shader Graph, this modifies the location it has in the shader selection list. When you change the path of Sub Graph, it will have a different location in the node creation menu.
- Added `Is Front Face` node. With this node, you can change graph output depending on the face sign of a given fragment. If the current fragment is part of a front face, the node returns true. For a back face, the node returns false. Note: This functionality requires that you have enabled **two sided** on the Master node.
- Gradient functionality is now available via two new nodes: Sample Gradient and Gradient Asset. The Sample Gradient node samples a gradient given a Time parameter. You can define this gradient on the Gradient slot control view. The Gradient Asset node defines a gradient that can be sampled by multiple Sample Gradient nodes using different Time parameters.
- Math nodes now have a Waves category. The category has four different nodes: Triangle wave, Sawtooth wave, Square wave, and Noise Sine wave. The Triangle, Sawtooth, and Square wave nodes output a waveform with a range of -1 to 1 over a period of 1. The Noise Sine wave outputs a standard Sine wave with a range of -1 to 1 over a period of 2 * pi. For variance, random noise is added to the amplitude of the Sine wave, within a determined range.
- Added `Sphere Mask` node for which you can indicate the starting coordinate and center point. The sphere mask uses these with the **Radius** and **Hardness** parameters. Sphere mask functionality works in both 2D and 3D spaces, and is based on the vector coordinates in the **Coords and Center** input.
- Added support for Texture 3D and Texture 2D Array via two new property types and four new nodes.
- A new node `Texture 2D LOD` has been added for LOD functionality on a Texture 2D Sample. Sample Texture 2D LOD uses the exact same input and output slots as Sample Texture 2D, but also includes an input for level of detail adjustments via a Vector1 slot.
- Added `Texel Size` node, which allows you to get the special texture properties of a Texture 2D Asset via the `{texturename}_TexelSize` variable. Based on input from the Texture 2D Asset, the node outputs the width and height of the texel size in Vector1 format.
- Added `Rotate About Axis` node. This allows you to rotate a 3D vector space around an axis. For the rotation, you can specify an amount of degrees or a radian value.
## [3.1.0]
### Changed
- The settings for master nodes now live in a small window that you can toggle on and off. Here, you can change various rendering settings for your shader.
- There are two Normal Derive Nodes: `Normal From Height` and `Normal Reconstruct Z`.
`Normal From Height` uses Vector1 input to derive a normal map.
`Normal Reconstruct Z` uses the X and Y components in Vector2 input to derive the proper Z value for a normal map.
- The Texture type default input now accepts render textures.
- HD PBR subshader no longer duplicates surface description code into vertex shader.
- If the current render pipeline is not compatible, master nodes now display an error badge.
- The preview shader now only considers the current render pipeline. Because of this there is less code to compile, so the preview shader compiles faster.
- When you rename a shader graph or sub shader graph locally on your disk, the title of the Shader Graph window, black board, and preview also updates.
- Removed legacy matrices from Transfomation Matrix node.
- Texture 2D Array and Texture 3D nodes can no longer be used in the vertex shader.
- `Normal Create` node has been renamed to `Normal From Texture`.
- When you close the Shader Graph after you have modified a file, the prompt about saving your changes now shows the file name as well.
- `Blend` node now supports Overwrite mode.
- `Simple Noise` node no longer has a loop.
- The `Polygon` node now calculates radius based on apothem.
- `Normal Strength` node now calculates Z value more accurately.
### HD Render Pipeline support
![](.data/hd_render_pipeline.png)
Shader Graph now supports the High Definition Render Pipeline with both PBR and Unlit Master nodes. Shaders built with Shader Graph work with both the Lightweight and HD render pipelines.
### Vertex position
![](.data/vertex_position.png)
You can now modify vertex position via the Position slot on the PBR and Unlit Master nodes. By default, the input to this node is object space position. Custom inputs to this slot should specify the absolute local position of a given vertex. Certain nodes (such as Procedural Shapes) are not viable in the vertex shader. Such nodes are incompatible with this slot.
### Master node settings
![](.data/menu_settings.png)
The settings for master nodes now live in a small window that you can toggle on and off. Here, you can change various rendering settings for your shader.
### Property reference names and exposed state
![](.data/editable_property_references.gif)
You can now edit the Reference name for a property. To do so, select the property and type a new name next to Reference. If you want to reset to the default name, right-click Reference, and select Reset reference.
In the expanded property window, you can now also toggle if the property is exposed.
### Editable paths for graphs
![](.data/change_path.gif)
![](.data/use_path.gif)
You can now change the path of Shader Graphs and Sub Graphs. When you change the path of a Shader Graph, this modifies the location it has in the shader selection list. When you change the path of Sub Graph, it will have a different location in the node creation menu.
### Is Front Face node
![](.data/face_sign.png)
With this node, you can change graph output depending on the face sign of a given fragment. If the current fragment is part of a front face, the node returns True. For a back face, the node returns False.
Note: This functionality requires that you have enabled **two sided** on the Master node.
### Gradient nodes
![](.data/gradient_node.png)
This adds gradient functionality via two new nodes. The Sample Gradient node samples a gradient given a Time parameter. You can define this gradient on the Gradient slot control view. The Gradient Asset node defines a gradient that can be sampled by multiple Sample Gradient nodes using different Time parameters.
### Waveform nodes
![](.data/wave_form_nodes.png)
Math nodes now have a Waves category. The category has four different nodes: Triangle wave, Sawtooth wave, Square wave, and Noise Sine wave.
The Triangle, Sawtooth, and Square wave nodes output a waveform with a range of -1 to 1 over a period of 1.
The Noise Sine wave outputs a standard Sine wave with a range of -1 to 1 over a period of 2 * pi. For variance, random noise is added to the amplitude of the Sine wave, within a determined range.
## Normal Derive Nodes
![](.data/normal_derive_nodes.png)
There are two Normal Derive Nodes: `Normal From Height` and `Normal Reconstruct Z`.
`Normal From Height` uses Vector1 input to derive a normal map. `Normal Reconstruct Z` uses the X and Y components in Vector2 input to derive the proper Z value for a normal map.
### Sphere Mask Node
![](.data/sphereMask.png)
With this node, you can create a sphere mask. Indicate the starting coordinate and center point. The sphere mask uses these with the **Radius** and **Hardness** parameters. Sphere mask functionality works in both 2D and 3D spaces, and is based on the vector coordinates in the **Coords and Center** input.
### Texture3D and Texture2D Array
![](.data/texture_nodes.png)
This change expands Unity's support for Texture types via two new property types and four new nodes. These allow you to define and sample Texture 3D and Texture 2D Array type assets in Shader Graph.
### Texture 2D LOD node
![](.data/texture_2d_lod_node.png)
This adds a new node for LOD functionality on a Texture 2D Sample. Sample Texture 2D LOD uses the exact same input and output slots as Sample Texture 2D, but also includes an input for level of detail adjustments via a Vector1 slot.
### Texel Size Node
![](.data/texel_size_node.png)
With this node, you can get the special texture properties of a Texture 2D Asset via the `{texturename}_TexelSize` variable. Based on input from the Texture 2D Asset, the node outputs the width and height of the texel size in Vector1 format.
**Note:** Do not use the default input to reference your texture Asset. It makes your graph perform worse. Connect this node to a separate Texture 2D Asset node per image example.
### Show generated code
![](.data/show_generated_code.gif)
You can now see the generated code for any specific node. To do so, right-click the node, and select Show Generated Code. The code snippet will now open in the code editor that you have linked to Unity.
### Rotate About Axis node
![](.data/rotate_about_axis_node.png)
With the Rotate About Axis node, you can rotate a 3D vector space around an axis. For the rotation, you can specify an amount of degrees or a radian value.
### Bug fixes and minor changes
### Fixed
- Vector 1 nodes now evaluate correctly. ([#334](https://github.com/Unity-Technologies/ShaderGraph/issues/334) and [#337](https://github.com/Unity-Technologies/ShaderGraph/issues/337))
- Properties can now be copied and pasted.
- Pasting a property node into another graph will now convert it to a concrete node. ([#300](https://github.com/Unity-Technologies/ShaderGraph/issues/300) and [#307](https://github.com/Unity-Technologies/ShaderGraph/pull/307))

- Sub graphs are now suffixed with (sub), so you can tell them apart from other nodes.
- Boolean and Texture type properties now function correctly in sub-graphs.
- The preview of a node does not obstruct the selection outliner anymore.
- The Texture type default input now accepts render textures.
- HD PBR subshader no longer duplicates surface description code into vertex shader.
- If the current render pipeline is not compatible, master nodes now display an error badge.
- The preview shader now only considers the current render pipeline. Because of this there is less code to compile, and therefore the preview shader will compile faster.
- When you rename a shader graph or sub shader graph locally on your disk, the title of the Shader Graph window, black board, and preview also updates.
- Removed legacy matrices from Transfomation Matrix node.
- Texture 2D Array and Texture 3D nodes can no longer be used in the vertex shader.
- When you close the Shader Graph after you have modified a file, the prompt about saving your changes now shows the file name as well.
- `Blend` node now supports Overwrite mode.
- `Simple Noise` node no longer has a loop.
- The `Polygon` node now calculates radius based on apothem.
- `Normal Strength` node now calculates Z value more accurately.
- The preview of nodes now updates correctly.
- Your system locale can no longer cause incorrect commands due to full stops being converted to commas.

8
com.unity.shadergraph/Editor/Data/Graphs/ColorShaderProperty.cs


result.Append("(\"");
result.Append(displayName);
result.Append("\", Color) = (");
result.Append(value.r);
result.Append(NodeUtils.FloatToShaderValue(value.r));
result.Append(value.g);
result.Append(NodeUtils.FloatToShaderValue(value.g));
result.Append(value.b);
result.Append(NodeUtils.FloatToShaderValue(value.b));
result.Append(value.a);
result.Append(NodeUtils.FloatToShaderValue(value.a));
result.Append(")");
return result.ToString();
}

9
com.unity.shadergraph/Editor/Data/Graphs/VectorShaderProperty.cs


using System;
using System.Text;
using UnityEditor.Graphing;
using UnityEngine;
namespace UnityEditor.ShaderGraph

result.Append("(\"");
result.Append(displayName);
result.Append("\", Vector) = (");
result.Append(value.x);
result.Append(NodeUtils.FloatToShaderValue(value.x));
result.Append(value.y);
result.Append(NodeUtils.FloatToShaderValue(value.y));
result.Append(value.z);
result.Append(NodeUtils.FloatToShaderValue(value.z));
result.Append(value.w);
result.Append(NodeUtils.FloatToShaderValue(value.w));
result.Append(")");
return result.ToString();
}

9
com.unity.shadergraph/Editor/Drawing/MaterialGraphEditWindow.cs


ColorSpace m_ColorSpace;
RenderPipelineAsset m_RenderPipelineAsset;
bool m_FrameAllAfterLayout;
GraphEditorView m_GraphEditorView;

m_GraphEditorView.saveRequested += UpdateAsset;
m_GraphEditorView.convertToSubgraphRequested += ToSubGraph;
m_GraphEditorView.showInProjectRequested += PingAsset;
m_GraphEditorView.RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
this.GetRootVisualContainer().Add(graphEditorView);
}
}

persistenceKey = selectedGuid,
assetName = asset.name.Split('/').Last()
};
m_FrameAllAfterLayout = true;
graphEditorView.RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
titleContent = new GUIContent(asset.name.Split('/').Last());

void OnGeometryChanged(GeometryChangedEvent evt)
{
graphEditorView.UnregisterCallback<GeometryChangedEvent>(OnGeometryChanged);
graphEditorView.graphView.FrameAll();
if (m_FrameAllAfterLayout)
graphEditorView.graphView.FrameAll();
m_FrameAllAfterLayout = false;
foreach (var node in m_GraphObject.graph.GetNodes<AbstractMaterialNode>())
node.Dirty(ModificationScope.Node);
}
}
}

999
com.unity.testing.srp.lightweight/Tests/ReferenceImages/Linear/OSXEditor/Metal/053_UnlitShader.png
文件差异内容过多而无法显示
查看文件

999
com.unity.testing.srp.lightweight/Tests/ReferenceImages/Linear/WindowsEditor/Direct3D11/053_UnlitShader.png
文件差异内容过多而无法显示
查看文件

4
com.unity.testing.srp.lightweight/Tests/Scenes/035_Shader_TerrainShaders.unity


m_HeightmapMaximumLOD: 0
m_CastShadows: 1
m_DrawHeightmap: 1
m_DrawInstanced: 0
m_DrawInstanced: 1
m_DrawTreesAndFoliage: 1
m_ReflectionProbeUsage: 1
m_MaterialType: 3

m_PreserveTreePrototypeLayers: 0
m_ScaleInLightmap: 0.0512
m_LightmapParameters: {fileID: 15203, guid: 0000000000000000f000000000000000, type: 0}
m_GroupingID: 0
m_AllowAutoConnect: 0
--- !u!4 &745712513
Transform:
m_ObjectHideFlags: 0

10
com.unity.testing.srp.lightweight/Tests/Scenes/035_Shader_TerrainShaders/New Terrain.asset
文件差异内容过多而无法显示
查看文件

8
com.unity.testing.srp.lightweight/Tests/Scenes/035_Shader_TerrainShaders/Terrain.mat


Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_EnableInstancingVariants: 0
m_EnableInstancingVariants: 1
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}

- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _TERRAIN_INSTANCED_PERPIXEL_NORMAL: 0
- _UVSec: 0
- _WorkflowMode: 1
- _ZWrite: 1

12
com.unity.testing.srp.lightweight/Tests/Scenes/045_CustomLWPipe/CustomLWPipe.cs


m_Initialized = true;
}
public void Setup(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults, ref RenderingData renderingData)
public void Setup(ScriptableRenderer renderer, ref RenderingData renderingData)
renderer.Clear();
renderer.SetupPerObjectLightIndices(ref cullResults, ref renderingData.lightData);
RenderTextureDescriptor baseDescriptor = ScriptableRenderer.CreateRTDesc(ref renderingData.cameraData);
renderer.SetupPerObjectLightIndices(ref renderingData.cullResults, ref renderingData.lightData);
RenderTextureDescriptor baseDescriptor = ScriptableRenderer.CreateRenderTextureDescriptor(ref renderingData.cameraData);
RenderTextureDescriptor shadowDescriptor = baseDescriptor;
shadowDescriptor.dimension = TextureDimension.Tex2D;

renderer.EnqueuePass(m_CreateLightweightRenderTexturesPass);
Camera camera = renderingData.cameraData.camera;
bool dynamicBatching = renderingData.supportsDynamicBatching;
m_RenderOpaqueForwardPass.Setup(baseDescriptor, colorHandle, depthHandle, ScriptableRenderer.GetCameraClearFlag(camera), camera.backgroundColor, rendererConfiguration, dynamicBatching);
m_RenderOpaqueForwardPass.Setup(baseDescriptor, colorHandle, depthHandle, ScriptableRenderer.GetCameraClearFlag(camera), camera.backgroundColor, rendererConfiguration);
renderer.EnqueuePass(m_RenderOpaqueForwardPass);
}
}

23
com.unity.testing.srp.lightweight/Tests/Scenes/052_LWCallbacks/CameraCallbackTests.cs


using UnityEngine;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.LightweightPipeline;
using UnityEngine.Rendering;

m_Target = target;
}
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
RenderTextureDescriptor opaqueDesc = ScriptableRenderer.CreateRTDesc(ref renderingData.cameraData);
RenderTextureDescriptor opaqueDesc = ScriptableRenderer.CreateRenderTextureDescriptor(ref renderingData.cameraData);
var cmd = CommandBufferPool.Get("Capture Pass");
cmd.GetTemporaryRT(m_Target.id, opaqueDesc);

{
CapturePass m_CopyResult = new CapturePass();
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context, ref CullResults cullResults,
ref RenderingData renderingData)
public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData)
m_CopyResult.Execute(renderer, ref context, ref cullResults, ref renderingData);
m_CopyResult.Execute(renderer, context, ref renderingData);
Material material = renderer.GetMaterial(MaterialHandles.Blit);

cmd.SetViewport(new Rect(0, renderingData.cameraData.camera.pixelRect.height / 2.0f, renderingData.cameraData.camera.pixelRect.width / 3.0f, renderingData.cameraData.camera.pixelRect.height / 2.0f));
cmd.SetGlobalTexture("_BlitTex", afterDepth.Identifier());
LightweightPipeline.DrawFullScreen(cmd, material);
ScriptableRenderer.RenderFullscreenQuad(cmd, material);
LightweightPipeline.DrawFullScreen(cmd, material);
ScriptableRenderer.RenderFullscreenQuad(cmd, material);
LightweightPipeline.DrawFullScreen(cmd, material);
ScriptableRenderer.RenderFullscreenQuad(cmd, material);
LightweightPipeline.DrawFullScreen(cmd, material);
ScriptableRenderer.RenderFullscreenQuad(cmd, material);
LightweightPipeline.DrawFullScreen(cmd, material);
ScriptableRenderer.RenderFullscreenQuad(cmd, material);
//TODO: Upsidown UV trash, ignore this for now

8
TestProjects/HDRP_Tests/Assets/GraphicTests/Scenes/1x_Materials/1601_TerrainLit.meta


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

539
TestProjects/HDRP_Tests/Assets/GraphicTests/Scenes/1x_Materials/1601_TerrainLit.unity


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!29 &1
OcclusionCullingSettings:
m_ObjectHideFlags: 0
serializedVersion: 2
m_OcclusionBakeSettings:
smallestOccluder: 5
smallestHole: 0.25
backfaceThreshold: 100
m_SceneGUID: 00000000000000000000000000000000
m_OcclusionCullingData: {fileID: 0}
--- !u!104 &2
RenderSettings:
m_ObjectHideFlags: 0
serializedVersion: 9
m_Fog: 0
m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1}
m_FogMode: 3
m_FogDensity: 0.01
m_LinearFogStart: 0
m_LinearFogEnd: 300
m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1}
m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1}
m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1}
m_AmbientIntensity: 0
m_AmbientMode: 0
m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1}
m_SkyboxMaterial: {fileID: 0}
m_HaloStrength: 0.5
m_FlareStrength: 1
m_FlareFadeSpeed: 3
m_HaloTexture: {fileID: 0}
m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0}
m_DefaultReflectionMode: 0
m_DefaultReflectionResolution: 128
m_ReflectionBounces: 1
m_ReflectionIntensity: 0
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 0}
m_UseRadianceAmbientProbe: 0
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0
serializedVersion: 11
m_GIWorkflowMode: 0
m_GISettings:
serializedVersion: 2
m_BounceScale: 1
m_IndirectOutputScale: 1
m_AlbedoBoost: 1
m_TemporalCoherenceThreshold: 1
m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 1
m_EnableRealtimeLightmaps: 1
m_LightmapEditorSettings:
serializedVersion: 10
m_Resolution: 2
m_BakeResolution: 40
m_AtlasSize: 1024
m_AO: 0
m_AOMaxDistance: 1
m_CompAOExponent: 1
m_CompAOExponentDirect: 0
m_Padding: 2
m_LightmapParameters: {fileID: 0}
m_LightmapsBakeMode: 1
m_TextureCompression: 1
m_FinalGather: 0
m_FinalGatherFiltering: 1
m_FinalGatherRayCount: 256
m_ReflectionCompression: 2
m_MixedBakeMode: 2
m_BakeBackend: 1
m_PVRSampling: 1
m_PVRDirectSampleCount: 32
m_PVRSampleCount: 500
m_PVRBounces: 2
m_PVRFilterTypeDirect: 0
m_PVRFilterTypeIndirect: 0
m_PVRFilterTypeAO: 0
m_PVRFilteringMode: 1
m_PVRCulling: 1
m_PVRFilteringGaussRadiusDirect: 1
m_PVRFilteringGaussRadiusIndirect: 5
m_PVRFilteringGaussRadiusAO: 2
m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_ShowResolutionOverlay: 1
m_LightingDataAsset: {fileID: 0}
m_UseShadowmask: 1
--- !u!196 &4
NavMeshSettings:
serializedVersion: 2
m_ObjectHideFlags: 0
m_BuildSettings:
serializedVersion: 2
agentTypeID: 0
agentRadius: 0.5
agentHeight: 2
agentSlope: 45
agentClimb: 0.4
ledgeDropHeight: 0
maxJumpAcrossDistance: 0
minRegionArea: 2
manualCellSize: 0
cellSize: 0.16666667
manualTileSize: 0
tileSize: 256
accuratePlacement: 0
debug:
m_Flags: 0
m_NavMeshData: {fileID: 0}
--- !u!1001 &476264687
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 4209882255362944, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: m_LocalPosition.x
value: -0.85279846
objectReference: {fileID: 0}
- target: {fileID: 4209882255362944, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: m_LocalPosition.y
value: 10.345987
objectReference: {fileID: 0}
- target: {fileID: 4209882255362944, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: m_LocalPosition.z
value: 72.13774
objectReference: {fileID: 0}
- target: {fileID: 4209882255362944, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: m_LocalRotation.x
value: -0.18097067
objectReference: {fileID: 0}
- target: {fileID: 4209882255362944, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: m_LocalRotation.y
value: -0.734918
objectReference: {fileID: 0}
- target: {fileID: 4209882255362944, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: m_LocalRotation.z
value: 0.21555983
objectReference: {fileID: 0}
- target: {fileID: 4209882255362944, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: m_LocalRotation.w
value: -0.61699206
objectReference: {fileID: 0}
- target: {fileID: 4209882255362944, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: m_RootOrder
value: 3
objectReference: {fileID: 0}
- target: {fileID: 4209882255362944, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4209882255362944, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4209882255362944, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 1132393308280272, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: m_Name
value: HDRP_Test_Camera
objectReference: {fileID: 0}
- target: {fileID: 20109210616973140, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
propertyPath: far clip plane
value: 500
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 3}
--- !u!1 &822358699
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 822358702}
- component: {fileID: 822358701}
- component: {fileID: 822358700}
m_Layer: 0
m_Name: Terrain
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!154 &822358700
TerrainCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 822358699}
m_Material: {fileID: 0}
m_Enabled: 1
m_TerrainData: {fileID: 15600000, guid: 245a04c8ad46a5349bcbaad4da1da133, type: 2}
m_EnableTreeColliders: 1
--- !u!218 &822358701
Terrain:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 822358699}
m_Enabled: 1
serializedVersion: 3
m_TerrainData: {fileID: 15600000, guid: 245a04c8ad46a5349bcbaad4da1da133, type: 2}
m_TreeDistance: 2000
m_TreeBillboardDistance: 50
m_TreeCrossFadeLength: 5
m_TreeMaximumFullLODCount: 50
m_DetailObjectDistance: 80
m_DetailObjectDensity: 1
m_HeightmapPixelError: 5
m_SplatMapDistance: 1000
m_HeightmapMaximumLOD: 0
m_CastShadows: 1
m_DrawHeightmap: 1
m_DrawInstanced: 1
m_DrawTreesAndFoliage: 1
m_ReflectionProbeUsage: 1
m_MaterialType: 3
m_LegacySpecular:
serializedVersion: 2
rgba: 4286545791
m_LegacyShininess: 0.078125
m_MaterialTemplate: {fileID: 2100000, guid: 22ff8771d87ef27429e670136399094b, type: 2}
m_BakeLightProbesForTrees: 1
m_PreserveTreePrototypeLayers: 0
m_ScaleInLightmap: 0.0512
m_LightmapParameters: {fileID: 15203, guid: 0000000000000000f000000000000000, type: 0}
m_AllowAutoConnect: 1
--- !u!4 &822358702
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 822358699}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1327369485
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1327369487}
- component: {fileID: 1327369486}
m_Layer: 0
m_Name: Decal Projector
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &1327369486
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1327369485}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: f19d9143a39eb3b46bc4563e9889cfbd, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 2100000, guid: 638b5db2a1568654e998f0152ad27948, type: 2}
m_DrawDistance: 1000
m_FadeScale: 0.9
m_UVScale: {x: 1, y: 1}
m_UVBias: {x: 0, y: 0}
m_AffectsTransparency: 0
m_Offset: {x: -6.749508, y: 3.085741, z: 7.9018707}
m_Size: {x: 16, y: 8.171482, z: 16}
--- !u!4 &1327369487
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1327369485}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 17.31, y: -1.35, z: 68.92}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 4
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1736369238
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1736369240}
- component: {fileID: 1736369239}
- component: {fileID: 1736369242}
- component: {fileID: 1736369241}
m_Layer: 0
m_Name: Directional Light
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!108 &1736369239
Light:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1736369238}
m_Enabled: 1
serializedVersion: 8
m_Type: 1
m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1}
m_Intensity: 3.1415927
m_Range: 10
m_SpotAngle: 30
m_CookieSize: 10
m_Shadows:
m_Type: 2
m_Resolution: -1
m_CustomResolution: -1
m_Strength: 1
m_Bias: 0.05
m_NormalBias: 0.4
m_NearPlane: 0.2
m_Cookie: {fileID: 0}
m_DrawHalo: 0
m_Flare: {fileID: 0}
m_RenderMode: 0
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_Lightmapping: 4
m_LightShadowCasterMode: 2
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_ColorTemperature: 6570
m_UseColorTemperature: 0
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!4 &1736369240
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1736369238}
m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261}
m_LocalPosition: {x: 0, y: 3, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0}
--- !u!114 &1736369241
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1736369238}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c6c2871f720b2af4e9210febdac74517, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Version: 1
shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
contactShadows: 0
viewBiasMin: 0.2
viewBiasMax: 100
viewBiasScale: 1
normalBiasMin: 0.5
normalBiasMax: 0.5
normalBiasScale: 1
sampleBiasScale: 0
edgeLeakFixup: 1
edgeToleranceNormal: 1
edgeTolerance: 1
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05
- 0.15
- 0.3
shadowCascadeBorders:
- 0
- 0
- 0
- 0.2
shadowAlgorithm: 0
shadowVariant: 3
shadowPrecision: 0
shadowData:
format: 0
data: 000000000000803f
shadowDatas:
- format: 0
data: 000000000000803f
--- !u!114 &1736369242
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1736369238}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 7a68c43fe1f2a47cfa234b5eeaa98012, type: 3}
m_Name:
m_EditorClassIdentifier:
version: 2
m_Version: 2
directionalIntensity: 3.1415927
punctualIntensity: 600
areaIntensity: 200
enableSpotReflector: 0
m_InnerSpotPercent: 0
lightDimmer: 1
volumetricDimmer: 1
lightUnit: 2
fadeDistance: 10000
affectDiffuse: 1
affectSpecular: 1
nonLightmappedOnly: 0
lightTypeExtent: 0
spotLightShape: 0
shapeWidth: 0.5
shapeHeight: 0.5
aspectRatio: 1
shapeRadius: 0
maxSmoothness: 1
applyRangeAttenuation: 1
useOldInspector: 0
featuresFoldout: 1
showAdditionalSettings: 0
displayLightIntensity: 3.1415927
displayAreaLightEmissiveMesh: 0
lightLayers: 1
--- !u!33 &8798469937330876322
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8798469937333842852}
m_Mesh: {fileID: 4300006, guid: ebcf3e09572f188498750733ca8d41aa, type: 3}
--- !u!23 &8798469937331842402
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8798469937333842852}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 61e846cd580c3d84eb34916c1e123ad2, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!4 &8798469937333743492
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8798469937333842852}
m_LocalRotation: {x: -0.7071068, y: -0, z: -0, w: 0.7071068}
m_LocalPosition: {x: 22.98, y: -0.16, z: 13.7}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &8798469937333842852
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 8798469937333743492}
- component: {fileID: 8798469937330876322}
- component: {fileID: 8798469937331842402}
m_Layer: 0
m_Name: Part02_Inside_02
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1

7
TestProjects/HDRP_Tests/Assets/GraphicTests/Scenes/1x_Materials/1601_TerrainLit.unity.meta


fileFormatVersion: 2
guid: d52dbea61cf2f884fadf33f8cc6afc0c
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

1001
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1601_TerrainLit.png
文件差异内容过多而无法显示
查看文件

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

正在加载...
取消
保存