浏览代码

Merge branch 'master'

/Yibing-Project-2
Evgenii Golubev 7 年前
当前提交
d1c74bcb
共有 851 个文件被更改,包括 5541 次插入7374 次删除
  1. 1
      .npmignore
  2. 999
      ImageTemplates/LightweightPipeline/Scenes/005_LitBakedEmission.unity.png
  3. 2
      ImageTemplates/LightweightPipeline/Scenes/005_LitBakedEmission.unity.png.meta
  4. 999
      ImageTemplates/LightweightPipeline/Scenes/006_LitShaderLightProbes.unity.png
  5. 2
      ImageTemplates/LightweightPipeline/Scenes/006_LitShaderLightProbes.unity.png.meta
  6. 999
      ImageTemplates/LightweightPipeline/Scenes/010_MultiplePointLights.unity.png
  7. 999
      ImageTemplates/LightweightPipeline/Scenes/018_Lighting_Scene_DirectionalBakedIndirect.unity.png
  8. 2
      ImageTemplates/LightweightPipeline/Scenes/018_Lighting_Scene_DirectionalBakedIndirect.unity.png.meta
  9. 999
      ImageTemplates/LightweightPipeline/Scenes/019_Lighting_Scene_PointLights.unity.png
  10. 2
      ImageTemplates/LightweightPipeline/Scenes/019_Lighting_Scene_PointLights.unity.png.meta
  11. 999
      ImageTemplates/LightweightPipeline/Scenes/026_Shader_PBRscene.unity.png
  12. 2
      ImageTemplates/LightweightPipeline/Scenes/026_Shader_PBRscene.unity.png.meta
  13. 999
      ImageTemplates/LightweightPipeline/Scenes/027_PostProcessing.unity.png
  14. 2
      ImageTemplates/LightweightPipeline/Scenes/027_PostProcessing.unity.png.meta
  15. 27
      SampleScenes/FPTL/FPTL.unity
  16. 20
      SampleScenes/FPTL/Materials/FwdMat.mat
  17. 7
      ScriptableRenderPipeline/Core/CoreUtils.cs
  18. 5
      ScriptableRenderPipeline/Core/Debugging/Editor/DebugMenuEditor.cs
  19. 35
      ScriptableRenderPipeline/Core/ProfilingSample.cs
  20. 4
      ScriptableRenderPipeline/Core/ShaderGenerator/Editor/ShaderGeneratorMenu.cs
  21. 2
      ScriptableRenderPipeline/Core/ShaderLibrary/Common.hlsl
  22. 2
      ScriptableRenderPipeline/Core/Shadow/Resources/DebugDisplayShadowMap.shader
  23. 15
      ScriptableRenderPipeline/Core/Shadow/Shadow.cs
  24. 14
      ScriptableRenderPipeline/HDRenderPipeline/Camera/HDCamera.cs
  25. 2
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayLatlong.shader
  26. 2
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugFullScreen.shader
  27. 2
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugViewMaterialGBuffer.shader
  28. 2
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugViewTiles.shader
  29. 5
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDAssetFactory.cs
  30. 28
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs
  31. 7
      ScriptableRenderPipeline/HDRenderPipeline/Editor/UpgradeStandardShaderMaterials.cs
  32. 224
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
  33. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDUtils.cs
  34. 15
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Deferred.shader
  35. 328
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs
  36. 117
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Volumetrics/VolumetricLighting.cs
  37. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader
  38. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader
  39. 16
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl
  40. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader
  41. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader
  42. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CombineLighting.shader
  43. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CopyStencilBuffer.shader
  44. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/PreIntegratedFGD.shader
  45. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/SubsurfaceScattering.shader
  46. 12
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs
  47. 3
      ScriptableRenderPipeline/HDRenderPipeline/Material/RenderPipelineMaterial.cs
  48. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.shader
  49. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawSssProfile.shader
  50. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader
  51. 13
      ScriptableRenderPipeline/HDRenderPipeline/ShaderVariables.hlsl
  52. 11
      ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesFunctions.hlsl
  53. 8
      ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesMatrixDefsHDCamera.hlsl
  54. 8
      ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesMatrixDefsLegacyUnity.hlsl
  55. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/BlacksmithlSky/Resources/SkyBlacksmith.shader
  56. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/ComputeGgxIblSampleData.compute
  57. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/GGXConvolve.shader
  58. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Resources/SkyHDRI.shader
  59. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/OpaqueAtmosphericScattering.shader
  60. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/Resources/ProceduralSky.shader
  61. 6
      ScriptableRenderPipeline/HDRenderPipeline/Sky/SkyManager.cs
  62. 6
      ScriptableRenderPipeline/LightweightPipeline/Editor/LegacyShadersToLightweightPipelineUpgrader.cs
  63. 20
      ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightPipelineUpgraders.cs
  64. 8
      ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardGUI.cs
  65. 6
      ScriptableRenderPipeline/LightweightPipeline/Editor/StandardToLightweightMaterialUpgrader.cs
  66. 45
      ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightAssetEditor.cs
  67. 11
      ScriptableRenderPipeline/LightweightPipeline/LightweightConstantBuffer.cs
  68. 456
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipeline.cs
  69. 12
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset
  70. 67
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.cs
  71. 96
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineUtils.cs
  72. 24
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultParticle.mat
  73. 4
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-Default.mat
  74. 212
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightCore.cginc
  75. 375
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightLighting.cginc
  76. 303
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPassLit.cginc
  77. 1
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightShadows.cginc
  78. 13
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightStandard.shader
  79. 48
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightStandardSimpleLighting.shader
  80. 4
      TestbedPipelines/BasicRenderPipeline/BasicRenderPipeline.cs
  81. 2
      TestbedPipelines/Fptl/FPTLRenderPipeline.asset
  82. 41
      TestbedPipelines/Fptl/FptlLighting.cs
  83. 8
      TestbedPipelines/Fptl/RegularForwardLightingUtils.hlsl
  84. 66
      TestbedPipelines/OnTileDeferredPipeline/OnTileDeferredRenderPipeline.cs
  85. 5
      Tests/GraphicsTests/Framework/Editor/TestFrameworkCustomBuild.cs
  86. 4
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Scripts/Editor/GraphicTestTools.cs
  87. 5
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Shaders/DistordFromTex.shader
  88. 1001
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/Distortion/Distord_TexRemap.exr
  89. 4
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/Distortion/Distord_TexRemap.mat
  90. 882
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion.unity
  91. 4
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion/Lit_Distortion.mat
  92. 12
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/001_SimpleCube.unity
  93. 7
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/002_Camera_Clip.unity
  94. 10
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/003_Camera_Ortho.unity
  95. 13
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/004_Camera_TargetTexture.unity
  96. 143
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/005_LitBakedEmission.unity
  97. 4
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/005_LitBakedEmission/005_LitBakeEmission_Sphere.mat
  98. 8
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/005_LitBakedEmission/LightingData.asset
  99. 2
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/005_LitBakedEmission/LightingData.asset.meta
  100. 1001
      Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/005_LitBakedEmission/Lightmap-0_comp_light.exr

1
.npmignore


/SampleScenes*
/TestbedPipelines*
/Tests*
/ScriptableRenderPipeline/HDRenderPipeline*
/.collabignore
/.gitignore
/.gitmodules

999
ImageTemplates/LightweightPipeline/Scenes/005_LitBakedEmission.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/LightweightPipeline/Scenes/005_LitBakedEmission.unity.png.meta


fileFormatVersion: 2
guid: f8a5ea9c8121c5b45826dc4c99918223
timeCreated: 1504173061
timeCreated: 1509370030
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}

999
ImageTemplates/LightweightPipeline/Scenes/006_LitShaderLightProbes.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/LightweightPipeline/Scenes/006_LitShaderLightProbes.unity.png.meta


fileFormatVersion: 2
guid: f803aab2456d7844fbd67d66f4c1afe8
timeCreated: 1504173061
timeCreated: 1509370329
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}

999
ImageTemplates/LightweightPipeline/Scenes/010_MultiplePointLights.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/LightweightPipeline/Scenes/018_Lighting_Scene_DirectionalBakedIndirect.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/LightweightPipeline/Scenes/018_Lighting_Scene_DirectionalBakedIndirect.unity.png.meta


fileFormatVersion: 2
guid: 89ed8247fbdb545f58bf8e0c6cf53d00
timeCreated: 1504695587
timeCreated: 1509372551
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}

999
ImageTemplates/LightweightPipeline/Scenes/019_Lighting_Scene_PointLights.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/LightweightPipeline/Scenes/019_Lighting_Scene_PointLights.unity.png.meta


fileFormatVersion: 2
guid: 17ad6947534f84588abd730750168c53
timeCreated: 1504695587
timeCreated: 1509374529
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}

999
ImageTemplates/LightweightPipeline/Scenes/026_Shader_PBRscene.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/LightweightPipeline/Scenes/026_Shader_PBRscene.unity.png.meta


fileFormatVersion: 2
guid: bf08da8c044d748a6b54f9ad754b2773
timeCreated: 1505223637
timeCreated: 1509377198
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}

999
ImageTemplates/LightweightPipeline/Scenes/027_PostProcessing.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/LightweightPipeline/Scenes/027_PostProcessing.unity.png.meta


fileFormatVersion: 2
guid: c40bd57fb760b4839a1ef80428356062
timeCreated: 1507026380
timeCreated: 1509377483
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}

27
SampleScenes/FPTL/FPTL.unity


m_EnableBakedLightmaps: 0
m_EnableRealtimeLightmaps: 0
m_LightmapEditorSettings:
serializedVersion: 9
serializedVersion: 10
m_TextureWidth: 1024
m_TextureHeight: 1024
m_AtlasSize: 1024
m_AO: 0
m_AOMaxDistance: 1
m_CompAOExponent: 0

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1713034008}
m_Enabled: 1
m_ExtensionPropertyValues: []
--- !u!124 &1713034010
Behaviour:
m_ObjectHideFlags: 0

m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
m_StereoMirrorMode: 0
--- !u!4 &1713034013
Transform:
m_ObjectHideFlags: 0

m_Script: {fileID: 11500000, guid: 92bb16b4ee20841929b24d6bd771738d, type: 3}
m_Name:
m_EditorClassIdentifier:
m_RenderLoop: {fileID: 11400000, guid: 4dc14083116279a438e1b2de3830999f, type: 2}
--- !u!114 &1713034015
MonoBehaviour:
m_ObjectHideFlags: 0

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
- {fileID: 2100000, guid: cb6536d04ba24874981eb01dfd87479e, type: 2}
- {fileID: 2100000, guid: 24e6a15bf9d2c0944b380d860a738528, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
- {fileID: 2100000, guid: cb6536d04ba24874981eb01dfd87479e, type: 2}
- {fileID: 2100000, guid: 24e6a15bf9d2c0944b380d860a738528, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
- {fileID: 2100000, guid: cb6536d04ba24874981eb01dfd87479e, type: 2}
- {fileID: 2100000, guid: 24e6a15bf9d2c0944b380d860a738528, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

20
SampleScenes/FPTL/Materials/FwdMat.mat


m_PrefabInternal: {fileID: 0}
m_Name: FwdMat
m_Shader: {fileID: 4800000, guid: 8f28d6dbfdba66d4dbae80224aca5669, type: 3}
m_ShaderKeywords: _EMISSION
m_ShaderKeywords: _ALPHAPREMULTIPLY_ON _EMISSION
m_CustomRenderQueue: -1
stringTagMap: {}
m_DoubleSidedGI: 0
m_CustomRenderQueue: 3000
stringTagMap:
RenderType: Transparent
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3

- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _DstBlend: 10
- _Glossiness: 0.5
- _Glossiness: 0.806
- _Metallic: 0
- _Mode: 0
- _Metallic: 0.891
- _Mode: 3
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0

- _ZWrite: 1
- _ZWrite: 0
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _Color: {r: 1, g: 1, b: 1, a: 0.559}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1}

7
ScriptableRenderPipeline/Core/CoreUtils.cs


using System;
using System;
using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;

{
// Note: Color.Black have alpha channel set to 1. Most of the time we want alpha channel set to 0 as we use black to clear render target
public static Color clearColorAllBlack { get { return new Color(0f, 0f, 0f, 0f); } }
public const int editMenuPriority1 = 320;
public const int editMenuPriority2 = 331;
public const int assetCreateMenuPriority1 = 230;
public const int assetCreateMenuPriority2 = 241;
// Render Target Management.
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier buffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)

5
ScriptableRenderPipeline/Core/Debugging/Editor/DebugMenuEditor.cs


using UnityEngine;
using UnityEditor;
namespace UnityEngine.Experimental.Rendering

[SerializeField]
private DebugMenuState m_DebugMenuState;
[MenuItem("HDRenderPipeline/Debug Window")]
[MenuItem("Edit/Render Pipeline/Tools/High Definition/Debug Window", priority = CoreUtils.editMenuPriority2)]
static void DisplayDebugMenu()
{
var window = EditorWindow.GetWindow<DebugMenuEditor>("Debug Window");

}
}
}
}

35
ScriptableRenderPipeline/Core/ProfilingSample.cs


using System;
using UnityEngine.Rendering;
using UnityEngine.Profiling;
public readonly CommandBuffer cmd;
public readonly string name;
readonly CommandBuffer m_Cmd;
readonly string m_Name;
CustomSampler m_Sampler;
public ProfilingSample(CommandBuffer cmd, string name)
public ProfilingSample(CommandBuffer cmd, string name,CustomSampler sampler = null)
this.cmd = cmd;
this.name = name;
m_Cmd = cmd;
m_Name = name;
m_Sampler = sampler;
if (m_Sampler != null)
m_Sampler.Begin();
public ProfilingSample(CommandBuffer cmd, string format, object arg)
public ProfilingSample(CommandBuffer cmd, string format, object arg) : this(cmd,string.Format(format, arg))
this.cmd = cmd;
name = string.Format(format, arg);
m_Disposed = false;
cmd.BeginSample(name);
public ProfilingSample(CommandBuffer cmd, string format, params object[] args)
public ProfilingSample(CommandBuffer cmd, string format, params object[] args) : this(cmd,string.Format(format, args))
this.cmd = cmd;
name = string.Format(format, args);
m_Disposed = false;
cmd.BeginSample(name);
}
public void Dispose()

// As this is a struct, it could have been initialized using an empty constructor so we
// need to make sure `cmd` isn't null to avoid a crash. Switching to a class would fix
// this but will generate garbage on every frame (and this struct is used quite a lot).
if (disposing && cmd != null)
cmd.EndSample(name);
if (disposing && m_Cmd != null)
{
m_Cmd.EndSample(m_Name);
if (m_Sampler != null)
m_Sampler.End();
}
m_Disposed = true;
}

4
ScriptableRenderPipeline/Core/ShaderGenerator/Editor/ShaderGeneratorMenu.cs


using UnityEngine.Experimental.Rendering;
[UnityEditor.MenuItem("RenderPipeline/Generate Shader Includes")]
[UnityEditor.MenuItem("Edit/Render Pipeline/Tools/Generate Shader Includes", priority = CoreUtils.editMenuPriority1)]
static void GenerateShaderIncludes()
{
CSharpToHLSL.GenerateAll();

2
ScriptableRenderPipeline/Core/ShaderLibrary/Common.hlsl


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

2
ScriptableRenderPipeline/Core/Shadow/Resources/DebugDisplayShadowMap.shader


{
HLSLINCLUDE
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: unitl we go futher in dev
#include "../../../Core/ShaderLibrary/Common.hlsl"

15
ScriptableRenderPipeline/Core/Shadow/Shadow.cs


namespace UnityEngine.Experimental.Rendering
{
using ShadowRequestVector = VectorArray<ShadowmapBase.ShadowRequest>;
using ShadowDataVector = VectorArray<ShadowData>;
using ShadowDataVector = VectorArray<ShadowData>;
using ShadowAlgoVector = VectorArray<GPUShadowAlgorithm>;
using ShadowAlgoVector = VectorArray<GPUShadowAlgorithm>;
using Profiling;
// Standard shadow map atlas implementation using one large shadow map
public class ShadowAtlas : ShadowmapBase, IDisposable

protected float[] m_TmpBorders = new float[((k_MaxCascadesInShader+3)/4)*4];
protected ShadowAlgoVector m_SupportedAlgorithms = new ShadowAlgoVector( 0, false );
protected Material m_DebugMaterial = null;
private CustomSampler m_SamplerShadowMaps = CustomSampler.Create("ShadowMaps");
protected struct Key
{

{
if (m_ActiveEntriesCount == 0)
return;
var profilingSample = new ProfilingSample(cmd, "Shadowmap{0}", m_TexSlot);
string sLabel = string.Format("Shadowmap{0}", m_TexSlot);
var profilingSample = new ProfilingSample(cmd, sLabel, m_SamplerShadowMaps);
string cbName = "";
if (!string.IsNullOrEmpty( m_ShaderKeyword ) )

private ShadowRequestVector m_TmpRequests = new ShadowRequestVector( 0, false );
// The following vector holds data that are returned to the caller so it can be sent to GPU memory in some form. Contents are stable in between calls to ProcessShadowRequests.
private ShadowIndicesVector m_ShadowIndices = new ShadowIndicesVector( 0, false );
private CustomSampler m_SamplerRenderShadows = CustomSampler.Create("RenderShadows");
public override uint GetShadowMapCount()
{

public override void RenderShadows( FrameId frameId, ScriptableRenderContext renderContext, CommandBuffer cmd, CullResults cullResults, List<VisibleLight> lights)
{
using (new ProfilingSample(cmd, "Render Shadows"))
using (new ProfilingSample(cmd, "Render Shadows", m_SamplerRenderShadows))
{
foreach( var sm in m_Shadowmaps )
{

14
ScriptableRenderPipeline/HDRenderPipeline/Camera/HDCamera.cs


material.SetVectorArray(HDShaderIDs._FrustumPlanes, frustumPlaneEquations);
}
// TODO: We should set all the value below globally and not let it under the control of Unity,
// Need to test that because we are not sure in which order these value are setup, but we need to have control on them, or rename them in our shader.
// For now, apply it for all our compute shader to make it work
cmd.SetComputeMatrixParam(cs, HDShaderIDs._ViewMatrix, viewMatrix);
cmd.SetComputeMatrixParam(cs, HDShaderIDs._InvViewMatrix, viewMatrix.inverse);
cmd.SetComputeMatrixParam(cs, HDShaderIDs._ProjMatrix, projMatrix);
cmd.SetComputeMatrixParam(cs, HDShaderIDs._InvProjMatrix, projMatrix.inverse);
cmd.SetComputeMatrixParam(cs, HDShaderIDs._NonJitteredViewProjMatrix, nonJitteredViewProjMatrix);
cmd.SetComputeMatrixParam(cs, HDShaderIDs._ViewProjMatrix, viewProjMatrix);
cmd.SetComputeMatrixParam(cs, HDShaderIDs._InvViewProjMatrix, viewProjMatrix.inverse);
cmd.SetComputeVectorParam(cs, HDShaderIDs._InvProjParam, invProjParam);
cmd.SetComputeVectorParam(cs, HDShaderIDs._ScreenSize, screenSize);
cmd.SetComputeMatrixParam(cs, HDShaderIDs._PrevViewProjMatrix, prevViewProjMatrix);
cmd.SetComputeVectorArrayParam(cs, HDShaderIDs._FrustumPlanes, frustumPlaneEquations);
// Copy values set by Unity which are not configured in scripts.
cmd.SetComputeVectorParam(cs, HDShaderIDs.unity_OrthoParams, Shader.GetGlobalVector(HDShaderIDs.unity_OrthoParams));
cmd.SetComputeVectorParam(cs, HDShaderIDs._ProjectionParams, Shader.GetGlobalVector(HDShaderIDs._ProjectionParams));

2
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayLatlong.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: unitl we go futher in dev
#pragma vertex Vert
#pragma fragment Frag

2
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugFullScreen.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: unitl we go futher in dev
#pragma vertex Vert
#pragma fragment Frag

2
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugViewMaterialGBuffer.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma vertex Vert
#pragma fragment Frag

2
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugViewTiles.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma vertex Vert
#pragma fragment Frag

5
ScriptableRenderPipeline/HDRenderPipeline/Editor/HDAssetFactory.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering.HDPipeline

get { return HDEditorUtils.GetHDRenderPipelinePath() + "RenderPipelineResources/HDRenderPipelineResources.asset"; }
}
[MenuItem("RenderPipeline/HDRenderPipeline/Create Pipeline Asset", false, 16)]
[MenuItem("Assets/Create/Render Pipeline/High Definition/Render Pipeline", priority = CoreUtils.assetCreateMenuPriority1)]
static void CreateHDRenderPipeline()
{
var instance = ScriptableObject.CreateInstance<HDRenderPipelineAsset>();

// TODO skybox/cubemap
[MenuItem("RenderPipeline/HDRenderPipeline/Create Resources Asset", false, 15)]
[MenuItem("Assets/Create/Render Pipeline/High Definition/Render Pipeline Resources", priority = CoreUtils.assetCreateMenuPriority2)]
static void CreateRenderPipelineResources()
{
string HDRenderPipelinePath = HDEditorUtils.GetHDRenderPipelinePath();

28
ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs


public class HDRenderPipelineMenuItems
{
[MenuItem("HDRenderPipeline/Add \"Additional Light-shadow Data\" (if not present)")]
[MenuItem("Internal/HDRenderPipeline/Add \"Additional Light-shadow Data\" (if not present)")]
static void AddAdditionalLightData()
{
var lights = UnityObject.FindObjectsOfType(typeof(Light)) as Light[];

}
}
[MenuItem("HDRenderPipeline/Add \"Additional Camera Data\" (if not present)")]
[MenuItem("Internal/HDRenderPipeline/Add \"Additional Camera Data\" (if not present)")]
static void AddAdditionalCameraData()
{
var cameras = UnityObject.FindObjectsOfType(typeof(Camera)) as Camera[];

}
// This script is a helper for the artists to re-synchronize all layered materials
[MenuItem("HDRenderPipeline/Synchronize all Layered materials")]
[MenuItem("Internal/HDRenderPipeline/Synchronize all Layered materials")]
static void SynchronizeAllLayeredMaterial()
{
var materials = Resources.FindObjectsOfTypeAll<Material>();

// In case the shader code have change and the inspector have been update with new kind of keywords we need to regenerate the set of keywords use by the material.
// This script will remove all keyword of a material and trigger the inspector that will re-setup all the used keywords.
// It require that the inspector of the material have a static function call that update all keyword based on material properties.
[MenuItem("HDRenderPipeline/Test/Reset all materials keywords")]
[MenuItem("Edit/Render Pipeline/Upgrade/High Definition/Reset All Materials Keywords (Loaded Materials)", priority = CoreUtils.editMenuPriority2)]
static void ResetAllMaterialKeywords()
{
try

}
}
[MenuItem("HDRenderPipeline/Test/Reset all materials keywords in project")]
[MenuItem("Edit/Render Pipeline/Upgrade/High Definition/Reset All Materials Keywords (Materials in Project)", priority = CoreUtils.editMenuPriority2)]
static void ResetAllMaterialKeywordsInProject()
{
try

}
}
[MenuItem("HDRenderPipeline/Update/Update SSS profile indices")]
[MenuItem("Internal/HDRenderPipeline/Update/Update SSS profile indices")]
static void UpdateSSSProfileIndices()
{
try

}
// Function used only to check performance of data with and without tessellation
[MenuItem("HDRenderPipeline/Test/Remove tessellation materials (not reversible)")]
[MenuItem("Internal/HDRenderPipeline/Test/Remove tessellation materials (not reversible)")]
static void RemoveTessellationMaterials()
{
var materials = Resources.FindObjectsOfTypeAll<Material>();

}
}
[MenuItem("HDRenderPipeline/Export Sky to Image")]
[MenuItem("Edit/Render Pipeline/Tools/High Definition/Export Sky to Image", priority = CoreUtils.editMenuPriority2)]
static void ExportSkyToImage()
{
var renderpipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;

}
}
[MenuItem("GameObject/HD Render Pipeline/Scene Settings", false, 10)]
[MenuItem("GameObject/Render Pipeline/High Definition/Scene Settings", priority = 10)]
static void CreateCustomGameObject(MenuCommand menuCommand)
{
var sceneSettings = new GameObject("Scene Settings");

class DoCreateNewAssetProceduralSkySettings : DoCreateNewAsset<ProceduralSkySettings> {}
class DoCreateNewAssetSubsurfaceScatteringSettings : DoCreateNewAsset<SubsurfaceScatteringSettings> {}
[MenuItem("Assets/Create/HDRenderPipeline/Common Settings", priority = 700)]
[MenuItem("Assets/Create/Render Pipeline/High Definition/Common Settings", priority = CoreUtils.assetCreateMenuPriority2)]
static void MenuCreateCommonSettings()
{
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");

[MenuItem("Assets/Create/HDRenderPipeline/Subsurface Scattering Settings", priority = 702)]
[MenuItem("Assets/Create/Render Pipeline/High Definition/Subsurface Scattering Settings", priority = CoreUtils.assetCreateMenuPriority2)]
static void MenuCreateSubsurfaceScatteringProfile()
{
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");

[MenuItem("Assets/Create/HDRenderPipeline/HDRISky Settings", priority = 750)]
[MenuItem("Assets/Create/Render Pipeline/High Definition/HDRISky Settings", priority = CoreUtils.assetCreateMenuPriority2)]
static void MenuCreateHDRISkySettings()
{
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");

[MenuItem("Assets/Create/HDRenderPipeline/BlacksmithSky Settings", priority = 751)]
[MenuItem("Assets/Create/Render Pipeline/High Definition/BlacksmithSky Settings", priority = CoreUtils.assetCreateMenuPriority2)]
static void MenuCreateBlacksmithSkySettings()
{
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");

[MenuItem("Assets/Create/HDRenderPipeline/ProceduralSky Settings", priority = 752)]
[MenuItem("Assets/Create/Render Pipeline/High Definition/ProceduralSky Settings", priority = CoreUtils.assetCreateMenuPriority2)]
static void MenuCreateProceduralSkySettings()
{
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");

7
ScriptableRenderPipeline/HDRenderPipeline/Editor/UpgradeStandardShaderMaterials.cs


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

return upgraders;
}
[MenuItem("RenderPipeline/HDRenderPipeline/Material Upgraders/Upgrade Standard Materials to Lit Materials - Project Folder", false, 1)]
[MenuItem("Edit/Render Pipeline/Upgrade/High Definition/Upgrade Standard Materials to Lit Materials (Project)", priority = CoreUtils.editMenuPriority2)]
[MenuItem("RenderPipeline/HDRenderPipeline/Material Upgraders/Upgrade Standard Materials to Lit Materials - Selection", false, 2)]
[MenuItem("Edit/Render Pipeline/Upgrade/High Definition/Upgrade Standard Materials to Lit Materials (Selection)", priority = CoreUtils.editMenuPriority2)]
[MenuItem("RenderPipeline/HDRenderPipeline/Material Upgraders/Modify Light Intensity for Upgrade - Scene Only", false, 3)]
[MenuItem("Edit/Render Pipeline/Upgrade/High Definition/Modify Light Intensity for Upgrade (Scene Only)", priority = CoreUtils.editMenuPriority2)]
static void UpgradeLights()
{
Light[] lights = Light.GetLights(LightType.Directional, 0);

224
ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs


using System.Linq;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.Experimental.Rendering.HDPipeline.TilePass;
using UnityEngine.Profiling;
#if UNITY_EDITOR
using UnityEditor;

RenderTargetIdentifier m_CameraStencilBufferCopyRT;
RenderTargetIdentifier m_HTileRT;
static CustomSampler[] m_samplers = new CustomSampler[(int)CustomSamplerId.Max];
// The pass "SRPDefaultUnlit" is a fall back to legacy unlit rendering and is required to support unity 2d + unity UI that render in the scene.
ShaderPassName[] m_ForwardAndForwardOnlyPassNames = { new ShaderPassName(), new ShaderPassName(), HDShaderPassNames.s_SRPDefaultUnlitName};
ShaderPassName[] m_ForwardOnlyPassNames = { new ShaderPassName(), HDShaderPassNames.s_SRPDefaultUnlitName};

CommonSettings.Settings m_CommonSettings = CommonSettings.Settings.s_Defaultsettings;
SkySettings m_SkySettings = null;
static public CustomSampler GetSampler(CustomSamplerId id)
{
return m_samplers[(int)id];
}
public CommonSettings.Settings commonSettingsToUse
{
get

m_DebugDisplaySettings.RegisterDebug();
m_DebugFullScreenTempRT = HDShaderIDs._DebugFullScreenTexture;
// Init all samplers
for (int i = 0; i < (int)CustomSamplerId.Max; i++)
{
CustomSamplerId id = (CustomSamplerId)i;
m_samplers[i] = CustomSampler.Create("C#_" + id.ToString());
}
InitializeRenderStateBlocks();
RegisterDebug();

m_SkyManager.Cleanup();
#if UNITY_EDITOR
SupportedRenderingFeatures.active = SupportedRenderingFeatures.Default;
SupportedRenderingFeatures.active = new SupportedRenderingFeatures();
#endif
}

reflectionProbe = SupportedRenderingFeatures.ReflectionProbe.Rotation
reflectionProbeSupportFlags = SupportedRenderingFeatures.ReflectionProbeSupportFlags.Rotation
};
#endif

public void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd, SubsurfaceScatteringSettings sssParameters)
{
using (new ProfilingSample(cmd, "Push Global Parameters"))
using (new ProfilingSample(cmd, "Push Global Parameters", GetSampler(CustomSamplerId.PushGlobalParameters)))
// TODO: cmd.SetGlobalInt() does not exist, so we are forced to use Shader.SetGlobalInt() instead.
m_SkyManager.SetGlobalSkyTexture();
Shader.SetGlobalInt(HDShaderIDs._EnvLightSkyEnabled, 1);
m_SkyManager.SetGlobalSkyTexture(cmd);
cmd.SetGlobalInt(HDShaderIDs._EnvLightSkyEnabled, 1);
Shader.SetGlobalInt(HDShaderIDs._EnvLightSkyEnabled, 0);
cmd.SetGlobalInt(HDShaderIDs._EnvLightSkyEnabled, 0);
Shader.SetGlobalInt( HDShaderIDs._EnableSSSAndTransmission, m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission ? 1 : 0);
Shader.SetGlobalInt( HDShaderIDs._TexturingModeFlags, sssParameters.texturingModeFlags);
Shader.SetGlobalInt( HDShaderIDs._TransmissionFlags, sssParameters.transmissionFlags);
Shader.SetGlobalInt( HDShaderIDs._UseDisneySSS, sssParameters.useDisneySSS ? 1 : 0);
cmd.SetGlobalInt(HDShaderIDs._EnableSSSAndTransmission, m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission ? 1 : 0);
cmd.SetGlobalInt(HDShaderIDs._UseDisneySSS, sssParameters.useDisneySSS ? 1 : 0);
unsafe
{
// Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system.
// Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader.
uint texturingModeFlags = sssParameters.texturingModeFlags;
uint transmissionFlags = sssParameters.transmissionFlags;
cmd.SetGlobalFloat(HDShaderIDs._TexturingModeFlags, *(float*)&texturingModeFlags);
cmd.SetGlobalFloat(HDShaderIDs._TransmissionFlags, *(float*)&transmissionFlags);
}
cmd.SetGlobalVectorArray(HDShaderIDs._ThicknessRemaps, sssParameters.thicknessRemaps);
cmd.SetGlobalVectorArray(HDShaderIDs._ShapeParams, sssParameters.shapeParams);
cmd.SetGlobalVectorArray(HDShaderIDs._HalfRcpVariancesAndWeights, sssParameters.halfRcpVariancesAndWeights);

void CopyDepthBufferIfNeeded(CommandBuffer cmd)
{
using (new ProfilingSample(cmd, NeedDepthBufferCopy() ? "Copy DepthBuffer" : "Set DepthBuffer"))
using (new ProfilingSample(cmd, NeedDepthBufferCopy() ? "Copy DepthBuffer" : "Set DepthBuffer", GetSampler(CustomSamplerId.CopySetDepthBuffer)))
using (new ProfilingSample(cmd, "Copy depth-stencil buffer"))
using (new ProfilingSample(cmd, "Copy depth-stencil buffer", GetSampler(CustomSamplerId.CopyDepthStencilbuffer)))
{
cmd.CopyTexture(m_CameraDepthStencilBufferRT, m_CameraDepthBufferCopyRT);
}

{
if (NeedStencilBufferCopy())
{
using (new ProfilingSample(cmd, "Copy StencilBuffer"))
using (new ProfilingSample(cmd, "Copy StencilBuffer", GetSampler(CustomSamplerId.CopyStencilBuffer)))
{
cmd.SetRandomWriteTarget(1, GetHTile());
// Our method of exporting the stencil requires one pass per unique stencil value.

CullResults m_CullResults;
public override void Render(ScriptableRenderContext renderContext, Camera[] cameras)
{
base.Render(renderContext, cameras);
// This is the main command buffer used for the frame.
var cmd = CommandBufferPool.Get("");
using (new ProfilingSample(cmd, "HDRenderPipeline::Render", GetSampler(CustomSamplerId.HDRenderPipelineRender)))
{
base.Render(renderContext, cameras);
#if UNITY_EDITOR
SupportedRenderingFeatures.active = s_NeededFeatures;

HDCamera.CleanUnused();
m_FrameCount = Time.frameCount;
}
// This is the main command buffer used for the frame.
var cmd = CommandBufferPool.Get("");
foreach (var material in m_MaterialList)
material.RenderInit(cmd);

m_CurrentDebugDisplaySettings = m_DebugDisplaySettings;
}
ApplyDebugDisplaySettings();
ApplyDebugDisplaySettings(cmd);
UpdateCommonSettings();
ScriptableCullingParameters cullingParams;

}
#endif
CullResults.Cull(ref cullingParams, renderContext,ref m_CullResults);
using (new ProfilingSample(cmd, "CullResults.Cull", GetSampler(CustomSamplerId.CullResultsCull)))
{
CullResults.Cull(ref cullingParams, renderContext,ref m_CullResults);
}
Resize(camera);

// TODO: Add another path dedicated to planar reflection / real time cubemap that implement simpler lighting
// It is up to the users to only send unlit object for this camera path
using (new ProfilingSample(cmd, "Forward"))
using (new ProfilingSample(cmd, "Forward", GetSampler(CustomSamplerId.Forward)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Color | ClearFlag.Depth);
RenderOpaqueRenderList(m_CullResults, camera, renderContext, cmd, HDShaderPassNames.s_ForwardName);

// Currently to know if you need shadow mask you need to go through all visible lights (of CullResult), check the LightBakingOutput struct and look at lightmapBakeType/mixedLightingMode. If one light have shadow mask bake mode, then you need shadow mask features (i.e extra Gbuffer).
// It mean that when we build a standalone player, if we detect a light with bake shadow mask, we generate all shader variant (with and without shadow mask) and at runtime, when a bake shadow mask light is visible, we dynamically allocate an extra GBuffer and switch the shader.
// So the first thing to do is to go through all the light: PrepareLightsForGPU
bool enableBakeShadowMask = m_LightLoop.PrepareLightsForGPU(m_ShadowSettings, m_CullResults, camera);
bool enableBakeShadowMask;
using (new ProfilingSample(cmd, "TP_PrepareLightsForGPU", GetSampler(CustomSamplerId.TPPrepareLightsForGPU)))
{
enableBakeShadowMask = m_LightLoop.PrepareLightsForGPU(m_ShadowSettings, m_CullResults, camera);
}
ConfigureForShadowMask(enableBakeShadowMask, cmd);
InitAndClearBuffer(hdCamera, enableBakeShadowMask, cmd);

}
else
{
using (new ProfilingSample(cmd, "Build Light list and render shadows"))
using (new ProfilingSample(cmd, "Render SSAO", GetSampler(CustomSamplerId.RenderSSAO)))
// Apply SSAO from PostprocessLayer
if (postProcessLayer != null)
{
var settings = postProcessLayer.GetSettings<AmbientOcclusion>();
if (settings.IsEnabledAndSupported(null))
{
cmd.GetTemporaryRT(HDShaderIDs._AmbientOcclusionTexture, new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight, RenderTextureFormat.R8, 0)
{
sRGB = false,
enableRandomWrite = true
}, FilterMode.Bilinear);
postProcessLayer.BakeMSVOMap(cmd, camera, HDShaderIDs._AmbientOcclusionTexture, GetDepthTexture(), true);
cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, new Vector4(settings.color.value.r, settings.color.value.g, settings.color.value.b, settings.directLightingStrength.value));
PushFullScreenDebugTexture(cmd, HDShaderIDs._AmbientOcclusionTexture, camera, renderContext, FullScreenDebugMode.SSAO);
}
else
{
cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, RuntimeUtilities.blackTexture); // Neutral is black, see the comment in the shaders
cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, Vector4.zero);
}
}
RenderSSAO(cmd, camera, renderContext, postProcessLayer);
}
using (new ProfilingSample(cmd, "Render shadows", GetSampler(CustomSamplerId.RenderShadows)))
{
// TODO: check if statement below still apply
renderContext.SetupCameraProperties(camera); // Need to recall SetupCameraProperties after RenderShadows as it modify our view/proj matrix
}
cmd.GetTemporaryRT(m_DeferredShadowBuffer, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear, 1 , true);
using (new ProfilingSample(cmd, "Deferred directional shadows", GetSampler(CustomSamplerId.RenderDeferredDirectionalShadow)))
{
cmd.GetTemporaryRT(m_DeferredShadowBuffer, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear, 1, true);
}
renderContext.SetupCameraProperties(camera); // Need to recall SetupCameraProperties after m_ShadowPass.Render
using (new ProfilingSample(cmd, "Build Light list", GetSampler(CustomSamplerId.BuildLightList)))
{
m_LightLoop.BuildGPULightLists(camera, cmd, m_CameraDepthStencilBufferRT, GetStencilTexture());
}

// Planar and real time cubemap doesn't need post process and render in FP16
if (camera.cameraType == CameraType.Reflection)
{
using (new ProfilingSample(cmd, "Blit to final RT"))
using (new ProfilingSample(cmd, "Blit to final RT", GetSampler(CustomSamplerId.BlitToFinalRT)))
{
// Simple blit
cmd.Blit(m_CameraColorBufferRT, BuiltinRenderTextureType.CameraTarget);

renderContext.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
renderContext.Submit();
}
}
void RenderOpaqueRenderList(CullResults cull,

if (!m_CurrentDebugDisplaySettings.renderingDebugSettings.enableDistortion)
return;
using (new ProfilingSample(cmd, "Distortion"))
using (new ProfilingSample(cmd, "Distortion", GetSampler(CustomSamplerId.Distortion)))
{
int w = camera.pixelWidth;
int h = camera.pixelHeight;

void RenderDistortion(CommandBuffer cmd, RenderPipelineResources resources)
{
using (new ProfilingSample(cmd, "ApplyDistortion"))
using (new ProfilingSample(cmd, "ApplyDistortion", GetSampler(CustomSamplerId.ApplyDistortion)))
{
var size = new Vector4(m_CurrentWidth, m_CurrentHeight, 1f / m_CurrentWidth, 1f / m_CurrentHeight);
uint x, y, z;

bool addFullDepthPrepass = m_Asset.renderingSettings.ShouldUseForwardRenderingOnly() || m_Asset.renderingSettings.useDepthPrepassWithDeferredRendering;
bool addAlphaTestedOnly = !m_Asset.renderingSettings.ShouldUseForwardRenderingOnly() && m_Asset.renderingSettings.useDepthPrepassWithDeferredRendering && m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass;
using (new ProfilingSample(cmd, addAlphaTestedOnly ? "Depth Prepass alpha test" : "Depth Prepass"))
using (new ProfilingSample(cmd, addAlphaTestedOnly ? "Depth Prepass alpha test" : "Depth Prepass", GetSampler(CustomSamplerId.DepthPrepass)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraDepthStencilBufferRT);
if (addFullDepthPrepass && !addAlphaTestedOnly) // Always true in case of forward rendering, use in case of deferred rendering if requesting a full depth prepass

if (m_Asset.renderingSettings.ShouldUseForwardRenderingOnly())
return;
using (new ProfilingSample(cmd, m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() ? "GBufferDebugDisplay" : "GBuffer"))
using (new ProfilingSample(cmd, m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() ? "GBufferDebugDisplay" : "GBuffer", GetSampler(CustomSamplerId.GBuffer)))
{
// setup GBuffer for rendering
CoreUtils.SetRenderTarget(cmd, m_GbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT);

void RenderDebugViewMaterial(CullResults cull, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd)
{
using (new ProfilingSample(cmd, "DisplayDebug ViewMaterial"))
using (new ProfilingSample(cmd, "DisplayDebug ViewMaterial", GetSampler(CustomSamplerId.DisplayDebugViewMaterial)))
using (new ProfilingSample(cmd, "DebugViewMaterialGBuffer"))
using (new ProfilingSample(cmd, "DebugViewMaterialGBuffer", GetSampler(CustomSamplerId.DebugViewMaterialGBuffer)))
{
CoreUtils.DrawFullScreen(cmd, m_currentDebugViewMaterialGBuffer, m_CameraColorBufferRT);
}

// Last blit
{
using (new ProfilingSample(cmd, "Blit DebugView Material Debug"))
using (new ProfilingSample(cmd, "Blit DebugView Material Debug", GetSampler(CustomSamplerId.BlitDebugViewMaterialDebug)))
{
cmd.Blit(m_CameraColorBufferRT, BuiltinRenderTextureType.CameraTarget);
}

void RenderSSAO(CommandBuffer cmd, Camera camera, ScriptableRenderContext renderContext, PostProcessLayer postProcessLayer)
{
// Apply SSAO from PostProcessLayer
if (postProcessLayer != null && postProcessLayer.enabled)
{
var settings = postProcessLayer.GetSettings<AmbientOcclusion>();
if (settings.IsEnabledAndSupported(null))
{
cmd.GetTemporaryRT(HDShaderIDs._AmbientOcclusionTexture, new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight, RenderTextureFormat.R8, 0)
{
sRGB = false,
enableRandomWrite = true
}, FilterMode.Bilinear);
postProcessLayer.BakeMSVOMap(cmd, camera, HDShaderIDs._AmbientOcclusionTexture, GetDepthTexture(), true);
cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, new Vector4(settings.color.value.r, settings.color.value.g, settings.color.value.b, settings.directLightingStrength.value));
PushFullScreenDebugTexture(cmd, HDShaderIDs._AmbientOcclusionTexture, camera, renderContext, FullScreenDebugMode.SSAO);
return;
}
}
// No AO applied - neutral is black, see the comment in the shaders
cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, RuntimeUtilities.blackTexture);
cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, Vector4.zero);
}
void RenderDeferredLighting(HDCamera hdCamera, CommandBuffer cmd)
{
if (m_Asset.renderingSettings.ShouldUseForwardRenderingOnly())

// Output split lighting for materials asking for it (masked in the stencil buffer)
options.outputSplitLighting = true;
m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, m_MRTCache2, m_CameraDepthStencilBufferRT, depthTexture, m_DeferredShadowBuffer, options);
m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, m_MRTCache2, m_CameraDepthStencilBufferRT, depthTexture, options);
m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, m_MRTCache2, m_CameraDepthStencilBufferRT, depthTexture, m_DeferredShadowBuffer, options);
m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, m_MRTCache2, m_CameraDepthStencilBufferRT, depthTexture, options);
}
// Combines specular lighting and diffuse lighting with subsurface scattering.

if (!m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission || m_Asset.renderingSettings.ShouldUseForwardRenderingOnly())
return;
using (new ProfilingSample(cmd, "Subsurface Scattering"))
using (new ProfilingSample(cmd, "Subsurface Scattering", GetSampler(CustomSamplerId.SubsurfaceScattering)))
// TODO: Remove this once fix, see comment inside the function
cmd.SetComputeIntParam( m_SubsurfaceScatteringCS, HDShaderIDs._TexturingModeFlags, sssParameters.texturingModeFlags);
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._WorldScales, sssParameters.worldScales);
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._FilterKernels, sssParameters.filterKernels);
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._ShapeParams, sssParameters.shapeParams);
unsafe
{
// Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system.
// Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader.
uint texturingModeFlags = sssParameters.texturingModeFlags;
cmd.SetComputeFloatParam(m_SubsurfaceScatteringCS, HDShaderIDs._TexturingModeFlags, *(float*)&texturingModeFlags);
}
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._WorldScales, sssParameters.worldScales);
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._FilterKernels, sssParameters.filterKernels);
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._ShapeParams, sssParameters.shapeParams);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture0, m_GbufferManager.GetGBuffers()[0]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture1, m_GbufferManager.GetGBuffers()[1]);

profileName = k_ForwardPassName[(int)pass];
}
using (new ProfilingSample(cmd, profileName))
using (new ProfilingSample(cmd, profileName, GetSampler(CustomSamplerId.ForwardPassName)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);

void RenderTransparentDepthPrepass(CullResults cullResults, Camera camera, ScriptableRenderContext renderContext, CommandBuffer cmd)
{
using (new ProfilingSample(cmd,"Forward Transparent Depth Prepass"))
using (new ProfilingSample(cmd,"Forward Transparent Depth Prepass", GetSampler(CustomSamplerId.ForwardTransparentDepthPrepass)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraDepthStencilBufferRT);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, HDShaderPassNames.s_TransparentDepthPrepassName, preRefractionQueue: true);

[Conditional("DEVELOPMENT_BUILD"), Conditional("UNITY_EDITOR")]
void RenderForwardError(CullResults cullResults, Camera camera, ScriptableRenderContext renderContext, CommandBuffer cmd, ForwardPass pass)
{
using (new ProfilingSample(cmd, "Render Forward Error"))
using (new ProfilingSample(cmd, "Render Forward Error", GetSampler(CustomSamplerId.RenderForwardError)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);

void RenderVelocity(CullResults cullResults, HDCamera hdcam, ScriptableRenderContext renderContext, CommandBuffer cmd)
{
using (new ProfilingSample(cmd, "Velocity"))
using (new ProfilingSample(cmd, "Velocity", GetSampler(CustomSamplerId.Velocity)))
{
// If opaque velocity have been render during GBuffer no need to render it here
// TODO: Currently we can't render velocity vector into GBuffer, neither during forward pass (in case of forward opaque), so it is always a separate pass

if (!m_CurrentDebugDisplaySettings.renderingDebugSettings.enableGaussianPyramid)
return;
using (new ProfilingSample(cmd, "Gaussian Pyramid Color"))
using (new ProfilingSample(cmd, "Gaussian Pyramid Color", GetSampler(CustomSamplerId.GaussianPyramidColor)))
{
int w = camera.pixelWidth;
int h = camera.pixelHeight;

if (!m_CurrentDebugDisplaySettings.renderingDebugSettings.enableGaussianPyramid)
return;
using (new ProfilingSample(cmd, "Pyramid Depth"))
using (new ProfilingSample(cmd, "Pyramid Depth", GetSampler(CustomSamplerId.PyramidDepth)))
{
int w = camera.pixelWidth;
int h = camera.pixelHeight;

void RenderPostProcesses(Camera camera, CommandBuffer cmd, PostProcessLayer layer)
{
using (new ProfilingSample(cmd, "Post-processing"))
using (new ProfilingSample(cmd, "Post-processing", GetSampler(CustomSamplerId.PostProcessing)))
{
if (CoreUtils.IsPostProcessingActive(layer))
{

}
}
public void ApplyDebugDisplaySettings()
public void ApplyDebugDisplaySettings(CommandBuffer cmd)
{
m_ShadowSettings.enabled = m_CurrentDebugDisplaySettings.lightingDebugSettings.enableShadows;

Shader.SetGlobalInt(HDShaderIDs._DebugViewMaterial, (int)m_CurrentDebugDisplaySettings.GetDebugMaterialIndex());
Shader.SetGlobalInt(HDShaderIDs._DebugLightingMode, (int)m_CurrentDebugDisplaySettings.GetDebugLightingMode());
Shader.SetGlobalVector(HDShaderIDs._DebugLightingAlbedo, debugAlbedo);
Shader.SetGlobalVector(HDShaderIDs._DebugLightingSmoothness, debugSmoothness);
cmd.SetGlobalInt(HDShaderIDs._DebugViewMaterial, (int)m_CurrentDebugDisplaySettings.GetDebugMaterialIndex());
cmd.SetGlobalInt(HDShaderIDs._DebugLightingMode, (int)m_CurrentDebugDisplaySettings.GetDebugLightingMode());
cmd.SetGlobalVector(HDShaderIDs._DebugLightingAlbedo, debugAlbedo);
cmd.SetGlobalVector(HDShaderIDs._DebugLightingSmoothness, debugSmoothness);
}
public void PushFullScreenDebugTexture(CommandBuffer cb, RenderTargetIdentifier textureID, Camera camera, ScriptableRenderContext renderContext, FullScreenDebugMode debugMode)

if (camera.camera.cameraType == CameraType.Reflection || camera.camera.cameraType == CameraType.Preview)
return;
using (new ProfilingSample(cmd, "Render Debug"))
using (new ProfilingSample(cmd, "Render Debug", GetSampler(CustomSamplerId.RenderDebug)))
{
// We make sure the depth buffer is bound because we need it to write depth at near plane for overlays otherwise the editor grid end up visible in them.
CoreUtils.SetRenderTarget(cmd, BuiltinRenderTextureType.CameraTarget, m_CameraDepthStencilBufferRT);

void InitAndClearBuffer(HDCamera camera, bool enableBakeShadowMask, CommandBuffer cmd)
{
using (new ProfilingSample(cmd, "InitAndClearBuffer"))
using (new ProfilingSample(cmd, "InitAndClearBuffer", GetSampler(CustomSamplerId.InitAndClearBuffer)))
using (new ProfilingSample(cmd, "InitGBuffers and clear Depth/Stencil"))
using (new ProfilingSample(cmd, "InitGBuffers and clear Depth/Stencil", GetSampler(CustomSamplerId.InitGBuffersAndClearDepthStencil)))
{
// Init buffer
// With scriptable render loop we must allocate ourself depth and color buffer (We must be independent of backbuffer for now, hope to fix that later).

}
// Clear the diffuse SSS lighting target
using (new ProfilingSample(cmd, "Clear SSS diffuse target"))
using (new ProfilingSample(cmd, "Clear SSS diffuse target", GetSampler(CustomSamplerId.ClearSSSDiffuseTarget)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraSssDiffuseLightingBufferRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}

{
// Clear the SSS filtering target
using (new ProfilingSample(cmd, "Clear SSS filtering target"))
using (new ProfilingSample(cmd, "Clear SSS filtering target", GetSampler(CustomSamplerId.ClearSSSFilteringTarget)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraFilteringBuffer, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}

if (NeedStencilBufferCopy())
{
using (new ProfilingSample(cmd, "Clear stencil texture"))
using (new ProfilingSample(cmd, "Clear stencil texture", GetSampler(CustomSamplerId.ClearStencilTexture)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraStencilBufferCopyRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}

{
using (new ProfilingSample(cmd, "Clear HTile"))
using (new ProfilingSample(cmd, "Clear HTile", GetSampler(CustomSamplerId.ClearHTile)))
{
CoreUtils.SetRenderTarget(cmd, m_HTileRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}

// Clear the HDR target
using (new ProfilingSample(cmd, "Clear HDR target"))
using (new ProfilingSample(cmd, "Clear HDR target", GetSampler(CustomSamplerId.ClearHDRTarget)))
{
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}

{
using (new ProfilingSample(cmd, "Clear GBuffer"))
using (new ProfilingSample(cmd, "Clear GBuffer", GetSampler(CustomSamplerId.ClearGBuffer)))
{
CoreUtils.SetRenderTarget(cmd, m_GbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDUtils.cs


public class HDUtils
{
public const RendererConfiguration k_RendererConfigurationBakedLighting = RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbeProxyVolume;
public const RendererConfiguration k_RendererConfigurationBakedLightingWithShadowMask = RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbeProxyVolume;
public const RendererConfiguration k_RendererConfigurationBakedLightingWithShadowMask = k_RendererConfigurationBakedLighting | RendererConfiguration.PerObjectOcclusionProbe | RendererConfiguration.PerObjectOcclusionProbeProxyVolume | RendererConfiguration.PerObjectShadowMask;
public static List<RenderPipelineMaterial> GetRenderPipelineMaterialList()
{

15
ScriptableRenderPipeline/HDRenderPipeline/Lighting/Deferred.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
// #pragma enable_d3d11_debug_symbols
#pragma vertex Vert

#endif
Outputs outputs;
outputs.specularLighting = float4(specularLighting, 1.0);
outputs.diffuseLighting = TagLightingForSSS(diffuseLighting);
if (_EnableSSSAndTransmission != 0)
{
outputs.specularLighting = float4(specularLighting, 1.0);
outputs.diffuseLighting = TagLightingForSSS(diffuseLighting);
}
else
{
outputs.specularLighting = float4(diffuseLighting + specularLighting, 1.0);
outputs.diffuseLighting = 0;
}
#else
outputs.combinedLighting = float4(diffuseLighting + specularLighting, 1.0);
#endif

328
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs


RenderTargetIdentifier[] tex;
sc.GetTex2DArrays(out tex, out offset, out count);
if(computeShader)
{
// bind buffers
cb.SetComputeBufferParam(computeShader, computeKernel, HDShaderIDs._ShadowDatasExp, s_ShadowDataBuffer);
cb.SetComputeBufferParam(computeShader, computeKernel, HDShaderIDs._ShadowPayloads, s_ShadowPayloadBuffer);
// bind textures
cb.SetComputeTextureParam(computeShader, computeKernel, HDShaderIDs._ShadowmapExp_VSM_0, tex[0]);
cb.SetComputeTextureParam(computeShader, computeKernel, HDShaderIDs._ShadowmapExp_VSM_1, tex[1]);
cb.SetComputeTextureParam(computeShader, computeKernel, HDShaderIDs._ShadowmapExp_VSM_2, tex[2]);
cb.SetComputeTextureParam(computeShader, computeKernel, HDShaderIDs._ShadowmapExp_PCF, tex[3]);
}
else
{
// bind buffers
cb.SetGlobalBuffer(HDShaderIDs._ShadowDatasExp, s_ShadowDataBuffer);
cb.SetGlobalBuffer(HDShaderIDs._ShadowPayloads, s_ShadowPayloadBuffer);
// bind textures
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_VSM_0, tex[0]);
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_VSM_1, tex[1]);
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_VSM_2, tex[2]);
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_PCF, tex[3]);
}
// bind buffers
cb.SetGlobalBuffer(HDShaderIDs._ShadowDatasExp, s_ShadowDataBuffer);
cb.SetGlobalBuffer(HDShaderIDs._ShadowPayloads, s_ShadowPayloadBuffer);
// bind textures
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_VSM_0, tex[0]);
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_VSM_1, tex[1]);
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_VSM_2, tex[2]);
cb.SetGlobalTexture(HDShaderIDs._ShadowmapExp_PCF, tex[3]);
// TODO: Currently samplers are hard coded in ShadowContext.hlsl, so we can't really set them here
};

cmd.SetComputeBufferParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, s_TileFeatureFlags);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, stencilTextureRT);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture0, HDShaderIDs._GBufferTexture0);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture1, HDShaderIDs._GBufferTexture1);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture2, HDShaderIDs._GBufferTexture2);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture3, HDShaderIDs._GBufferTexture3);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._ShadowMaskTexture, HDShaderIDs._ShadowMaskTexture);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._VelocityTexture, HDShaderIDs._VelocityTexture);
cmd.DispatchCompute(buildMaterialFlagsShader, buildMaterialFlagsKernel, numTilesX, numTilesY, 1);
}

}
cmd.EndSample("Build Light List");
}
// This is a workaround for global properties not being accessible from compute.
// When activeComputeShader is set, all calls to SetGlobalXXX will set the property on the select compute shader instead of the global scope.
private ComputeShader activeComputeShader;
private int activeComputeKernel;
private CommandBuffer activeCommandBuffer;
private void SetGlobalPropertyRedirect(ComputeShader computeShader, int computeKernel, CommandBuffer commandBuffer)
{
activeComputeShader = computeShader;
activeComputeKernel = computeKernel;
activeCommandBuffer = commandBuffer;
}
private void SetGlobalTexture(int nameID, Texture value)
{
if (activeComputeShader)
activeCommandBuffer.SetComputeTextureParam(activeComputeShader, activeComputeKernel, nameID, value);
else
activeCommandBuffer.SetGlobalTexture(nameID, value);
}
private void SetGlobalBuffer(int nameID, ComputeBuffer buffer)
{
if (activeComputeShader)
activeCommandBuffer.SetComputeBufferParam(activeComputeShader, activeComputeKernel, nameID, buffer);
else
activeCommandBuffer.SetGlobalBuffer(nameID, buffer);
}
private void SetGlobalInt(int nameID, int value)
{
if (activeComputeShader)
activeCommandBuffer.SetComputeIntParam(activeComputeShader, nameID, value);
else
Shader.SetGlobalInt(nameID, value);
}
private void SetGlobalFloat(int nameID, float value)
{
if (activeComputeShader)
activeCommandBuffer.SetComputeFloatParam(activeComputeShader, nameID, value);
else
activeCommandBuffer.SetGlobalFloat(nameID, value);
}
private void SetGlobalVector(int nameID, Vector4 value)
{
if (activeComputeShader)
activeCommandBuffer.SetComputeVectorParam(activeComputeShader, nameID, value);
else
activeCommandBuffer.SetGlobalVector(nameID, value);
}
private void SetGlobalVectorArray(int nameID, Vector4[] values)
{
if (activeComputeShader)
{
activeCommandBuffer.SetComputeVectorArrayParam(activeComputeShader, nameID, values);
}
else
{
activeCommandBuffer.SetGlobalVectorArray(nameID, values);
}
PushGlobalParams(camera, cmd);
}
private void UpdateDataBuffers()

s_LightVolumeDataBuffer.SetData(m_lightList.lightVolumes);
}
private void BindGlobalParams(CommandBuffer cmd, Camera camera, bool forceClustered)
void PushGlobalParams(Camera camera, CommandBuffer cmd)
m_ShadowMgr.BindResources(cmd, activeComputeShader, activeComputeKernel);
using (new ProfilingSample(cmd, "Push Global Parameters", HDRenderPipeline.GetSampler(CustomSamplerId.TPPushGlobalParameters)))
{
// Shadows
m_ShadowMgr.SyncData();
m_ShadowMgr.BindResources(cmd, null, 0);
SetGlobalBuffer(HDShaderIDs.g_vLightListGlobal, (forceClustered || !usingFptl) ? s_PerVoxelLightLists : s_LightList); // opaques list (unless MSAA possibly)
cmd.SetGlobalTexture(HDShaderIDs._CookieTextures, m_CookieTexArray.GetTexCache());
cmd.SetGlobalTexture(HDShaderIDs._CookieCubeTextures, m_CubeCookieTexArray.GetTexCache());
cmd.SetGlobalTexture(HDShaderIDs._EnvTextures, m_CubeReflTexArray.GetTexCache());
SetGlobalTexture(HDShaderIDs._CookieTextures, m_CookieTexArray.GetTexCache());
SetGlobalTexture(HDShaderIDs._CookieCubeTextures, m_CubeCookieTexArray.GetTexCache());
SetGlobalTexture(HDShaderIDs._EnvTextures, m_CubeReflTexArray.GetTexCache());
cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, s_DirectionalLightDatas);
cmd.SetGlobalInt(HDShaderIDs._DirectionalLightCount, m_lightList.directionalLights.Count);
cmd.SetGlobalBuffer(HDShaderIDs._LightDatas, s_LightDatas);
cmd.SetGlobalInt(HDShaderIDs._PunctualLightCount, m_punctualLightCount);
cmd.SetGlobalInt(HDShaderIDs._AreaLightCount, m_areaLightCount);
cmd.SetGlobalBuffer(HDShaderIDs._EnvLightDatas, s_EnvLightDatas);
cmd.SetGlobalInt(HDShaderIDs._EnvLightCount, m_lightList.envLights.Count);
cmd.SetGlobalBuffer(HDShaderIDs._ShadowDatas, s_shadowDatas);
cmd.SetGlobalVectorArray(HDShaderIDs._DirShadowSplitSpheres, m_lightList.directionalShadowSplitSphereSqr);
SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, s_DirectionalLightDatas);
SetGlobalInt(HDShaderIDs._DirectionalLightCount, m_lightList.directionalLights.Count);
SetGlobalBuffer(HDShaderIDs._LightDatas, s_LightDatas);
SetGlobalInt(HDShaderIDs._PunctualLightCount, m_punctualLightCount);
SetGlobalInt(HDShaderIDs._AreaLightCount, m_areaLightCount);
SetGlobalBuffer(HDShaderIDs._EnvLightDatas, s_EnvLightDatas);
SetGlobalInt(HDShaderIDs._EnvLightCount, m_lightList.envLights.Count);
SetGlobalBuffer(HDShaderIDs._ShadowDatas, s_shadowDatas);
SetGlobalVectorArray(HDShaderIDs._DirShadowSplitSpheres, m_lightList.directionalShadowSplitSphereSqr);
SetGlobalInt(HDShaderIDs._NumTileFtplX, GetNumTileFtplX(camera));
SetGlobalInt(HDShaderIDs._NumTileFtplY, GetNumTileFtplY(camera));
SetGlobalInt(HDShaderIDs._NumTileClusteredX, GetNumTileClusteredX(camera));
SetGlobalInt(HDShaderIDs._NumTileClusteredY, GetNumTileClusteredY(camera));
if (m_TileSettings.enableBigTilePrepass)
SetGlobalBuffer(HDShaderIDs.g_vBigTileLightList, s_BigTileLightList);
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplX, GetNumTileFtplX(camera));
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplY, GetNumTileFtplY(camera));
if (m_TileSettings.enableClustered)
{
SetGlobalFloat(HDShaderIDs.g_fClustScale, m_ClustScale);
SetGlobalFloat(HDShaderIDs.g_fClustBase, k_ClustLogBase);
SetGlobalFloat(HDShaderIDs.g_fNearPlane, camera.nearClipPlane);
SetGlobalFloat(HDShaderIDs.g_fFarPlane, camera.farClipPlane);
SetGlobalInt(HDShaderIDs.g_iLog2NumClusters, k_Log2NumClusters);
cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredX, GetNumTileClusteredX(camera));
cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredY, GetNumTileClusteredY(camera));
SetGlobalInt(HDShaderIDs.g_isLogBaseBufferEnabled, k_UseDepthBuffer ? 1 : 0);
if (m_TileSettings.enableBigTilePrepass)
cmd.SetGlobalBuffer(HDShaderIDs.g_vBigTileLightList, s_BigTileLightList);
SetGlobalBuffer(HDShaderIDs.g_vLayeredOffsetsBuffer, s_PerVoxelOffset);
if (k_UseDepthBuffer)
if (m_TileSettings.enableClustered)
SetGlobalBuffer(HDShaderIDs.g_logBaseBuffer, s_PerTileLogBaseTweak);
}
}
}
public void PushGlobalParams(Camera camera, CommandBuffer cmd, ComputeShader computeShader, int kernelIndex, bool forceClustered = false)
{
using (new ProfilingSample(cmd, "Push Global Parameters"))
{
// Shadows
m_ShadowMgr.SyncData();
cmd.SetGlobalFloat(HDShaderIDs.g_fClustScale, m_ClustScale);
cmd.SetGlobalFloat(HDShaderIDs.g_fClustBase, k_ClustLogBase);
cmd.SetGlobalFloat(HDShaderIDs.g_fNearPlane, camera.nearClipPlane);
cmd.SetGlobalFloat(HDShaderIDs.g_fFarPlane, camera.farClipPlane);
cmd.SetGlobalInt(HDShaderIDs.g_iLog2NumClusters, k_Log2NumClusters);
cmd.SetGlobalInt(HDShaderIDs.g_isLogBaseBufferEnabled, k_UseDepthBuffer ? 1 : 0);
SetGlobalPropertyRedirect(computeShader, kernelIndex, cmd);
BindGlobalParams(cmd, camera, forceClustered);
SetGlobalPropertyRedirect(null, 0, null);
cmd.SetGlobalBuffer(HDShaderIDs.g_vLayeredOffsetsBuffer, s_PerVoxelOffset);
if (k_UseDepthBuffer)
{
cmd.SetGlobalBuffer(HDShaderIDs.g_logBaseBuffer, s_PerTileLogBaseTweak);
}
}
}
}

if (lightingDebug.tileDebugByCategory == TileSettings.TileDebug.None)
return;
using (new ProfilingSample(cmd, "Tiled Lighting Debug"))
using (new ProfilingSample(cmd, "Tiled Lighting Debug", HDRenderPipeline.GetSampler(CustomSamplerId.TPTiledLightingDebug)))
{
bool bUseClusteredForDeferred = !usingFptl;

#endif
// Debug tiles
PushGlobalParams(hdCamera.camera, cmd, null, 0);
if (lightingDebug.tileDebugByCategory == TileSettings.TileDebug.FeatureVariants)
{
if (GetFeatureVariantsEnabled(m_TileSettings))

CoreUtils.DrawFullScreen(cmd, m_DebugViewTilesMaterial, 0, colorBuffer);
}
SetGlobalPropertyRedirect(null, 0, null);
}
}

if (m_CurrentSunLight == null)
return;
using (new ProfilingSample(cmd, "Deferred Directional"))
using (new ProfilingSample(cmd, "Deferred Directional Shadow", HDRenderPipeline.GetSampler(CustomSamplerId.TPDeferredDirectionalShadow)))
hdCamera.SetupComputeShader(deferredDirectionalShadowComputeShader, cmd);
m_ShadowMgr.BindResources(cmd, deferredDirectionalShadowComputeShader, s_deferredDirectionalShadowKernel);
cmd.SetComputeFloatParam(deferredDirectionalShadowComputeShader, HDShaderIDs._DirectionalShadowIndex, (float)m_CurrentSunLightShadowIndex);

public void RenderDeferredLighting( HDCamera hdCamera, CommandBuffer cmd,
DebugDisplaySettings debugDisplaySettings,
RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthStencilBuffer, RenderTargetIdentifier depthTexture, RenderTargetIdentifier deferredShadowTexture,
RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthStencilBuffer, RenderTargetIdentifier depthTexture,
cmd.SetGlobalBuffer(HDShaderIDs.g_vLightListGlobal, bUseClusteredForDeferred ? s_PerVoxelLightLists : s_LightList);
if (m_TileSettings.enableTileAndCluster && m_TileSettings.enableComputeLightEvaluation && options.outputSplitLighting)
{

string singlePassName = "SinglePass - Deferred Lighting Pass";
string SinglePassMRTName = "SinglePass - Deferred Lighting Pass MRT";
using (new ProfilingSample(cmd, m_TileSettings.enableTileAndCluster ?
// TODO: Check if we can remove this, when I test I can't
Texture skyTexture = Shader.GetGlobalTexture(HDShaderIDs._SkyTexture);
float skyTextureMipCount = Shader.GetGlobalFloat(HDShaderIDs._SkyTextureMipCount);
string sLabel = m_TileSettings.enableTileAndCluster ?
(options.outputSplitLighting ? SinglePassMRTName : singlePassName)))
(options.outputSplitLighting ? SinglePassMRTName : singlePassName);
using (new ProfilingSample(cmd, sLabel, HDRenderPipeline.GetSampler(CustomSamplerId.TPRenderDeferredLighting)))
{
var camera = hdCamera.camera;

if (enableFeatureVariants)
numVariants = LightDefinitions.s_NumFeatureVariants;
int debugViewMaterial = Shader.GetGlobalInt(HDShaderIDs._DebugViewMaterial);
int debugLightingMode = Shader.GetGlobalInt(HDShaderIDs._DebugLightingMode);
Vector4 debugLightingAlbedo = Shader.GetGlobalVector(HDShaderIDs._DebugLightingAlbedo);
Vector4 debugLightingSmoothness = Shader.GetGlobalVector(HDShaderIDs._DebugLightingSmoothness);
Texture ltcData = Shader.GetGlobalTexture(HDShaderIDs._LtcData);
Texture preIntegratedFGD = Shader.GetGlobalTexture(HDShaderIDs._PreIntegratedFGD);
Texture ltcGGXMatrix = Shader.GetGlobalTexture(HDShaderIDs._LtcGGXMatrix);
Texture ltcDisneyDiffuseMatrix = Shader.GetGlobalTexture(HDShaderIDs._LtcDisneyDiffuseMatrix);
Texture ltcMultiGGXFresnelDisneyDiffuse = Shader.GetGlobalTexture(HDShaderIDs._LtcMultiGGXFresnelDisneyDiffuse);
Matrix4x4 invScrProjection = Shader.GetGlobalMatrix(HDShaderIDs.g_mInvScrProjection);
int useTileLightList = Shader.GetGlobalInt(HDShaderIDs._UseTileLightList);
Vector4 time = Shader.GetGlobalVector(HDShaderIDs._Time);
Vector4 sinTime = Shader.GetGlobalVector(HDShaderIDs._SinTime);
Vector4 cosTime = Shader.GetGlobalVector(HDShaderIDs._CosTime);
Vector4 unity_DeltaTime = Shader.GetGlobalVector(HDShaderIDs.unity_DeltaTime);
int envLightSkyEnabled = Shader.GetGlobalInt(HDShaderIDs._EnvLightSkyEnabled);
Vector4 ambientOcclusionParam = Shader.GetGlobalVector(HDShaderIDs._AmbientOcclusionParam);
int enableSSSAndTransmission = Shader.GetGlobalInt(HDShaderIDs._EnableSSSAndTransmission);
int texturingModeFlags = Shader.GetGlobalInt(HDShaderIDs._TexturingModeFlags);
int transmissionFlags = Shader.GetGlobalInt(HDShaderIDs._TransmissionFlags);
int useDisneySSS = Shader.GetGlobalInt(HDShaderIDs._UseDisneySSS);
Vector4[] thicknessRemaps = Shader.GetGlobalVectorArray(HDShaderIDs._ThicknessRemaps);
Vector4[] shapeParams = Shader.GetGlobalVectorArray(HDShaderIDs._ShapeParams);
Vector4[] transmissionTints = Shader.GetGlobalVectorArray(HDShaderIDs._TransmissionTints);
Vector4[] halfRcpVariancesAndWeights = Shader.GetGlobalVectorArray(HDShaderIDs._HalfRcpVariancesAndWeights);
Texture skyTexture = Shader.GetGlobalTexture(HDShaderIDs._SkyTexture);
float skyTextureMipCount = Shader.GetGlobalFloat(HDShaderIDs._SkyTextureMipCount);
for (int variant = 0; variant < numVariants; variant++)
{
int kernel;

if (m_enableBakeShadowMask)
{
if (debugDisplaySettings.IsDebugDisplayEnabled())
kernel = usingFptl ? s_shadeOpaqueDirectFptlDebugDisplayKernel : s_shadeOpaqueDirectClusteredDebugDisplayKernel;
kernel = usingFptl ? s_shadeOpaqueDirectShadowMaskFptlDebugDisplayKernel : s_shadeOpaqueDirectShadowMaskClusteredDebugDisplayKernel;
kernel = usingFptl ? s_shadeOpaqueDirectFptlKernel : s_shadeOpaqueDirectClusteredKernel;
kernel = usingFptl ? s_shadeOpaqueDirectShadowMaskFptlKernel : s_shadeOpaqueDirectShadowMaskClusteredKernel;
kernel = usingFptl ? s_shadeOpaqueDirectShadowMaskFptlDebugDisplayKernel : s_shadeOpaqueDirectShadowMaskClusteredDebugDisplayKernel;
kernel = usingFptl ? s_shadeOpaqueDirectFptlDebugDisplayKernel : s_shadeOpaqueDirectClusteredDebugDisplayKernel;
kernel = usingFptl ? s_shadeOpaqueDirectShadowMaskFptlKernel : s_shadeOpaqueDirectShadowMaskClusteredKernel;
kernel = usingFptl ? s_shadeOpaqueDirectFptlKernel : s_shadeOpaqueDirectClusteredKernel;
// Pass global parameters to compute shader
// TODO: get rid of this by making global parameters visible to compute shaders
PushGlobalParams(camera, cmd, deferredComputeShader, kernel);
hdCamera.SetupComputeShader(deferredComputeShader, cmd);
// TODO: Update value like in ApplyDebugDisplaySettings() call. Sadly it is high likely that this will not be keep in sync. we really need to get rid of this by making global parameters visible to compute shaders
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs._DebugViewMaterial, debugViewMaterial);
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs._DebugLightingMode, debugLightingMode);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._DebugLightingAlbedo, debugLightingAlbedo);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._DebugLightingSmoothness, debugLightingSmoothness);
cmd.SetComputeBufferParam(deferredComputeShader, kernel, HDShaderIDs.g_vLightListGlobal, bUseClusteredForDeferred ? s_PerVoxelLightLists : s_LightList);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._DeferredShadowTexture, deferredShadowTexture);
// TODO: Don't know why but If we use Shader.GetGlobalTexture(HDShaderIDs._GBufferTexture0) instead of HDShaderIDs._GBufferTexture0 the screen start to flicker in SceneView...
// Need to investigate what is happening. But this may be unnecessary as development of SetGlobalTexture for compute shader have begin
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._GBufferTexture0, HDShaderIDs._GBufferTexture0);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._GBufferTexture1, HDShaderIDs._GBufferTexture1);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._GBufferTexture2, HDShaderIDs._GBufferTexture2);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._GBufferTexture3, HDShaderIDs._GBufferTexture3);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._ShadowMaskTexture, HDShaderIDs._ShadowMaskTexture);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._VelocityTexture, HDShaderIDs._VelocityTexture);
// TODO: Should remove this setting but can't remove it else get error: Property (_AmbientOcclusionTexture) at kernel index (32) is not set. Check why
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._LtcData, ltcData);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._PreIntegratedFGD, preIntegratedFGD);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._LtcGGXMatrix, ltcGGXMatrix);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._LtcDisneyDiffuseMatrix, ltcDisneyDiffuseMatrix);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._LtcMultiGGXFresnelDisneyDiffuse, ltcMultiGGXFresnelDisneyDiffuse);
cmd.SetComputeMatrixParam(deferredComputeShader, HDShaderIDs.g_mInvScrProjection, invScrProjection);
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs._UseTileLightList, useTileLightList);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._Time, time);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._SinTime, sinTime);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._CosTime, cosTime);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs.unity_DeltaTime, unity_DeltaTime);
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs._EnvLightSkyEnabled, envLightSkyEnabled);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._AmbientOcclusionParam, ambientOcclusionParam);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._SkyTexture, skyTexture ? skyTexture : m_DefaultTexture2DArray);
cmd.SetComputeFloatParam(deferredComputeShader, HDShaderIDs._SkyTextureMipCount, skyTextureMipCount);
// Set SSS parameters.
cmd.SetComputeIntParam( deferredComputeShader, HDShaderIDs._EnableSSSAndTransmission, enableSSSAndTransmission);
cmd.SetComputeIntParam( deferredComputeShader, HDShaderIDs._TexturingModeFlags, texturingModeFlags);
cmd.SetComputeIntParam( deferredComputeShader, HDShaderIDs._TransmissionFlags, transmissionFlags);
cmd.SetComputeIntParam( deferredComputeShader, HDShaderIDs._UseDisneySSS, useDisneySSS);
cmd.SetComputeVectorArrayParam(deferredComputeShader, HDShaderIDs._ThicknessRemaps, thicknessRemaps);
cmd.SetComputeVectorArrayParam(deferredComputeShader, HDShaderIDs._ShapeParams, shapeParams);
cmd.SetComputeVectorArrayParam(deferredComputeShader, HDShaderIDs._TransmissionTints, transmissionTints);
cmd.SetComputeVectorArrayParam(deferredComputeShader, HDShaderIDs._HalfRcpVariancesAndWeights, halfRcpVariancesAndWeights);
if (options.volumetricLightingEnabled)
{
// TODO: enable keyword VOLUMETRIC_LIGHTING_ENABLED.
// TODO: do not use globals, call HDRenderPipeline.SetVolumetricLightingData() instead.
HDRenderPipeline.SetVolumetricLightingDataFromGlobals(cmd, deferredComputeShader, kernel);
}
else
{
// TODO: disable keyword VOLUMETRIC_LIGHTING_ENABLED.
// We should not access any volumetric lighting data in our shaders.
}
// TODO: Is it possible to setup this outside the loop ? Can figure out how, get this: Property (specularLightingUAV) at kernel index (21) is not set
// TODO: Check if we can remove this, when I test I can't
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._SkyTexture, skyTexture);
cmd.SetComputeFloatParam(deferredComputeShader, HDShaderIDs._SkyTextureMipCount, skyTextureMipCount);
// always do deferred lighting in blocks of 16x16 (not same as tiled light size)
if (enableFeatureVariants)

bUseClusteredForDeferred ? 1 : 0,
debugDisplaySettings.IsDebugDisplayEnabled() ? 1 : 0];
PushGlobalParams(camera, cmd, null, 0);
if (options.outputSplitLighting)
{
CoreUtils.DrawFullScreen(cmd, currentLightingMaterial, colorBuffers, depthStencilBuffer);

CoreUtils.DrawFullScreen(cmd, currentLightingMaterial, colorBuffers[0], depthStencilBuffer);
}
}
SetGlobalPropertyRedirect(null, 0, null);
PushGlobalParams(camera, cmd, null, 0);
using (new ProfilingSample(cmd, "Forward pass"))
using (new ProfilingSample(cmd, "Forward pass", HDRenderPipeline.GetSampler(CustomSamplerId.TPForwardPass)))
{
cmd.EnableShaderKeyword("LIGHTLOOP_SINGLE_PASS");
cmd.DisableShaderKeyword("LIGHTLOOP_TILE_PASS");

// Only opaques can use FPTL, transparent must use clustered!
bool useFptl = renderOpaque && usingFptl;
using (new ProfilingSample(cmd, useFptl ? "Forward Tiled pass" : "Forward Clustered pass"))
using (new ProfilingSample(cmd, useFptl ? "Forward Tiled pass" : "Forward Clustered pass", HDRenderPipeline.GetSampler(CustomSamplerId.TPForwardTiledClusterpass)))
{
// say that we want to use tile of single loop
cmd.EnableShaderKeyword("LIGHTLOOP_TILE_PASS");

public void RenderDebugOverlay(Camera camera, CommandBuffer cmd, DebugDisplaySettings debugDisplaySettings, ref float x, ref float y, float overlaySize, float width)
{
LightingDebugSettings lightingDebug = debugDisplaySettings.lightingDebugSettings;
using (new ProfilingSample(cmd, "Display Shadows"))
using (new ProfilingSample(cmd, "Display Shadows", HDRenderPipeline.GetSampler(CustomSamplerId.TPDisplayShadows)))
{
if (lightingDebug.shadowDebugMode == ShadowMapDebugMode.VisualizeShadowMap)
{

117
ScriptableRenderPipeline/HDRenderPipeline/Lighting/Volumetrics/VolumetricLighting.cs


}
}
// Since we are rendering tiles of pixels, our VBuffer can potentially extend past the boundaries of the viewport.
// Since a single voxel corresponds to a tile (e.g. 8x8) of pixels,
// the VBuffer can potentially extend past the boundaries of the viewport.
// The function returns the fraction of the {width, height} of the VBuffer visible on screen.
Vector2 ComputeVBufferResolutionAndScale(float screenWidth, float screenHeight,
ref int w, ref int h, ref int d)

m_VBufferLighting[i].volumeDepth = d;
m_VBufferLighting[i].enableRandomWrite = true;
m_VBufferLighting[i].Create();
// Returns 'true' if a global fog component exists.
public static bool SetGlobalVolumeProperties(CommandBuffer cmd, ComputeShader cs = null)
// Uses a logarithmic depth encoding.
// Near plane: depth = 0; far plane: depth = 1.
// x = n, y = log2(f/n), z = 1/n, w = 1/log2(f/n).
public static Vector4 ComputeLogarithmicDepthEncodingParams(float nearPlane, float farPlane)
{
Vector4 depthParams = new Vector4();
float n = nearPlane;
float f = farPlane;
depthParams.x = n;
depthParams.y = Mathf.Log(f / n, 2);
depthParams.z = 1.0f / depthParams.x;
depthParams.w = 1.0f / depthParams.y;
return depthParams;
}
// Returns NULL if a global fog component does not exist, or is not enabled.
public static HomogeneousFog GetGlobalFogComponent()
{
HomogeneousFog globalFogComponent = null;

}
}
// TODO: may want to cache these results somewhere.
VolumeProperties globalFogProperties = (globalFogComponent != null) ? globalFogComponent.volumeParameters.GetProperties()
: VolumeProperties.GetNeutralVolumeProperties();
if (cs)
{
cmd.SetComputeVectorParam(cs, HDShaderIDs._GlobalFog_Scattering, globalFogProperties.scattering);
cmd.SetComputeFloatParam( cs, HDShaderIDs._GlobalFog_Extinction, globalFogProperties.extinction);
}
else
{
cmd.SetGlobalVector(HDShaderIDs._GlobalFog_Scattering, globalFogProperties.scattering);
cmd.SetGlobalFloat( HDShaderIDs._GlobalFog_Extinction, globalFogProperties.extinction);
}
return (globalFogComponent != null);
return globalFogComponent;
// Uses a logarithmic depth encoding.
// Near plane: depth = 0; far plane: depth = 1.
// x = n, y = log2(f/n), z = 1/n, w = 1/log2(f/n).
public static Vector4 ComputeLogarithmicDepthEncodingParams(float nearPlane, float farPlane)
public void SetVolumetricLightingData(HDCamera camera, CommandBuffer cmd)
Vector4 depthParams = new Vector4();
HomogeneousFog globalFogComponent = GetGlobalFogComponent();
float n = nearPlane;
float f = farPlane;
// TODO: may want to cache these results somewhere.
VolumeProperties globalFogProperties = (globalFogComponent != null) ? globalFogComponent.volumeParameters.GetProperties()
: VolumeProperties.GetNeutralVolumeProperties();
depthParams.x = n;
depthParams.y = Mathf.Log(f / n, 2);
depthParams.z = 1 / depthParams.x;
depthParams.w = 1 / depthParams.y;
return depthParams;
}
public void SetVolumetricLightingData(HDCamera camera, CommandBuffer cmd, ComputeShader cs = null, int kernel = 0)
{
SetGlobalVolumeProperties(cmd, cs);
cmd.SetGlobalVector(HDShaderIDs._GlobalFog_Scattering, globalFogProperties.scattering);
cmd.SetGlobalFloat( HDShaderIDs._GlobalFog_Extinction, globalFogProperties.extinction);
int w = 0, h = 0, d = 0;
Vector2 scale = ComputeVBufferResolutionAndScale(camera.screenSize.x, camera.screenSize.y, ref w, ref h, ref d);

if (cs)
{
cmd.SetComputeVectorParam( cs, HDShaderIDs._VBufferResolutionAndScale, resAndScale);
cmd.SetComputeVectorParam( cs, HDShaderIDs._VBufferDepthEncodingParams, depthParams);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._VBufferLighting, m_VBufferLightingRT[0]);
}
else
{
cmd.SetGlobalVector( HDShaderIDs._VBufferResolutionAndScale, resAndScale);
cmd.SetGlobalVector( HDShaderIDs._VBufferDepthEncodingParams, depthParams);
cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, m_VBufferLightingRT[0]);
}
}
public static void SetVolumetricLightingDataFromGlobals(CommandBuffer cmd, ComputeShader cs, int kernel)
{
SetGlobalVolumeProperties(cmd, cs);
cmd.SetComputeVectorParam( cs, HDShaderIDs._VBufferResolutionAndScale, Shader.GetGlobalVector( HDShaderIDs._VBufferResolutionAndScale));
cmd.SetComputeVectorParam( cs, HDShaderIDs._VBufferDepthEncodingParams, Shader.GetGlobalVector( HDShaderIDs._VBufferDepthEncodingParams));
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._VBufferLighting, Shader.GetGlobalTexture(HDShaderIDs._VBufferLighting));
cmd.SetGlobalVector( HDShaderIDs._VBufferResolutionAndScale, resAndScale);
cmd.SetGlobalVector( HDShaderIDs._VBufferDepthEncodingParams, depthParams);
cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, m_VBufferLightingRT[0]);
}
void VolumetricLightingPass(HDCamera camera, CommandBuffer cmd)

using (new ProfilingSample(cmd, "Volumetric Lighting"))
{
bool hasGlobalVolume = SetGlobalVolumeProperties(cmd, m_VolumetricLightingCS);
if (!hasGlobalVolume)
if (GetGlobalFogComponent() == null)
{
// Clear the render target instead of running the shader.
CoreUtils.SetRenderTarget(cmd, m_VBufferLightingRT[0], ClearFlag.Color, CoreUtils.clearColorAllBlack);

camera.SetupComputeShader(m_VolumetricLightingCS, cmd);
bool enableClustered = m_Asset.tileSettings.enableClustered && m_Asset.tileSettings.enableTileAndCluster;
int kernel = m_VolumetricLightingCS.FindKernel(enableClustered ? "VolumetricLightingClustered"
: "VolumetricLightingAllLights");
int kernel = m_VolumetricLightingCS.FindKernel(enableClustered ? "VolumetricLightingClustered"
: "VolumetricLightingAllLights");
Vector4 resAndScale = new Vector4(w, h, scale.x, scale.y);
Vector4 depthParams = ComputeLogarithmicDepthEncodingParams(m_VBufferNearPlane, m_VBufferFarPlane);
float vFoV = camera.camera.fieldOfView * Mathf.Deg2Rad;
float vFoV = camera.camera.fieldOfView * Mathf.Deg2Rad;
// Compose the matrix which allows us to compute the world space view direction.
// Compute it using the scaled resolution to account for the visible area of the VBuffer.

// TODO: set 'm_VolumetricLightingPreset'.
cmd.SetComputeVectorParam( m_VolumetricLightingCS, HDShaderIDs._Time, Shader.GetGlobalVector(HDShaderIDs._Time));
cmd.SetComputeVectorParam( m_VolumetricLightingCS, HDShaderIDs._VBufferResolutionAndScale, resAndScale);
cmd.SetComputeVectorParam( m_VolumetricLightingCS, HDShaderIDs._VBufferDepthEncodingParams, depthParams);
cmd.SetComputeMatrixParam( m_VolumetricLightingCS, HDShaderIDs._VBufferCoordToViewDirWS, transform);
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLighting, m_VBufferLightingRT[0]);
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLightingPrev, m_VBufferLightingRT[1]);
// Pass the light data to the compute shader.
m_LightLoop.PushGlobalParams(camera.camera, cmd, m_VolumetricLightingCS, kernel, true);
cmd.SetComputeMatrixParam( m_VolumetricLightingCS, HDShaderIDs._VBufferCoordToViewDirWS, transform);
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLighting, m_VBufferLightingRT[0]);
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLightingPrev, m_VBufferLightingRT[1]);
// The shader defines GROUP_SIZE_1D = 16.
cmd.DispatchCompute(m_VolumetricLightingCS, kernel, (w + 15) / 16, (h + 15) / 16, 1);

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


HLSLINCLUDE
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
// #pragma enable_d3d11_debug_symbols
#pragma shader_feature _ALPHATEST_ON

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


HLSLINCLUDE
#pragma target 5.0
#pragma only_renderers d3d11 ps4 // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan // TEMP: until we go further in dev
// #pragma enable_d3d11_debug_symbols
#pragma shader_feature _ALPHATEST_ON

16
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl


#define SSS_WRAP_LIGHT cos(PI/2 - SSS_WRAP_ANGLE)
CBUFFER_START(UnitySSSParameters)
uint _EnableSSSAndTransmission; // Globally toggles subsurface and transmission scattering on/off
uint _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter
uint _TransmissionFlags; // 2 bit/profile; 0 = inf. thick, 1 = thin, 2 = regular
// Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system.
// Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader.
uint _EnableSSSAndTransmission; // Globally toggles subsurface and transmission scattering on/off
float _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter
float _TransmissionFlags; // 2 bit/profile; 0 = inf. thick, 1 = thin, 2 = regular
// Old SSS Model >>>
uint _UseDisneySSS;
float4 _HalfRcpVariancesAndWeights[SSS_N_PROFILES][2]; // 2x Gaussians in RGB, A is interpolation weights

bsdfData.subsurfaceRadius = subsurfaceRadius;
bsdfData.thickness = _ThicknessRemaps[subsurfaceProfile].x + _ThicknessRemaps[subsurfaceProfile].y * thickness;
uint transmissionMode = BitFieldExtract(_TransmissionFlags, 2u, 2u * subsurfaceProfile);
uint transmissionMode = BitFieldExtract(asuint(_TransmissionFlags), 2u, 2u * subsurfaceProfile);
bsdfData.enableTransmission = transmissionMode != SSS_TRSM_MODE_NONE && (_EnableSSSAndTransmission > 0);
bsdfData.enableTransmission = _EnableSSSAndTransmission != 0 && transmissionMode != SSS_TRSM_MODE_NONE;
if (_UseDisneySSS)
if (_UseDisneySSS != 0)
{
bsdfData.transmittance = ComputeTransmittanceDisney(_ShapeParams[subsurfaceProfile].rgb,
_TransmissionTints[subsurfaceProfile].rgb,

if (enableSssAndTransmission)
{
bool performPostScatterTexturing = IsBitSet(_TexturingModeFlags, bsdfData.subsurfaceProfile);
bool performPostScatterTexturing = IsBitSet(asuint(_TexturingModeFlags), bsdfData.subsurfaceProfile);
if (performPostScatterTexturing)
{

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


HLSLINCLUDE
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go futher in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go futher in dev
//#pragma enable_d3d11_debug_symbols
//-------------------------------------------------------------------------------------

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


HLSLINCLUDE
#pragma target 5.0
#pragma only_renderers d3d11 ps4// TEMP: until we go futher in dev
#pragma only_renderers d3d11 ps4 vulkan// TEMP: until we go futher in dev
// #pragma enable_d3d11_debug_symbols
//-------------------------------------------------------------------------------------

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CombineLighting.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
// #pragma enable_d3d11_debug_symbols
#pragma vertex Vert

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CopyStencilBuffer.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma multi_compile _ EXPORT_HTILE
// #pragma enable_d3d11_debug_symbols

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/PreIntegratedFGD.shader


#pragma vertex Vert
#pragma fragment Frag
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#include "../../../../Core/ShaderLibrary/Common.hlsl"
#include "../../../../Core/ShaderLibrary/ImageBasedLighting.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/SubsurfaceScattering.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
// #pragma enable_d3d11_debug_symbols
#pragma vertex Vert

12
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs


public bool useDisneySSS = true;
public SubsurfaceScatteringProfile[] profiles;
[NonSerialized] public int texturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter
[NonSerialized] public int transmissionFlags; // 2 bit/profile; 0 = inf. thick, 1 = thin, 2 = regular
[NonSerialized] public uint texturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter
[NonSerialized] public uint transmissionFlags; // 2 bit/profile; 0 = inf. thick, 1 = thin, 2 = regular
[NonSerialized] public Vector4[] thicknessRemaps; // Remap: 0 = start, 1 = end - start
[NonSerialized] public Vector4[] worldScales; // Size of the world unit in meters (only the X component is used)
[NonSerialized] public Vector4[] shapeParams; // RGB = S = 1 / D, A = filter radius

int i = p + 1;
// Erase previous value (This need to be done here individually as in the SSS editor we edit individual component)
int mask = 1 << i;
uint mask = 1u << i;
mask = 3 << i * 2;
mask = 3u << i * 2;
texturingModeFlags |= (int)profiles[p].texturingMode << i;
transmissionFlags |= (int)profiles[p].transmissionMode << i * 2;
texturingModeFlags |= (uint)profiles[p].texturingMode << i;
transmissionFlags |= (uint)profiles[p].transmissionMode << i * 2;
thicknessRemaps[i] = new Vector4(profiles[p].thicknessRemap.x, profiles[p].thicknessRemap.y - profiles[p].thicknessRemap.x, 0f, 0f);
worldScales[i] = new Vector4(profiles[p].worldScale, 0f, 0f, 0f);

3
ScriptableRenderPipeline/HDRenderPipeline/Material/RenderPipelineMaterial.cs


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

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


HLSLINCLUDE
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
//#pragma enable_d3d11_debug_symbols
//-------------------------------------------------------------------------------------

2
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawSssProfile.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma vertex Vert
#pragma fragment Frag

2
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma vertex Vert
#pragma fragment Frag

13
ScriptableRenderPipeline/HDRenderPipeline/ShaderVariables.hlsl


float4 _FrustumPlanes[6]; // {(a, b, c) = N, d = -dot(N, P)} [L, R, T, B, N, F]
CBUFFER_END
float4x4 OptimizeAffineMatrix(float4x4 M)
{
// Matrix format (x = non-constant value).
// | x x x x |
// | x x x x |
// | x x x x |
// | 0 0 0 1 |
// Notice that the last row is constant.
// We can avoid loading and doing math with constants.
M[3] = float4(0, 0, 0, 1);
return M;
}
float4x4 OptimizeProjectionMatrix(float4x4 M)
{
// Matrix format (x = non-constant value).

11
ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesFunctions.hlsl


#if defined(SHADERPASS) && (SHADERPASS != SHADERPASS_SHADOWS)
return GetPrimaryCameraPosition();
#else
// TEMP: this is rather expensive. Then again, we need '_WorldSpaceCameraPos'
// to represent the position of the primary (scene view) camera in order to
// have identical tessellation levels for both the scene view and shadow views.
// Otherwise, depth comparisons become meaningless!
float4x4 trViewMat = transpose(GetWorldToViewMatrix());
float3 rotCamPos = trViewMat[3].xyz;
return mul((float3x3)trViewMat, -rotCamPos);
// This is a generic solution.
// However, for the primary camera, using '_WorldSpaceCameraPos' is better for cache locality,
// and in case we enable camera-relative rendering, we can statically set the position is 0.
return UNITY_MATRIX_I_V._14_24_34;
#endif
}

8
ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesMatrixDefsHDCamera.hlsl


#ifndef UNITY_SHADER_VARIABLES_MATRIX_DEFS_HDCAMERA_INCLUDED
#define UNITY_SHADER_VARIABLES_MATRIX_DEFS_HDCAMERA_INCLUDED
#define UNITY_MATRIX_M OptimizeAffineMatrix(unity_ObjectToWorld)
#define UNITY_MATRIX_I_M OptimizeAffineMatrix(unity_WorldToObject)
#define UNITY_MATRIX_V OptimizeAffineMatrix(_ViewMatrix)
#define UNITY_MATRIX_I_V OptimizeAffineMatrix(_InvViewMatrix)
#define UNITY_MATRIX_M unity_ObjectToWorld
#define UNITY_MATRIX_I_M unity_WorldToObject
#define UNITY_MATRIX_V _ViewMatrix
#define UNITY_MATRIX_I_V _InvViewMatrix
#define UNITY_MATRIX_P OptimizeProjectionMatrix(_ProjMatrix)
#define UNITY_MATRIX_I_P _InvProjMatrix
#define UNITY_MATRIX_VP _ViewProjMatrix

8
ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesMatrixDefsLegacyUnity.hlsl


#ifndef UNITY_SHADER_VARIABLES_MATRIX_DEFS_LEGACY_UNITY_INCLUDED
#define UNITY_SHADER_VARIABLES_MATRIX_DEFS_LEGACY_UNITY_INCLUDED
#define UNITY_MATRIX_M OptimizeAffineMatrix(unity_ObjectToWorld)
#define UNITY_MATRIX_I_M OptimizeAffineMatrix(unity_WorldToObject)
#define UNITY_MATRIX_V OptimizeAffineMatrix(unity_MatrixV)
#define UNITY_MATRIX_I_V OptimizeAffineMatrix(unity_MatrixInvV)
#define UNITY_MATRIX_M unity_ObjectToWorld
#define UNITY_MATRIX_I_M unity_WorldToObject
#define UNITY_MATRIX_V unity_MatrixV
#define UNITY_MATRIX_I_V unity_MatrixInvV
#define UNITY_MATRIX_P OptimizeProjectionMatrix(glstate_matrix_projection)
#define UNITY_MATRIX_I_P inverse_glstate_matrix_projection_is_not_defined
#define UNITY_MATRIX_VP unity_MatrixVP

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/BlacksmithlSky/Resources/SkyBlacksmith.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma vertex Vert
#pragma fragment Frag

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/ComputeGgxIblSampleData.compute


{
// We switch to the Golden sequence instead of the Fibonacci sequence
// since the sample count is not guaranteed to be a Fibonacci number.
// TODO: might be interesting to try Mitchell's Poisson disk sampling algorithm.
// In our case, samples would not have disks associated with them, but rather solid angles.
float2 u = Golden2dSeq(i, sampleCount);
SampleGGXDir(u, V, k_identity3x3, roughness, localL, NdotL, NdotH, LdotH, true);

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/GGXConvolve.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma multi_compile _ USE_MIS

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Resources/SkyHDRI.shader


#pragma fragment Frag
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#include "../../../../Core/ShaderLibrary/Color.hlsl"
#include "../../../../Core/ShaderLibrary/Common.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/OpaqueAtmosphericScattering.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma vertex Vert
#pragma fragment Frag

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/Resources/ProceduralSky.shader


#pragma fragment Frag
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma multi_compile _ _ENABLE_SUN_DISK

6
ScriptableRenderPipeline/HDRenderPipeline/Sky/SkyManager.cs


// Sets the global MIP-mapped cubemap '_SkyTexture' in the shader.
// The texture being set is the sky (environment) map pre-convolved with GGX.
public void SetGlobalSkyTexture()
public void SetGlobalSkyTexture(CommandBuffer cmd)
Shader.SetGlobalTexture(HDShaderIDs._SkyTexture, m_SkyboxGGXCubemapRT);
cmd.SetGlobalTexture(HDShaderIDs._SkyTexture, m_SkyboxGGXCubemapRT);
Shader.SetGlobalFloat(HDShaderIDs._SkyTextureMipCount, mipCount);
cmd.SetGlobalFloat(HDShaderIDs._SkyTextureMipCount, mipCount);
}
public void Resize(float nearPlane, float farPlane)

6
ScriptableRenderPipeline/LightweightPipeline/Editor/LegacyShadersToLightweightPipelineUpgrader.cs


{
public class LegacyShadersToLightweightPipelineUpgrader
{
//[MenuItem("RenderPipeline/Lightweight Pipeline/Material Upgraders/Upgrade Legacy Materials to LightweightPipeline - Project", false, 3)]
//[MenuItem("Edit/Render Pipeline/Upgrade/Lightweight/Upgrade Legacy Materials to Lightweight Pipeline (Project)", priority = CoreUtils.editMenuPriority)]
//[MenuItem("RenderPipeline/Lightweight Pipeline/Material Upgraders/Upgrade Legacy Materials to LightweightPipeline - Selection", false, 4)]
//[MenuItem("Edit/Render Pipeline/Upgrade/Lightweight/Upgrade Legacy Materials to Lightweight Pipeline (Selection)", priority = CoreUtils.editMenuPriority)]
// MaterialUpgrader.UpgradeSelection(materialUpgraders, "Upgrade to Lightweight Materials");
//}

20
ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightPipelineUpgraders.cs


public class StandardUpgrader : MaterialUpgrader
{
public static void UpdateStandardMaterialKeywords(Material material)
{
material.SetFloat("_WorkflowMode", 1.0f);
LightweightShaderHelper.SetKeyword(material, "_OCCLUSIONMAP", material.GetTexture("_OcclusionMap"));
LightweightShaderHelper.SetKeyword(material, "_METALLICSPECGLOSSMAP", material.GetTexture("_MetallicGlossMap"));
}
public static void UpdateStandardSpecularMaterialKeywords(Material material)
{
material.SetFloat("_WorkflowMode", 0.0f);
LightweightShaderHelper.SetKeyword(material, "_OCCLUSIONMAP", material.GetTexture("_OcclusionMap"));
LightweightShaderHelper.SetKeyword(material, "_METALLICSPECGLOSSMAP", material.GetTexture("_SpecGlossMap"));
LightweightShaderHelper.SetKeyword(material, "_SPECULAR_SETUP", true);
}
RenameShader(oldShaderName, LightweightPipelineAsset.m_StandardShaderPath);
if (oldShaderName.Contains("Specular"))
RenameShader(oldShaderName, LightweightPipelineAsset.m_StandardShaderPath, UpdateStandardSpecularMaterialKeywords);
else
RenameShader(oldShaderName, LightweightPipelineAsset.m_StandardShaderPath, UpdateStandardMaterialKeywords);
}
}

8
ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardGUI.cs


public static GUIContent detailMaskText = new GUIContent("Detail Mask", "Mask for Secondary Maps (A)");
public static GUIContent detailAlbedoText = new GUIContent("Detail Albedo x2", "Albedo (RGB) multiplied by 2");
public static GUIContent detailNormalMapText = new GUIContent("Normal Map", "Normal Map");
public static GUIContent bumpScaleNotSupported = new GUIContent("Bump scale is not supported on mobile platforms");
public static GUIContent fixNow = new GUIContent("Fix now");
public static string primaryMapsText = "Main Maps";
public static string secondaryMapsText = "Secondary Maps";

void DoNormalArea()
{
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap);
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null);
if (bumpScale.floatValue != 1 && UnityEditorInternal.InternalEditorUtility.IsMobilePlatform(EditorUserBuildSettings.activeBuildTarget))
if (m_MaterialEditor.HelpBoxWithButton(Styles.bumpScaleNotSupported, Styles.fixNow))
bumpScale.floatValue = 1;
}
void DoAlbedoArea(Material material)

hasGlossMap = material.GetTexture("_MetallicGlossMap");
LightweightShaderHelper.SetKeyword(material, "_SPECULAR_SETUP", isSpecularWorkFlow);
LightweightShaderHelper.SetKeyword(material, "_METALLIC_SETUP", !isSpecularWorkFlow);
LightweightShaderHelper.SetKeyword(material, "_METALLICSPECGLOSSMAP", hasGlossMap);
LightweightShaderHelper.SetKeyword(material, "_SPECGLOSSMAP", hasGlossMap && isSpecularWorkFlow);

6
ScriptableRenderPipeline/LightweightPipeline/Editor/StandardToLightweightMaterialUpgrader.cs


using System.Collections.Generic;
using UnityEngine.Experimental.Rendering;
[MenuItem("RenderPipeline/Lightweight Pipeline/Material Upgraders/Upgrade Project Materials", false, 1)]
[MenuItem("Edit/Render Pipeline/Upgrade/Lightweight/Upgrade Standard Materials to Lightweight Pipeline (Project)", priority = CoreUtils.editMenuPriority2)]
private static void UpgradeMaterialsToLDProject()
{
List<MaterialUpgrader> upgraders = new List<MaterialUpgrader>();

}
[MenuItem("RenderPipeline/Lightweight Pipeline/Material Upgraders/Upgrade Selected Materials", false, 2)]
[MenuItem("Edit/Render Pipeline/Upgrade/Lightweight/Upgrade Standard Materials to Lightweight Pipeline (Selection)", priority = CoreUtils.editMenuPriority2)]
private static void UpgradeMaterialsToLDSelection()
{
List<MaterialUpgrader> upgraders = new List<MaterialUpgrader>();

{
upgraders.Add(new StandardUpgrader("Standard (Specular setup)"));
upgraders.Add(new StandardUpgrader("Standard"));
upgraders.Add(new TerrainUpgrader("TerrainSurface"));
}
}
}

45
ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightAssetEditor.cs


namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{
[CustomEditor(typeof(LightweightPipelineAsset))]
public class LightweightAssetInspector : Editor
public class LightweightAssetEditor : Editor
{
internal class Styles
{

public static GUIContent shadowCascadeSplit = new GUIContent("Shadow Cascade Split",
"Percentages to split shadow volume");
public static GUIContent defaultDiffuseMaterial = new GUIContent("Default Diffuse Material",
public static GUIContent defaultMaterial = new GUIContent("Default Material",
public static GUIContent defaultLineMaterial = new GUIContent("Default Line Material",
"Material to use when creating Line Renderers");
public static GUIContent defaultSpriteMaterial = new GUIContent("Default Sprite Material",
"Material to use when creating Sprites");
public static GUIContent defaultTerrainMaterial = new GUIContent("Default Terrain Material",
"Material to use in Terrains");
public static GUIContent defaultUIMaterial = new GUIContent("Default UI Material", "Material to use when creating UI Text");
public static GUIContent defaultShader = new GUIContent("Default Shader",
"Shader to use when creating materials");
public static GUIContent msaaContent = new GUIContent("Anti Aliasing (MSAA)", "Controls the global anti aliasing quality. When set to disabled, MSAA will not be performed even if the camera allows it.");
public static GUIContent attenuationTextureLabel = new GUIContent("Attenuation Texture", "Light attenuation falloff texture");
public static GUIContent msaaContent = new GUIContent("Anti Aliasing (MSAA)", "Controls the global anti aliasing applied to all cameras.");
}
private int kMaxSupportedAdditionalPixelLights = 8;

private SerializedProperty m_ShadowCascadesProp;
private SerializedProperty m_ShadowCascade2SplitProp;
private SerializedProperty m_ShadowCascade4SplitProp;
private SerializedProperty m_DefaultDiffuseMaterial;
private SerializedProperty m_DefaultMaterial;
private SerializedProperty m_DefaultLineMaterial;
private SerializedProperty m_DefaultSpriteMaterial;
private SerializedProperty m_DefaultUIMaterial;
private SerializedProperty m_DefaultShader;
private SerializedProperty m_DefaultTerrainMaterial;
private SerializedProperty m_AttenuationTexture;
void OnEnable()
{

m_ShadowCascadesProp = serializedObject.FindProperty("m_ShadowCascades");
m_ShadowCascade2SplitProp = serializedObject.FindProperty("m_Cascade2Split");
m_ShadowCascade4SplitProp = serializedObject.FindProperty("m_Cascade4Split");
m_DefaultDiffuseMaterial = serializedObject.FindProperty("m_DefaultDiffuseMaterial");
m_DefaultMaterial = serializedObject.FindProperty("m_DefaultMaterial");
m_DefaultLineMaterial = serializedObject.FindProperty("m_DefaultLineMaterial");
m_DefaultSpriteMaterial = serializedObject.FindProperty("m_DefaultSpriteMaterial");
m_DefaultUIMaterial = serializedObject.FindProperty("m_DefaultUIMaterial");
m_DefaultShader = serializedObject.FindProperty("m_DefaultShader");
m_DefaultTerrainMaterial = serializedObject.FindProperty("m_DefaultTerrainMaterial");
m_AttenuationTexture = serializedObject.FindProperty("m_AttenuationTexture");
}
public override void OnInspectorGUI()

EditorGUILayout.PropertyField(m_SupportsVertexLightProp, Styles.enableVertexLightLabel);
EditorGUILayout.PropertyField(m_SupportSoftParticlesProp, Styles.enableSoftParticles);
EditorGUILayout.PropertyField(m_MSAA, Styles.msaaContent);
EditorGUILayout.PropertyField(m_AttenuationTexture, Styles.attenuationTextureLabel);
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUILayout.Space();

EditorGUILayout.Space();
EditorGUILayout.LabelField(Styles.defaults, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_DefaultDiffuseMaterial, Styles.defaultDiffuseMaterial);
EditorGUILayout.PropertyField(m_DefaultMaterial, Styles.defaultMaterial);
EditorGUILayout.PropertyField(m_DefaultLineMaterial, Styles.defaultLineMaterial);
EditorGUILayout.PropertyField(m_DefaultSpriteMaterial, Styles.defaultSpriteMaterial);
EditorGUILayout.PropertyField(m_DefaultUIMaterial, Styles.defaultUIMaterial);
EditorGUILayout.PropertyField(m_DefaultShader, Styles.defaultShader);
EditorGUILayout.PropertyField(m_DefaultTerrainMaterial, Styles.defaultTerrainMaterial);
EditorGUI.indentLevel--;
serializedObject.ApplyModifiedProperties();

11
ScriptableRenderPipeline/LightweightPipeline/LightweightConstantBuffer.cs


public static class PerFrameBuffer
{
public static int _GlossyEnvironmentColor;
public static int _AttenuationTexture;
}
public static class PerCameraBuffer

public static int _MainLightAttenuationParams;
public static int _MainLightDistanceAttenuation;
public static int _MainLightSpotAttenuation;
public static int _MainLightCookie;
public static int _WorldToLight;
public static int _AdditionalLightAttenuationParams;
public static int _AdditionalLightDistanceAttenuation;
public static int _AdditionalLightSpotAttenuation;
}
}

456
ScriptableRenderPipeline/LightweightPipeline/LightweightPipeline.cs


public bool shadowsRendered;
}
public static class CameraRenderTargetID
{
// Camera color target. Not used when camera is rendering to backbuffer or camera
// is rendering to a texture (offscreen camera)
public static int color;
// Camera copy color texture. In case there is a single BeforeTransparent postFX
// we need use copyColor RT as a work RT.
public static int copyColor;
// Camera depth target. Only used when post processing or soft particles are enabled.
public static int depth;
// If soft particles are enabled and no depth prepass is performed we need to copy depth.
public static int depthCopy;
}
public class LightweightPipeline : RenderPipeline
{
private readonly LightweightPipelineAsset m_Asset;

// The engine fills in the lights indices per-object in unity4_LightIndices0 and unity_4LightIndices1
private static readonly int kMaxPerObjectAdditionalLights = 8;
private bool m_IsOffscreenCamera;
private Vector4[] m_LightAttenuations = new Vector4[kMaxVisibleAdditionalLights];
private Vector4[] m_LightDistanceAttenuations = new Vector4[kMaxVisibleAdditionalLights];
private Vector4[] m_LightSpotAttenuations = new Vector4[kMaxVisibleAdditionalLights];
private int m_ShadowMapTexture;
private int m_CameraColorTexture;
private int m_CameraDepthTexture;
private int m_CameraCopyDepthTexture;
private int m_ShadowMapRTID;
private RenderTargetIdentifier m_CurrCameraColorRT;
private RenderTargetIdentifier m_CameraColorRT;
private RenderTargetIdentifier m_CameraDepthRT;
private RenderTargetIdentifier m_CameraCopyDepthRT;
private RenderTargetIdentifier m_ColorRT;
private RenderTargetIdentifier m_CopyColorRT;
private RenderTargetIdentifier m_DepthRT;
private RenderTargetIdentifier m_CopyDepth;
private RenderTargetIdentifier m_Color;
private bool m_RequiredDepth = false;
private const int kShadowDepthBufferBits = 16;
private const int kCameraDepthBufferBits = 32;

private ShadowSliceData[] m_ShadowSlices = new ShadowSliceData[kMaxCascades];
private static readonly ShaderPassName m_DepthPrePass = new ShaderPassName("DepthOnly");
private static readonly ShaderPassName m_LitPassName = new ShaderPassName("LightweightForward");
private static readonly ShaderPassName m_UnlitPassName = new ShaderPassName("SRPDefaultUnlit");

BuildShadowSettings();
PerFrameBuffer._GlossyEnvironmentColor = Shader.PropertyToID("_GlossyEnvironmentColor");
PerFrameBuffer._AttenuationTexture = Shader.PropertyToID("_AttenuationTexture");
// Lights are culled per-camera. Therefore we need to reset light buffers on each camera render
PerCameraBuffer._MainLightAttenuationParams = Shader.PropertyToID("_MainLightAttenuationParams");
PerCameraBuffer._MainLightDistanceAttenuation = Shader.PropertyToID("_MainLightDistanceAttenuation");
PerCameraBuffer._MainLightSpotAttenuation = Shader.PropertyToID("_MainLightSpotAttenuation");
PerCameraBuffer._MainLightCookie = Shader.PropertyToID("_MainLightCookie");
PerCameraBuffer._WorldToLight = Shader.PropertyToID("_WorldToLight");
PerCameraBuffer._AdditionalLightAttenuationParams = Shader.PropertyToID("_AdditionalLightAttenuationParams");
PerCameraBuffer._AdditionalLightDistanceAttenuation = Shader.PropertyToID("_AdditionalLightDistanceAttenuation");
PerCameraBuffer._AdditionalLightSpotAttenuation = Shader.PropertyToID("_AdditionalLightSpotAttenuation");
m_ShadowMapTexture = Shader.PropertyToID("_ShadowMap");
m_CameraColorTexture = Shader.PropertyToID("_CameraColorTexture");
m_CameraDepthTexture = Shader.PropertyToID("_CameraDepthTexture");
m_CameraCopyDepthTexture = Shader.PropertyToID("_CameraCopyDepthTexture");
m_ShadowMapRTID = Shader.PropertyToID("_ShadowMap");
m_ShadowMapRT = new RenderTargetIdentifier(m_ShadowMapTexture);
m_CameraColorRT = new RenderTargetIdentifier(m_CameraColorTexture);
m_CameraDepthRT = new RenderTargetIdentifier(m_CameraDepthTexture);
m_CameraCopyDepthRT = new RenderTargetIdentifier(m_CameraCopyDepthTexture);
CameraRenderTargetID.color = Shader.PropertyToID("_CameraColorRT");
CameraRenderTargetID.copyColor = Shader.PropertyToID("_CameraCopyColorRT");
CameraRenderTargetID.depth = Shader.PropertyToID("_CameraDepthTexture");
CameraRenderTargetID.depthCopy = Shader.PropertyToID("_CameraCopyDepthTexture");
m_ShadowMapRT = new RenderTargetIdentifier(m_ShadowMapRTID);
m_ColorRT = new RenderTargetIdentifier(CameraRenderTargetID.color);
m_CopyColorRT = new RenderTargetIdentifier(CameraRenderTargetID.copyColor);
m_DepthRT = new RenderTargetIdentifier(CameraRenderTargetID.depth);
m_CopyDepth = new RenderTargetIdentifier(CameraRenderTargetID.depthCopy);
m_PostProcessRenderContext = new PostProcessRenderContext();
m_CopyTextureSupport = SystemInfo.copyTextureSupport;

{
base.Render(context, cameras);
bool stereoEnabled = XRSettings.isDeviceActive;
// TODO: This is at the moment required for all pipes. We should not implicitly change user project settings
// instead this should be forced when using SRP, since all SRP use linear lighting.
GraphicsSettings.lightsUseLinearIntensity = true;

Array.Sort(cameras, m_CameraComparer);
foreach (Camera camera in cameras)
{
bool sceneViewCamera = camera.cameraType == CameraType.SceneView;
bool stereoEnabled = XRSettings.isDeviceActive && !sceneViewCamera;
m_IsOffscreenCamera = m_CurrCamera.targetTexture != null && m_CurrCamera.cameraType != CameraType.SceneView;
ScriptableCullingParameters cullingParameters;
if (!CullResults.GetCullingParameters(m_CurrCamera, stereoEnabled, out cullingParameters))

#if UNITY_EDITOR
// Emit scene view UI
if (camera.cameraType == CameraType.SceneView)
if (sceneViewCamera)
ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
#endif

InitializeLightData(visibleLights, out lightData);
ShadowPass(visibleLights, ref context, ref lightData);
ForwardPass(visibleLights, ref context, ref lightData, stereoEnabled);
FrameRenderingConfiguration frameRenderingConfiguration;
SetupFrameRendering(out frameRenderingConfiguration, stereoEnabled);
SetupIntermediateResources(frameRenderingConfiguration, ref context);
// SetupCameraProperties does the following:
// Setup Camera RenderTarget and Viewport
// VR Camera Setup and SINGLE_PASS_STEREO props
// Setup camera view, proj and their inv matrices.
// Setup properties: _WorldSpaceCameraPos, _ProjectionParams, _ScreenParams, _ZBufferParams, unity_OrthoParams
// Setup camera world clip planes props
// setup HDR keyword
// Setup global time properties (_Time, _SinTime, _CosTime)
context.SetupCameraProperties(m_CurrCamera, stereoEnabled);
if (LightweightUtils.HasFlag(frameRenderingConfiguration, FrameRenderingConfiguration.DepthPass))
DepthPass(ref context);
ForwardPass(visibleLights, frameRenderingConfiguration, ref context, ref lightData, stereoEnabled);
cmd.ReleaseTemporaryRT(m_ShadowMapTexture);
cmd.ReleaseTemporaryRT(m_CameraColorTexture);
cmd.ReleaseTemporaryRT(m_CameraDepthTexture);
cmd.ReleaseTemporaryRT(m_CameraCopyDepthTexture);
cmd.ReleaseTemporaryRT(m_ShadowMapRTID);
cmd.ReleaseTemporaryRT(CameraRenderTargetID.depthCopy);
cmd.ReleaseTemporaryRT(CameraRenderTargetID.depth);
cmd.ReleaseTemporaryRT(CameraRenderTargetID.color);
cmd.ReleaseTemporaryRT(CameraRenderTargetID.copyColor);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);

}
}
private void ForwardPass(VisibleLight[] visibleLights, ref ScriptableRenderContext context, ref LightData lightData, bool stereoEnabled)
private void DepthPass(ref ScriptableRenderContext context)
FrameRenderingConfiguration frameRenderingConfiguration;
SetupFrameRendering(out frameRenderingConfiguration);
SetupIntermediateResources(frameRenderingConfiguration, ref context);
SetupShaderConstants(visibleLights, ref context, ref lightData);
CommandBuffer cmd = CommandBufferPool.Get("Depth Prepass");
cmd.SetRenderTarget(m_DepthRT);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
// SetupCameraProperties does the following:
// Setup Camera RenderTarget and Viewport
// VR Camera Setup and SINGLE_PASS_STEREO props
// Setup camera view, proj and their inv matrices.
// Setup properties: _WorldSpaceCameraPos, _ProjectionParams, _ScreenParams, _ZBufferParams, unity_OrthoParams
// Setup camera world clip planes props
// setup HDR keyword
// Setup global time properties (_Time, _SinTime, _CosTime)
context.SetupCameraProperties(m_CurrCamera, stereoEnabled);
var opaqueDrawSettings = new DrawRendererSettings(m_CurrCamera, m_DepthPrePass);
opaqueDrawSettings.sorting.flags = SortFlags.CommonOpaque;
var opaqueFilterSettings = new FilterRenderersSettings(true)
{
renderQueueRange = RenderQueueRange.opaque
};
context.DrawRenderers(m_CullResults.visibleRenderers, ref opaqueDrawSettings, opaqueFilterSettings);
}
private void ForwardPass(VisibleLight[] visibleLights, FrameRenderingConfiguration frameRenderingConfiguration, ref ScriptableRenderContext context, ref LightData lightData, bool stereoEnabled)
{
SetupShaderConstants(visibleLights, ref context, ref lightData);
RendererConfiguration rendererSettings = GetRendererSettings(ref lightData);

private void RenderOpaques(ref ScriptableRenderContext context, RendererConfiguration settings)
{
var opaqueDrawSettings = new DrawRendererSettings(m_CurrCamera, m_LitPassName);
opaqueDrawSettings.SetShaderPassName(1, m_UnlitPassName);
opaqueDrawSettings.sorting.flags = SortFlags.CommonOpaque;
opaqueDrawSettings.rendererConfiguration = settings;

private void AfterOpaque(ref ScriptableRenderContext context, FrameRenderingConfiguration config)
{
if (!LightweightUtils.HasFlag(config, FrameRenderingConfiguration.RequireDepth))
if (!m_RequiredDepth)
cmd.SetGlobalTexture(m_CameraDepthTexture, m_CameraDepthRT);
cmd.SetGlobalTexture(CameraRenderTargetID.depth, m_DepthRT);
// When soft particles are enabled we have to copy depth to another RT so we can read and write to depth
if (m_Asset.SupportsSoftParticles)
// When only one opaque effect is active we need to blit to a work RT. We blit to copy color.
// TODO: We can check if there are more than one opaque postfx and avoid an extra blit.
// TODO: There's currently an issue in the PostFX stack that has a one frame delay when an effect is enabled/disabled
// when an effect is disabled, HasOpaqueOnlyEffects returns true in the first frame, however inside render the effect
// state is update, causing RenderPostProcess here to not blit to FinalColorRT. Until the next frame the RT will have garbage.
if (LightweightUtils.HasFlag(config, FrameRenderingConfiguration.BeforeTransparentPostProcess))
RenderTargetIdentifier colorRT = (m_CurrCamera.targetTexture != null) ? BuiltinRenderTextureType.CameraTarget : m_CameraColorRT;
CopyTexture(cmd, m_CameraDepthRT, m_CameraCopyDepthTexture);
SetupRenderTargets(cmd, colorRT, m_CameraCopyDepthRT);
RenderPostProcess(cmd, m_ColorRT, m_CopyColorRT, true);
m_CurrCameraColorRT = (m_IsOffscreenCamera) ? BuiltinRenderTextureType.CameraTarget : m_ColorRT;
// Only takes effect if custom BeforeTransparent PostProcessing effects are active
if (LightweightUtils.HasFlag(config, FrameRenderingConfiguration.PostProcess))
RenderPostProcess(cmd , true);
if (LightweightUtils.HasFlag(config, FrameRenderingConfiguration.DepthCopy))
{
RenderTargetIdentifier colorRT = (m_IsOffscreenCamera) ? BuiltinRenderTextureType.CameraTarget : m_ColorRT;
CopyTexture(cmd, m_DepthRT, m_CopyDepth, m_CopyDepthMaterial);
SetupRenderTargets(cmd, colorRT, m_CopyDepth);
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);

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

}
}
private void SetupFrameRendering(out FrameRenderingConfiguration configuration)
private void SetupFrameRendering(out FrameRenderingConfiguration configuration, bool stereoEnabled)
configuration = (XRSettings.enabled) ? FrameRenderingConfiguration.Stereo : FrameRenderingConfiguration.None;
if (XRSettings.enabled && XRSettings.eyeTextureDesc.dimension == TextureDimension.Tex2DArray)
configuration = (stereoEnabled) ? FrameRenderingConfiguration.Stereo : FrameRenderingConfiguration.None;
if (stereoEnabled && XRSettings.eyeTextureDesc.dimension == TextureDimension.Tex2DArray)
m_IntermediateTextureArray = true;
else
m_IntermediateTextureArray = false;

m_ColorFormat = m_CurrCamera.allowHDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;
m_RequiredDepth = false;
m_CameraPostProcessLayer = m_CurrCamera.GetComponent<PostProcessLayer>();
m_CameraPostProcessLayer = m_CurrCamera.GetComponent<PostProcessLayer>();
bool postProcessEnabled = m_CameraPostProcessLayer != null && m_CameraPostProcessLayer.enabled;
if (postProcessEnabled || m_Asset.SupportsSoftParticles)
bool msaaEnabled = m_Asset.MSAASampleCount > 1 && (m_CurrCamera.targetTexture == null || m_CurrCamera.targetTexture.antiAliasing > 1);
// TODO: PostProcessing and SoftParticles are currently not support for VR
bool postProcessEnabled = m_CameraPostProcessLayer != null && m_CameraPostProcessLayer.enabled && !stereoEnabled;
bool softParticlesEnabled = m_Asset.SupportsSoftParticles && !stereoEnabled;
if (postProcessEnabled)
{
m_RequiredDepth = true;
intermediateTexture = true;
configuration |= FrameRenderingConfiguration.PostProcess;
if (m_CameraPostProcessLayer.HasOpaqueOnlyEffects(m_PostProcessRenderContext))
configuration |= FrameRenderingConfiguration.BeforeTransparentPostProcess;
// Resolving depth msaa requires texture2DMS. Currently if msaa is enabled we do a depth pre-pass.
if (msaaEnabled)
configuration |= FrameRenderingConfiguration.DepthPass;
}
// In case of soft particles we need depth copy. If depth copy not supported fallback to depth prepass
if (softParticlesEnabled)
configuration |= FrameRenderingConfiguration.RequireDepth;
m_RequiredDepth = true;
if (postProcessEnabled)
configuration |= FrameRenderingConfiguration.PostProcess;
bool supportsDepthCopy = m_CopyTextureSupport != CopyTextureSupport.None && m_Asset.CopyDepthShader.isSupported;
// currently fallback to depth prepass if msaa is enabled since. We need texture2DMS to support depth resolve.
configuration |= (msaaEnabled || !supportsDepthCopy) ? FrameRenderingConfiguration.DepthPass : FrameRenderingConfiguration.DepthCopy;
// When post process or soft particles are enabled we disable msaa due to lack of depth resolve
// One can still use PostFX AA
else if (m_CurrCamera.allowMSAA && m_Asset.MSAASampleCount > 1)
if (msaaEnabled)
{
configuration |= FrameRenderingConfiguration.Msaa;
intermediateTexture = !LightweightUtils.PlatformSupportsMSAABackBuffer();

{
CommandBuffer cmd = CommandBufferPool.Get("Setup Intermediate Resources");
int msaaSamples = (m_IsOffscreenCamera) ? Math.Min(m_CurrCamera.targetTexture.antiAliasing, m_Asset.MSAASampleCount) : m_Asset.MSAASampleCount;
msaaSamples = (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Msaa)) ? msaaSamples : 1;
m_CurrCameraColorRT = BuiltinRenderTextureType.CameraTarget;
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture))
{
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Stereo))
SetupIntermediateResourcesStereo(cmd, msaaSamples);
else
SetupIntermediateResourcesSingle(cmd, renderingConfig, msaaSamples);
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
private void SetupIntermediateResourcesSingle(CommandBuffer cmd, FrameRenderingConfiguration renderingConfig, int msaaSamples)
{
int msaaSamples = (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Msaa)) ? m_Asset.MSAASampleCount : 1;
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture))
if (m_RequiredDepth)
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Stereo))
{
RenderTextureDescriptor rtDesc = new RenderTextureDescriptor();
rtDesc = XRSettings.eyeTextureDesc;
rtDesc.colorFormat = m_ColorFormat;
rtDesc.msaaSamples = msaaSamples;
cmd.GetTemporaryRT(CameraRenderTargetID.depth, rtWidth, rtHeight, kCameraDepthBufferBits, FilterMode.Bilinear, RenderTextureFormat.Depth);
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.DepthCopy))
cmd.GetTemporaryRT(CameraRenderTargetID.depthCopy, rtWidth, rtHeight, kCameraDepthBufferBits, FilterMode.Bilinear, RenderTextureFormat.Depth);
}
cmd.GetTemporaryRT(m_CameraColorTexture, rtDesc, FilterMode.Bilinear);
}
else if (m_CurrCamera.targetTexture == null)
{
cmd.GetTemporaryRT(m_CameraColorTexture, rtWidth, rtHeight, kCameraDepthBufferBits,
FilterMode.Bilinear, m_ColorFormat, RenderTextureReadWrite.Default, msaaSamples);
}
// When offscreen camera current rendertarget is CameraTarget
if (!m_IsOffscreenCamera)
{
cmd.GetTemporaryRT(CameraRenderTargetID.color, rtWidth, rtHeight, kCameraDepthBufferBits,
FilterMode.Bilinear, m_ColorFormat, RenderTextureReadWrite.Default, msaaSamples);
m_CurrCameraColorRT = m_ColorRT;
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.RequireDepth))
// When postprocessing is enabled we might have a before transparent effect. In that case we need to
// use the camera render target as input. We blit to an opaque RT and then after before postprocessing is done
// we blit to the final camera RT. If no postprocessing we blit to final camera RT from beginning.
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.BeforeTransparentPostProcess))
cmd.GetTemporaryRT(m_CameraDepthTexture, rtWidth, rtHeight, kCameraDepthBufferBits, FilterMode.Bilinear, RenderTextureFormat.Depth);
if (m_Asset.SupportsSoftParticles)
cmd.GetTemporaryRT(m_CameraCopyDepthTexture, rtWidth, rtHeight, kCameraDepthBufferBits, FilterMode.Bilinear, RenderTextureFormat.Depth);
cmd.GetTemporaryRT(CameraRenderTargetID.copyColor, rtWidth, rtHeight, kCameraDepthBufferBits,
FilterMode.Bilinear, m_ColorFormat, RenderTextureReadWrite.Default, msaaSamples);
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
private void SetupIntermediateResourcesStereo(CommandBuffer cmd, int msaaSamples)
{
RenderTextureDescriptor rtDesc = new RenderTextureDescriptor();
rtDesc = XRSettings.eyeTextureDesc;
rtDesc.colorFormat = m_ColorFormat;
rtDesc.msaaSamples = msaaSamples;
cmd.GetTemporaryRT(CameraRenderTargetID.color, rtDesc, FilterMode.Bilinear);
SetupShaderLightConstants(cmd, visibleLights, ref lightData, ref m_CullResults, ref context);
SetupShaderLightConstants(cmd, visibleLights, ref lightData);
SetShaderKeywords(cmd, ref lightData, visibleLights);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);

m_SortedLightIndexMap.Clear();
lightData.shadowsRendered = false;
{
// If there's exactly one visible light that will be picked as main light.
// Otherwise we disable main light by setting its index to -1.
lightData.mainLightIndex = visibleLightsCount - 1;
lightData.pixelAdditionalLightsCount = 0;
lightData.totalAdditionalLightsCount = 0;
return;
}
lightData.mainLightIndex = GetMainLight(visibleLights);
else
lightData.mainLightIndex = SortLights(visibleLights);
// We always support at least one per-pixel light, which is main light. Shade objects up to a limit of per-object
// pixel lights defined in the pipeline settings.
int maxSupportedPixelLights = Math.Min(m_Asset.MaxAdditionalPixelLights, kMaxPerObjectAdditionalLights) + 1;
int maxPixelLights = Math.Min(maxSupportedPixelLights, visibleLightsCount);
// If we have a main light we don't shade it in the per-object light loop. We also remove it from the per-object cull list
int additionalLightsCount = (lightData.mainLightIndex > 0) ? visibleLightsCount - 1 : visibleLightsCount;
additionalLightsCount = Math.Min(additionalLightsCount, kMaxPerObjectAdditionalLights);
// If vertex lighting is enabled in the pipeline settings, then we shade the remaining visible lights per-vertex
// up to the maximum amount of per-object lights.
int vertexLights = (m_Asset.SupportsVertexLight) ? kMaxPerObjectAdditionalLights - maxPixelLights - 1: 0;
int pixelLightsCount = Math.Min(additionalLightsCount, m_Asset.MaxAdditionalPixelLights);
int vertexLightCount = (m_Asset.SupportsVertexLight) ? additionalLightsCount - pixelLightsCount : 0;
lightData.mainLightIndex = SortLights(visibleLights);
lightData.pixelAdditionalLightsCount = maxPixelLights - 1;
lightData.totalAdditionalLightsCount = lightData.pixelAdditionalLightsCount + vertexLights;
lightData.pixelAdditionalLightsCount = pixelLightsCount;
lightData.totalAdditionalLightsCount = pixelLightsCount + vertexLightCount;
}
private int SortLights(VisibleLight[] visibleLights)

// How main light is decided:
// If shadows enabled, main light is always a shadow casting light. Directional has priority over local lights.
// Otherwise directional lights have priority based on cookie support and intensity
// If no directional light in the scene local lights based on cookie support and distance to camera
// If shadows are supported and the first visible light has shadows then this is main light
if (shadowsEnabled && visibleLights[0].light.shadows != LightShadows.None)
return 0;
if (totalVisibleLights == 0)
return -1;
int brighestDirectionalIndex = -1;
for (int i = 0; i < totalVisibleLights; ++i)
{
VisibleLight currLight = visibleLights[i];
// We don't have any directional shadow casting light, skip until we find the first non directional light
int lightIndex = 0;
while (lightIndex < totalVisibleLights && visibleLights[lightIndex].lightType == LightType.Directional)
lightIndex++;
// Particle system lights have the light property as null. We sort lights so all particles lights
// come last. Therefore, if first light is particle light then all lights are particle lights.
// In this case we either have no main light or already found it.
if (currLight.light == null)
break;
// If first non-directional light has shadows we return it, otherwise we return first light
return (lightIndex < totalVisibleLights && visibleLights[lightIndex].light.shadows != LightShadows.None) ? lightIndex : 0;
if (shadowsEnabled && currLight.light.shadows != LightShadows.None && LightweightUtils.IsSupportedShadowType(currLight.lightType))
return i;
if (currLight.lightType == LightType.Directional && brighestDirectionalIndex == -1)
brighestDirectionalIndex = i;
}
return brighestDirectionalIndex;
private void InitializeLightConstants(VisibleLight[] lights, int lightIndex, out Vector4 lightPos, out Vector4 lightColor, out Vector4 lightSpotDir,
out Vector4 lightAttenuationParams)
private void InitializeLightConstants(VisibleLight[] lights, int lightIndex, out Vector4 lightPos, out Vector4 lightColor, out Vector4 lightDistanceAttenuation, out Vector4 lightSpotDir,
out Vector4 lightSpotAttenuation)
lightAttenuationParams = new Vector4(0.0f, 1.0f, 0.0f, 0.0f);
lightDistanceAttenuation = new Vector4(0.0f, 1.0f, 0.0f, 0.0f);
lightSpotAttenuation = new Vector4(0.0f, 1.0f, 0.0f, 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

lightColor = light.finalColor;
float rangeSq = light.range * light.range;
float quadAtten = 0.0f;
// Directional Light attenuation is initialize so distance attenuation always be 1.0
quadAtten = (m_Asset.AttenuationTexture != null) ? 1.0f : 25.0f / rangeSq;
{
// 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
// smoothFactor = (lightRangeSqr - distanceToLightSqr) / (lightRangeSqr - fadeStartDistanceSqr)
// We rewrite smoothFactor to be able to pre compute the constant terms below and apply the smooth factor
// with one MAD instruction
// smoothFactor = distanceSqr * (1.0 / (fadeDistanceSqr - lightRangeSqr)) + (-lightRangeSqr / (fadeDistanceSqr - lightRangeSqr)
// distanceSqr * oneOverFadeRangeSqr + lightRangeSqrOverFadeRangeSqr
float lightRangeSqr = light.range * light.range;
float fadeStartDistanceSqr = 0.8f * 0.8f * lightRangeSqr;
float fadeRangeSqr = (fadeStartDistanceSqr - lightRangeSqr);
float oneOverFadeRangeSqr = 1.0f / fadeRangeSqr;
float lightRangeSqrOverFadeRangeSqr = -lightRangeSqr / fadeRangeSqr;
float quadAtten = 25.0f / lightRangeSqr;
lightDistanceAttenuation = new Vector4(quadAtten, oneOverFadeRangeSqr, lightRangeSqrOverFadeRangeSqr, 0.0f);
}
if (light.lightType == LightType.Spot)
{

float invAngleRange = 1.0f / smoothAngleRange;
float add = -cosOuterAngle * invAngleRange;
lightAttenuationParams = new Vector4(invAngleRange, add, quadAtten, rangeSq);
}
else
{
lightSpotDir = new Vector4(0.0f, 0.0f, 1.0f, 0.0f);
lightAttenuationParams = new Vector4(0.0f, 1.0f, quadAtten, rangeSq);
lightSpotAttenuation = new Vector4(invAngleRange, add, 0.0f);
}
}

SphericalHarmonicsL2 ambientSH = RenderSettings.ambientProbe;
Vector4 glossyEnvColor = new Vector4(ambientSH[0, 0], ambientSH[1, 0], ambientSH[2, 0]) * RenderSettings.reflectionIntensity;
CommandBuffer cmd = CommandBufferPool.Get("SetupPerFrameConstants");
cmd.SetGlobalVector(PerFrameBuffer._GlossyEnvironmentColor, glossyEnvColor);
if (m_Asset.AttenuationTexture != null) cmd.SetGlobalTexture(PerFrameBuffer._AttenuationTexture, m_Asset.AttenuationTexture);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release (cmd);
Shader.SetGlobalVector(PerFrameBuffer._GlossyEnvironmentColor, glossyEnvColor);
private void SetupShaderLightConstants(CommandBuffer cmd, VisibleLight[] lights, ref LightData lightData, ref CullResults cullResults, ref ScriptableRenderContext context)
private void SetupShaderLightConstants(CommandBuffer cmd, VisibleLight[] lights, ref LightData lightData)
SetupMainLightConstants(cmd, lights, lightData.mainLightIndex, ref context);
SetupMainLightConstants(cmd, lights, lightData.mainLightIndex);
SetupShadowShaderConstants(cmd, ref context, ref lights[lightData.mainLightIndex], m_ShadowCasterCascadesCount);
SetupShadowShaderConstants(cmd, ref lights[lightData.mainLightIndex], m_ShadowCasterCascadesCount);
SetupAdditionalListConstants(cmd, lights, ref lightData, ref context);
SetupAdditionalListConstants(cmd, lights, ref lightData);
private void SetupMainLightConstants(CommandBuffer cmd, VisibleLight[] lights, int lightIndex, ref ScriptableRenderContext context)
private void SetupMainLightConstants(CommandBuffer cmd, VisibleLight[] lights, int lightIndex)
Vector4 lightPos, lightColor, lightSpotDir, lightAttenuationParams;
InitializeLightConstants(lights, lightIndex, out lightPos, out lightColor, out lightSpotDir, out lightAttenuationParams);
Vector4 lightPos, lightColor, lightDistanceAttenuation, lightSpotDir, lightSpotAttenuation;
InitializeLightConstants(lights, lightIndex, out lightPos, out lightColor, out lightDistanceAttenuation, out lightSpotDir, out lightSpotAttenuation);
cmd.SetGlobalVector(PerCameraBuffer._MainLightDistanceAttenuation, lightDistanceAttenuation);
cmd.SetGlobalVector(PerCameraBuffer._MainLightAttenuationParams, lightAttenuationParams);
cmd.SetGlobalVector(PerCameraBuffer._MainLightSpotAttenuation, lightSpotAttenuation);
if (lightIndex >= 0 && LightweightUtils.IsSupportedCookieType(lights[lightIndex].lightType) && lights[lightIndex].light.cookie != null)
{
Matrix4x4 lightCookieMatrix;
LightweightUtils.GetLightCookieMatrix(lights[lightIndex], out lightCookieMatrix);
cmd.SetGlobalTexture(PerCameraBuffer._MainLightCookie, lights[lightIndex].light.cookie);
cmd.SetGlobalMatrix(PerCameraBuffer._WorldToLight, lightCookieMatrix);
}
private void SetupAdditionalListConstants(CommandBuffer cmd, VisibleLight[] lights, ref LightData lightData, ref ScriptableRenderContext context)
private void SetupAdditionalListConstants(CommandBuffer cmd, VisibleLight[] lights, ref LightData lightData)
{
int additionalLightIndex = 0;

perObjectLightIndexMap[GetLightUnsortedIndex(i)] = additionalLightIndex;
InitializeLightConstants(lights, i, out m_LightPositions[additionalLightIndex],
out m_LightColors[additionalLightIndex],
out m_LightDistanceAttenuations[additionalLightIndex],
out m_LightAttenuations[additionalLightIndex]);
out m_LightSpotAttenuations[additionalLightIndex]);
additionalLightIndex++;
}
}

lightData.totalAdditionalLightsCount, 0.0f, 0.0f));
cmd.SetGlobalVectorArray (PerCameraBuffer._AdditionalLightPosition, m_LightPositions);
cmd.SetGlobalVectorArray (PerCameraBuffer._AdditionalLightColor, m_LightColors);
cmd.SetGlobalVectorArray (PerCameraBuffer._AdditionalLightAttenuationParams, m_LightAttenuations);
cmd.SetGlobalVectorArray (PerCameraBuffer._AdditionalLightDistanceAttenuation, m_LightDistanceAttenuations);
cmd.SetGlobalVectorArray (PerCameraBuffer._AdditionalLightSpotAttenuation, m_LightSpotAttenuations);
private void SetupShadowShaderConstants(CommandBuffer cmd, ref ScriptableRenderContext context, ref VisibleLight shadowLight, int cascadeCount)
private void SetupShadowShaderConstants(CommandBuffer cmd, ref VisibleLight shadowLight, int cascadeCount)
Vector3 shadowLightDir = Vector3.Normalize(shadowLight.localToWorld.GetColumn(2));
Light light = shadowLight.light;
float bias = light.shadowBias * 0.1f;
float normalBias = light.shadowNormalBias;

cmd.SetGlobalMatrixArray("_WorldToShadow", shadowMatrices);
cmd.SetGlobalVectorArray("_DirShadowSplitSpheres", m_DirectionalShadowSplitDistances);
cmd.SetGlobalVector("_ShadowLightDirection", new Vector4(-shadowLightDir.x, -shadowLightDir.y, -shadowLightDir.z, 0.0f));
cmd.SetGlobalVector("_ShadowData", new Vector4(0.0f, bias, normalBias, 0.0f));
cmd.SetGlobalFloatArray("_PCFKernel", pcfKernel);
}

LightweightUtils.SetKeyword(cmd, "_VERTEX_LIGHTS", vertexLightsCount > 0);
int mainLightIndex = lightData.mainLightIndex;
// Currently only directional light cookie is supported
LightweightUtils.SetKeyword(cmd, "_MAIN_LIGHT_COOKIE", mainLightIndex != -1 && LightweightUtils.IsSupportedCookieType(visibleLights[mainLightIndex].lightType) && visibleLights[mainLightIndex].light.cookie != null);
LightweightUtils.SetKeyword (cmd, "_MAIN_DIRECTIONAL_LIGHT", mainLightIndex == -1 || visibleLights[mainLightIndex].lightType == LightType.Directional);
LightweightUtils.SetKeyword (cmd, "_MAIN_SPOT_LIGHT", mainLightIndex != -1 && visibleLights[mainLightIndex].lightType == LightType.Spot);
LightweightUtils.SetKeyword (cmd, "_MAIN_POINT_LIGHT", mainLightIndex != -1 && visibleLights[mainLightIndex].lightType == LightType.Point);

var setRenderTargetCommandBuffer = CommandBufferPool.Get();
setRenderTargetCommandBuffer.name = "Render packed shadows";
setRenderTargetCommandBuffer.GetTemporaryRT(m_ShadowMapTexture, m_ShadowSettings.shadowAtlasWidth,
setRenderTargetCommandBuffer.GetTemporaryRT(m_ShadowMapRTID, m_ShadowSettings.shadowAtlasWidth,
m_ShadowSettings.shadowAtlasHeight, kShadowDepthBufferBits, FilterMode.Bilinear, RenderTextureFormat.Depth);
setRenderTargetCommandBuffer.SetRenderTarget(m_ShadowMapRT);
setRenderTargetCommandBuffer.ClearRenderTarget(true, true, Color.black);

CommandBuffer cmd = CommandBufferPool.Get("SetCameraRenderTarget");
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture))
{
if (m_CurrCamera.targetTexture == null)
colorRT = m_CameraColorRT;
if (!m_IsOffscreenCamera)
colorRT = m_CurrCameraColorRT;
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.RequireDepth))
depthRT = m_CameraDepthRT;
if (m_RequiredDepth && !LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.DepthPass))
depthRT = m_DepthRT;
}
SetupRenderTargets(cmd, colorRT, depthRT);

private void EndForwardRendering(ref ScriptableRenderContext context, FrameRenderingConfiguration renderingConfig)
{
// No additional rendering needs to be done if this is an offscren rendering camera (unless camera is scene view)
if (m_CurrCamera.targetTexture != null && m_CurrCamera.cameraType != CameraType.SceneView)
// No additional rendering needs to be done if this is an off screen rendering camera
if (m_IsOffscreenCamera)
return;
var cmd = CommandBufferPool.Get("Blit");

cmd.Blit(m_CameraColorRT, BuiltinRenderTextureType.CurrentActive);
cmd.Blit(m_CurrCameraColorRT, BuiltinRenderTextureType.CurrentActive);
}
else if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture))
{

cmd.SetRenderTarget(colorRT, 0, CubemapFace.Unknown, depthSlice);
}
private void RenderPostProcess(CommandBuffer cmd, bool opaqueOnly)
private void RenderPostProcess(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier dest, bool opaqueOnly)
m_PostProcessRenderContext.source = BuiltinRenderTextureType.CurrentActive;
m_PostProcessRenderContext.source = source;
m_PostProcessRenderContext.destination = BuiltinRenderTextureType.CameraTarget;
m_PostProcessRenderContext.destination = dest;
{
cmd.Blit(m_CopyColorRT, m_ColorRT);
}
else
m_CameraPostProcessLayer.Render(m_PostProcessRenderContext);
}

Debug.Assert(index >= 0 && index < m_SortedLightIndexMap.Count, "Invalid index while accessing light index map. If you only have a single light in scene you should not try to map indices");
return m_SortedLightIndexMap[index];
return (index < m_SortedLightIndexMap.Count) ? m_SortedLightIndexMap[index] : index;
}
private void Blit(CommandBuffer cmd, FrameRenderingConfiguration renderingConfig, RenderTargetIdentifier sourceRT, RenderTargetIdentifier destRT, Material material = null)

}
}
private void CopyTexture(CommandBuffer cmd, RenderTargetIdentifier sourceRT, RenderTargetIdentifier destRT)
private void CopyTexture(CommandBuffer cmd, RenderTargetIdentifier sourceRT, RenderTargetIdentifier destRT, Material copyMaterial)
cmd.CopyTexture(m_CameraDepthRT, m_CameraCopyDepthRT);
cmd.CopyTexture(sourceRT, destRT);
cmd.Blit(m_CameraDepthRT, m_CameraCopyDepthRT, m_CopyDepthMaterial);
cmd.Blit(sourceRT, destRT, copyMaterial);
}
}
}

12
ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset


m_ShadowCascades: 1
m_Cascade2Split: 0.25
m_Cascade4Split: {x: 0.067, y: 0.2, z: 0.467}
m_AttenuationTexture: {fileID: 2800000, guid: ee420ad43ff580149a07f10ad66c49ff,
type: 3}
m_DefaultDiffuseMaterial: {fileID: 2100000, guid: 31321ba15b8f8eb4c954353edc038b1d,
type: 2}
m_DefaultMaterial: {fileID: 2100000, guid: 31321ba15b8f8eb4c954353edc038b1d, type: 2}
m_DefaultLineMaterial: {fileID: 2100000, guid: 541b04d3bf488324f816937313973e15,
type: 2}
m_DefaultSpriteMaterial: {fileID: 2100000, guid: e3ef893926d86c448a80512fe05b8a37,
m_DefaultTerrainMaterial: {fileID: 2100000, guid: 594ea882c5a793440b60ff72d896021e,
m_DefaultUIMaterial: {fileID: 2100000, guid: 786cc499ea3906946b10ab7d24c8d0e7, type: 2}
m_BlitShader: {fileID: 4800000, guid: c17132b1f77d20942aa75f8429c0f8bc, type: 3}
m_CopyDepthShader: {fileID: 4800000, guid: d6dae50ee9e1bfa4db75f19f99355220, type: 3}

67
ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.cs


{
public static readonly string m_SimpleLightShaderPath = "LightweightPipeline/Standard (Simple Lighting)";
public static readonly string m_StandardShaderPath = "LightweightPipeline/Standard (Physically Based)";
public static readonly string m_BlitShaderPath = "Hidden/LightweightPipeline/Blit";
public static readonly string m_CopyDephPath = "Hidden/LightweightPipeline/CopyDepth";
private static readonly string m_PipelineFolder = "Assets/LightweightPipeline";
private static readonly string m_AssetName = "LightweightPipelineAsset.asset";
[SerializeField] private int m_MaxAdditionalPixelLights = 1;
[SerializeField] private bool m_SupportsVertexLight = true;
[SerializeField] private int m_MaxAdditionalPixelLights = 4;
[SerializeField] private bool m_SupportsVertexLight = false;
[SerializeField] private MSAAQuality m_MSAA = MSAAQuality.Disabled;
[SerializeField] private MSAAQuality m_MSAA = MSAAQuality._4x;
[SerializeField] private float m_RenderScale = 1.0f;
[SerializeField] private ShadowType m_ShadowType = ShadowType.HARD_SHADOWS;
[SerializeField] private ShadowResolution m_ShadowAtlasResolution = ShadowResolution._1024;

[SerializeField] private float m_Cascade2Split = 0.25f;
[SerializeField] private Vector3 m_Cascade4Split = new Vector3(0.067f, 0.2f, 0.467f);
[SerializeField] private Texture2D m_AttenuationTexture;
[SerializeField] private Material m_DefaultDiffuseMaterial;
[SerializeField] private Material m_DefaultMaterial;
[SerializeField] private Material m_DefaultLineMaterial;
[SerializeField] private Material m_DefaultSpriteMaterial;
[SerializeField] private Material m_DefaultUIMaterial;
[SerializeField] private Material m_DefaultTerrainMaterial;
// Resources
[SerializeField] private Shader m_BlitShader;
[SerializeField] private Shader m_CopyDepthShader;
[UnityEditor.MenuItem("RenderPipeline/Lightweight Pipeline/Create Pipeline Asset", false, 15)]
[UnityEditor.MenuItem("Assets/Create/Render Pipeline/Lightweight/Render Pipeline", priority = CoreUtils.assetCreateMenuPriority1)]
var instance = ScriptableObject.CreateInstance<LightweightPipelineAsset>();
var instance = CreateInstance<LightweightPipelineAsset>();
instance.m_DefaultShader = Shader.Find(m_StandardShaderPath);
instance.m_BlitShader = Shader.Find("Hidden/LightweightPipeline/Blit");
instance.m_CopyDepthShader = Shader.Find("Hidden/LightweightPipeline/CopyDepth");
string[] paths = m_PipelineFolder.Split('/');
string currentPath = paths[0];
for (int i = 1; i < paths.Length; ++i)
{
string folder = currentPath + "/" + paths[i];
if (!UnityEditor.AssetDatabase.IsValidFolder(folder))
UnityEditor.AssetDatabase.CreateFolder(currentPath, paths[i]);
string path = UnityEditor.EditorUtility.SaveFilePanelInProject("Save Lightweight Asset", "LightweightAsset", "asset",
"Please enter a file name to save the asset to");
currentPath = folder;
}
UnityEditor.AssetDatabase.CreateAsset(instance, m_PipelineFolder + "/" + m_AssetName);
if (path.Length > 0)
UnityEditor.AssetDatabase.CreateAsset(instance, path);
}
#endif

private set { m_Cascade4Split = value; }
}
public Texture2D AttenuationTexture
{
get { return m_AttenuationTexture; }
set { m_AttenuationTexture = value; }
}
return m_DefaultDiffuseMaterial;
return m_DefaultMaterial;
}
public override Material GetDefaultParticleMaterial()

public override Material GetDefaultLineMaterial()
{
return m_DefaultLineMaterial;
return null;
return m_DefaultDiffuseMaterial;
return m_DefaultTerrainMaterial;
return m_DefaultUIMaterial;
return null;
return m_DefaultDiffuseMaterial;
return null;
return m_DefaultDiffuseMaterial;
return null;
return m_DefaultSpriteMaterial;
return null;
}
public override Shader GetDefaultShader()
{

public Shader BlitShader
{
get { return Shader.Find(LightweightPipelineAsset.m_BlitShaderPath); }
get { return m_BlitShader; }
get { return Shader.Find(LightweightPipelineAsset.m_CopyDephPath); }
get { return m_CopyDepthShader; }
}
}
}

96
ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineUtils.cs


{
public Camera CurrCamera { get; set; }
// Sorts on the following priority:
// Directionals have priority over local lights
// ShadowLight type
// Has Cookie
// Intensity if Directional, Distance to camera otherwise
// Particle Lights have the Light reference set to null
// They are at the end of the priority
if (lhsLight == null) return 1;
if (rhsLight == null) return -1;
// Prioritize lights marked as important
if (lhsLight.renderMode != rhsLight.renderMode)
{
if (lhsLight.renderMode == LightRenderMode.ForcePixel) return -1;
if (rhsLight.renderMode == LightRenderMode.ForcePixel) return 1;
}
// Prioritize Directional Lights
if (lhs.lightType != rhs.lightType)
{
if (lhs.lightType == LightType.Directional) return -1;

// Particle Lights have the Light reference set to null
// They are at the end of the priority
if (lhsLight == null) return 1;
if (rhsLight == null) return -1;
// In the following priority: Soft, Hard, None
// Prioritize Shadows Lights Soft > Hard > None
// Prioritize lights with cookies
// If directional sort by intensity
return (int)(lhsLight.intensity*100.0f) - (int)(rhsLight.intensity*100.0f);
else
return (int)(SquaredDistanceToCamera(lhsLight.transform.position) - SquaredDistanceToCamera(rhsLight.transform.position));
{
return (int)(rhsLight.intensity * 100.0f) - (int)(lhsLight.intensity * 100.0f);
}
// Punctual lights are sorted per-object by the engine based on distance to object center + luminance
// Here we sort globally the light list per camera distance to fit the closest lights in the global light buffer
// Check MAX_VISIBLE_LIGHTS in the LightweightLighting.cginc to see the max global buffer list size
int lhsDistance = (int) (SquaredDistanceToCamera(lhsLight.transform.position)*100.0f);
int rhsDistance = (int) (SquaredDistanceToCamera(rhsLight.transform.position)*100.0f);
int result = lhsDistance - rhsDistance;
return result;
}
public float SquaredDistanceToCamera(Vector3 lightPos)

None = 0,
Stereo = (1 << 0),
Msaa = (1 << 1),
PostProcess = (1 << 2),
RequireDepth = (1 << 3),
DefaultViewport = (1 << 4),
IntermediateTexture = (1 << 5),
BeforeTransparentPostProcess = (1 << 2),
PostProcess = (1 << 3),
DepthPass = (1 << 4),
DepthCopy = (1 << 5),
DefaultViewport = (1 << 6),
IntermediateTexture = (1 << 7),
public static void GetLightCookieMatrix(VisibleLight light, out Matrix4x4 cookieMatrix)
{
cookieMatrix = Matrix4x4.Inverse(light.localToWorld);
if (light.lightType == LightType.Directional)
{
float scale = 1.0f/light.light.cookieSize;
// apply cookie scale and offset by 0.5 to convert from [-0.5, 0.5] to texture space [0, 1]
Vector4 row0 = cookieMatrix.GetRow(0);
Vector4 row1 = cookieMatrix.GetRow(1);
cookieMatrix.SetRow(0, new Vector4(row0.x*scale, row0.y*scale, row0.z*scale, row0.w*scale + 0.5f));
cookieMatrix.SetRow(1, new Vector4(row1.x*scale, row1.y*scale, row1.z*scale, row1.w*scale + 0.5f));
}
else if (light.lightType == LightType.Spot)
{
// we want out.w = 2.0 * in.z / m_CotanHalfSpotAngle
// c = cotHalfSpotAngle
// 1 0 0 0
// 0 1 0 0
// 0 0 1 0
// 0 0 2/c 0
// the "2" will be used to scale .xy for the cookie as in .xy/2 + 0.5
float scale = 1.0f / light.range;
float halfSpotAngleRad = Mathf.Deg2Rad * light.spotAngle * 0.5f;
float cs = Mathf.Cos(halfSpotAngleRad);
float ss = Mathf.Sin(halfSpotAngleRad);
float cotHalfSpotAngle = cs / ss;
Matrix4x4 scaleMatrix = Matrix4x4.identity;
scaleMatrix.m00 = scaleMatrix.m11 = scaleMatrix.m22 = scale;
scaleMatrix.m33 = 0.0f;
scaleMatrix.m32 = scale * (2.0f / cotHalfSpotAngle);
cookieMatrix = scaleMatrix * cookieMatrix;
}
// Remaining light types don't support cookies
}
public static void SetKeyword(CommandBuffer cmd, string keyword, bool enable)
{
if (enable)

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

24
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultParticle.mat


m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lightweight-DefaultParticle
m_Shader: {fileID: 202, guid: 0000000000000000f000000000000000, type: 0}
m_Shader: {fileID: 4800000, guid: b7839dad95683814aa64166edc107ae2, type: 3}
m_LightmapFlags: 4
m_LightmapFlags: 0
disabledShaderPasses: []
disabledShaderPasses:
- ALWAYS
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BlendOp: 0
- _CameraFadingEnabled: 0
- _CameraFarFadeDistance: 2
- _CameraNearFadeDistance: 1
- _Cull: 2
- _DistortionBlend: 0.5
- _DistortionEnabled: 0
- _DistortionStrength: 1
- _DistortionStrengthScaled: 0
- _EmissionEnabled: 0
- _FlipbookMode: 0
- _LightingEnabled: 1
- _SoftParticlesEnabled: 0
- _SoftParticlesFarFadeDistance: 1
- _SoftParticlesNearFadeDistance: 0
- _CameraFadeParams: {r: 0, g: Infinity, b: 0, a: 0}
- _SoftParticleFadeParams: {r: 0, g: 0, b: 0, a: 0}

4
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-Default.mat


m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lightweight-StandardShader
m_Name: Lightweight-Default
m_ShaderKeywords: _METALLIC_SETUP
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

212
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightCore.cginc


#include "UnityCG.cginc"
#define MAX_VISIBLE_LIGHTS 16
#define OUTPUT_COLOR(color) return half4(LIGHTWEIGHT_LINEAR_TO_GAMMA(color.rgb), color.a)
#endif
#ifdef _SPECULAR_SETUP
#define SAMPLE_METALLICSPECULAR(uv) tex2D(_SpecGlossMap, uv)
#else
#define SAMPLE_METALLICSPECULAR(uv) tex2D(_MetallicGlossMap, uv)
#define OUTPUT_COLOR(color) color
CBUFFER_START(_PerObject)
half4 unity_LightIndicesOffsetAndCount;
half4 unity_4LightIndices0;
half4 unity_4LightIndices1;
half _Shininess;
CBUFFER_END
CBUFFER_START(_PerCamera)
float4 _MainLightPosition;
half4 _MainLightColor;
float4 _MainLightAttenuationParams;
half4 _MainLightSpotDir;
half4 _AdditionalLightCount;
float4 _AdditionalLightPosition[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightColor[MAX_VISIBLE_LIGHTS];
float4 _AdditionalLightAttenuationParams[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightSpotDir[MAX_VISIBLE_LIGHTS];
CBUFFER_END
CBUFFER_START(_PerFrame)
half4 _GlossyEnvironmentColor;
sampler2D _AttenuationTexture;
CBUFFER_END
half3 TangentToWorldNormal(half3 normalTangent, half3 tangent, half3 binormal, half3 normal)
half _Pow4(half x)
half3x3 tangentToWorld = half3x3(tangent, binormal, normal);
return normalize(mul(normalTangent, tangentToWorld));
return x * x * x * x;
float ComputeFogFactor(float z)
half _LerpOneTo(half b, half t)
float clipZ_01 = UNITY_Z_0_FAR_FROM_CLIPSPACE(z);
#if defined(FOG_LINEAR)
// factor = (end-z)/(end-start) = z * (-1/(end-start)) + (end/(end-start))
float fogFactor = saturate(clipZ_01 * unity_FogParams.z + unity_FogParams.w);
return half(fogFactor);
#elif defined(FOG_EXP)
// factor = exp(-density*z)
float unityFogFactor = unity_FogParams.y * clipZ_01;
return half(saturate(exp2(-unityFogFactor)));
#elif defined(FOG_EXP2)
// factor = exp(-(density*z)^2)
float unityFogFactor = unity_FogParams.x * clipZ_01;
return half(saturate(exp2(-unityFogFactor*unityFogFactor)));
#else
return 0.0h;
#endif
half oneMinusT = 1 - t;
return oneMinusT + b * t;
void ApplyFog(inout half3 color, half fogFactor)
half3 SafeNormalize(half3 inVec)
#if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
color = lerp(unity_FogColor, color, fogFactor);
#endif
half dp3 = max(1.e-4h, dot(inVec, inVec));
return inVec * rsqrt(dp3);
half4 OutputColor(half3 color, half alpha)
half3 UnpackNormalScale(half4 packednormal, half bumpScale)
#if defined(_ALPHABLEND_ON) || defined(_ALPHAPREMULTIPLY_ON)
return half4(LIGHTWEIGHT_LINEAR_TO_GAMMA(color), alpha);
#if defined(UNITY_NO_DXT5nm)
half3 normal = packednormal.xyz * 2 - 1;
#if (SHADER_TARGET >= 30)
// SM2.0: instruction count limitation
// SM2.0: normal scaler is not supported
normal.xy *= bumpScale;
#endif
return normal;
return half4(LIGHTWEIGHT_LINEAR_TO_GAMMA(color), 1);
// This do the trick
packednormal.x *= packednormal.w;
half3 normal;
normal.xy = (packednormal.xy * 2 - 1);
#if (SHADER_TARGET >= 30)
// SM2.0: instruction count limitation
// SM2.0: normal scaler is not supported
normal.xy *= bumpScale;
#endif
normal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy)));
return normal;
inline half Alpha(half albedoAlpha)
half3 EvaluateSHPerVertex(half3 normalWS)
#if defined(_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A)
half alpha = _Color.a;
#else
half alpha = albedoAlpha * _Color.a;
#endif
#if defined(_ALPHATEST_ON)
clip(alpha - _Cutoff);
#if defined(EVALUATE_SH_VERTEX)
return max(half3(0, 0, 0), ShadeSH9(half4(normalWS, 1.0)));
#elif defined(EVALUATE_SH_MIXED)
// no max since this is only L2 contribution
return SHEvalLinearL2(half4(normalWS, 1.0));
return alpha;
// Fully per-pixel. Nothing to compute.
return half3(0.0, 0.0, 0.0);
half3 Normal(float2 uv)
half3 EvaluateSHPerPixel(half3 normalWS)
#if _NORMALMAP
return UnpackNormal(tex2D(_BumpMap, uv));
#else
return half3(0.0h, 0.0h, 1.0h);
#endif
return max(half3(0, 0, 0), ShadeSH9(half4(normalWS, 1.0)));
inline void SpecularGloss(half2 uv, half alpha, out half4 specularGloss)
half3 EvaluateSHPerPixel(half3 normalWS, half3 L2Term)
specularGloss = half4(0, 0, 0, 1);
#ifdef _SPECGLOSSMAP
specularGloss = tex2D(_SpecGlossMap, uv);
specularGloss.rgb = LIGHTWEIGHT_GAMMA_TO_LINEAR(specularGloss.rgb);
#elif defined(_SPECULAR_COLOR)
specularGloss = _SpecColor;
#ifdef EVALUATE_SH_MIXED
return = max(half3(0, 0, 0), L2Term + SHEvalLinearL0L1(half4(normalWS, 1.0)));
#ifdef _GLOSSINESS_FROM_BASE_ALPHA
specularGloss.a = alpha;
#endif
// Default: Evaluate SH fully per-pixel
return max(half3(0, 0, 0), ShadeSH9(half4(normalWS, 1.0)));
half4 MetallicSpecGloss(float2 uv, half albedoAlpha)
half3 SampleLightmap(float2 lightmapUV, half3 normalWS)
half4 specGloss;
half4 encodedBakedColor = UNITY_SAMPLE_TEX2D(unity_Lightmap, lightmapUV);
half3 bakedColor = DecodeLightmap(encodedBakedColor);
#ifdef _METALLICSPECGLOSSMAP
specGloss = specGloss = SAMPLE_METALLICSPECULAR(uv);
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
specGloss.a = albedoAlpha * _GlossMapScale;
#else
specGloss.a *= _GlossMapScale;
#if DIRLIGHTMAP_COMBINED
half4 bakedDirection = UNITY_SAMPLE_TEX2D_SAMPLER(unity_LightmapInd, unity_Lightmap, lightmapUV);
bakedColor = DecodeDirectionalLightmap(bakedColor, bakedDirection, normalWS);
#else // _METALLICSPECGLOSSMAP
#if _METALLIC_SETUP
specGloss.rgb = _Metallic.rrr;
#else
specGloss.rgb = _SpecColor.rgb;
#endif
return bakedColor;
}
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
specGloss.a = albedoAlpha * _GlossMapScale;
#else
specGloss.a = _Glossiness;
#endif
#endif
void OutputTangentToWorld(half4 vertexTangent, half3 vertexNormal, out half3 tangentWS, out half3 binormalWS, out half3 normalWS)
{
half sign = vertexTangent.w * unity_WorldTransformParams.w;
normalWS = normalize(UnityObjectToWorldNormal(vertexNormal));
tangentWS = normalize(mul((half3x3)unity_ObjectToWorld, vertexTangent.xyz));
binormalWS = cross(normalWS, tangentWS) * sign;
}
return specGloss;
half3 TangentToWorldNormal(half3 normalTangent, half3 tangent, half3 binormal, half3 normal)
{
half3x3 tangentToWorld = half3x3(tangent, binormal, normal);
return normalize(mul(normalTangent, tangentToWorld));
half OcclusionLW(float2 uv)
float ComputeFogFactor(float z)
#ifdef _OCCLUSIONMAP
#if (SHADER_TARGET < 30)
// SM20: instruction count limitation
// SM20: simpler occlusion
return tex2D(_OcclusionMap, uv).g;
#else
half occ = tex2D(_OcclusionMap, uv).g;
return LerpOneTo(occ, _OcclusionStrength);
#endif
float clipZ_01 = UNITY_Z_0_FAR_FROM_CLIPSPACE(z);
#if defined(FOG_LINEAR)
// factor = (end-z)/(end-start) = z * (-1/(end-start)) + (end/(end-start))
float fogFactor = saturate(clipZ_01 * unity_FogParams.z + unity_FogParams.w);
return half(fogFactor);
#elif defined(FOG_EXP)
// factor = exp(-density*z)
float unityFogFactor = unity_FogParams.y * clipZ_01;
return half(saturate(exp2(-unityFogFactor)));
#elif defined(FOG_EXP2)
// factor = exp(-(density*z)^2)
float unityFogFactor = unity_FogParams.x * clipZ_01;
return half(saturate(exp2(-unityFogFactor*unityFogFactor)));
return 1.0;
return 0.0h;
half3 EmissionLW(float2 uv)
void ApplyFog(inout half3 color, half fogFactor)
#ifndef _EMISSION
return 0;
#else
return LIGHTWEIGHT_GAMMA_TO_LINEAR(tex2D(_EmissionMap, uv).rgb) * _EmissionColor.rgb;
#if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
color = lerp(unity_FogColor, color, fogFactor);
#endif

375
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightLighting.cginc


#define PI 3.14159265359f
#define kDieletricSpec half4(0.04, 0.04, 0.04, 1.0 - 0.04) // standard dielectric reflectivity coef at incident angle (= 4%)
#define MAX_VISIBLE_LIGHTS 16
#ifndef UNITY_SPECCUBE_LOD_STEPS
#define UNITY_SPECCUBE_LOD_STEPS 6
#endif
#ifdef NO_ADDITIONAL_LIGHTS
#undef _ADDITIONAL_LIGHTS
#endif
// If lightmap is not defined than we evaluate GI (ambient + probes) from SH
// We might do it fully or partially in vertex to save shader ALU
#if !defined(LIGHTMAP_ON)
#if SHADER_TARGET < 30
// Evaluates SH fully in vertex
#define EVALUATE_SH_VERTEX
#else
// Evaluates L2 SH in vertex and L0L1 in pixel
#define EVALUATE_SH_MIXED
#endif
#endif
light.atten = _MainLightAttenuationParams; \
light.spotDir = _MainLightSpotDir;
light.distanceAttenuation = _MainLightDistanceAttenuation; \
light.spotDirection = _MainLightSpotDir; \
light.spotAttenuation = _MainLightSpotAttenuation
// Indexing might have a performance hit for old mobile hardware
#define INITIALIZE_LIGHT(light, i) \

light.pos = _AdditionalLightPosition[lightIndex]; \
light.color = _AdditionalLightColor[lightIndex]; \
light.atten = _AdditionalLightAttenuationParams[lightIndex]; \
light.spotDir = _AdditionalLightSpotDir[lightIndex]
light.distanceAttenuation = _AdditionalLightDistanceAttenuation[lightIndex]; \
light.spotDirection = _AdditionalLightSpotDir[lightIndex]; \
light.spotAttenuation = _AdditionalLightSpotAttenuation[lightIndex]
struct LightInput
{
float4 pos;
half4 color;
float4 atten;
half4 spotDir;
};
CBUFFER_START(_PerObject)
half4 unity_LightIndicesOffsetAndCount;
half4 unity_4LightIndices0;
half4 unity_4LightIndices1;
CBUFFER_END
CBUFFER_START(_PerCamera)
sampler2D _MainLightCookie;
float4 _MainLightPosition;
half4 _MainLightColor;
half4 _MainLightDistanceAttenuation;
half4 _MainLightSpotDir;
half4 _MainLightSpotAttenuation;
float4x4 _WorldToLight;
half4 _AdditionalLightCount;
float4 _AdditionalLightPosition[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightColor[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightDistanceAttenuation[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightSpotDir[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightSpotAttenuation[MAX_VISIBLE_LIGHTS];
CBUFFER_END
CBUFFER_START(_PerFrame)
half4 _GlossyEnvironmentColor;
CBUFFER_END
// Must match Lightweigth ShaderGraph master node
struct SurfaceData
{
half3 albedo;

half alpha;
};
struct SurfaceInput
struct LightInput
float4 lightmapUV;
half3 normalWS;
half3 tangentWS;
half3 bitangentWS;
float3 positionWS;
half3 viewDirectionWS;
half fogFactor;
float4 pos;
half4 color;
half4 distanceAttenuation;
half4 spotDirection;
half4 spotAttenuation;
};
struct BRDFData

half grazingTerm;
};
inline void InitializeSurfaceData(out SurfaceData outSurfaceData)
{
outSurfaceData.albedo = half3(1.0h, 1.0h, 1.0h);
outSurfaceData.specular = half3(0.0h, 0.0h, 0.0h);
outSurfaceData.metallic = 1.0h;
outSurfaceData.smoothness = 0.5h;
outSurfaceData.normal = half3(0.0h, 0.0h, 1.0h);
outSurfaceData.occlusion = 1.0h;
outSurfaceData.emission = half3(0.0h, 0.0h, 0.0h);
outSurfaceData.alpha = 1.0h;
}
half SpecularReflectivity(half3 specular)
half ReflectivitySpecular(half3 specular)
// SM2.0: simplified SpecularStrength
return specular.r; // Red channel - because most metals are either monocrhome or with redish/yellowish tint
#else
return max(max(specular.r, specular.g), specular.b);

inline void InitializeBRDFData(half3 albedo, half metallic, half3 specular, half smoothness, half alpha, out BRDFData outBRDFData)
half OneMinusReflectivityMetallic(half metallic)
// BRDF SETUP
#ifdef _METALLIC_SETUP
// We'll need oneMinusReflectivity, so
// 1-reflectivity = 1-lerp(dielectricSpec, 1, metallic) = lerp(1-dielectricSpec, 0, metallic)
// store (1-dielectricSpec) in kDieletricSpec.a, then

half oneMinusReflectivity = oneMinusDielectricSpec - metallic * oneMinusDielectricSpec;
return oneMinusDielectricSpec - metallic * oneMinusDielectricSpec;
}
inline void InitializeBRDFData(half3 albedo, half metallic, half3 specular, half smoothness, half alpha, out BRDFData outBRDFData)
{
#ifdef _SPECULAR_SETUP
half reflectivity = ReflectivitySpecular(specular);
half oneMinusReflectivity = 1.0 - reflectivity;
outBRDFData.diffuse = albedo * (half3(1.0h, 1.0h, 1.0h) - specular);
outBRDFData.specular = specular;
#else
half oneMinusReflectivity = OneMinusReflectivityMetallic(metallic);
#else
half reflectivity = SpecularReflectivity(specular);
outBRDFData.diffuse = albedo * (half3(1.0h, 1.0h, 1.0h) - specular);
outBRDFData.specular = specular;
#endif
outBRDFData.grazingTerm = saturate(smoothness + reflectivity);

#ifdef _ALPHAPREMULTIPLY_ON
outBRDFData.diffuse *= alpha;
alpha = reflectivity + alpha * (1.0 - reflectivity);
alpha = alpha * oneMinusReflectivity + reflectivity;
#endif
}
half3 GlossyEnvironment(half3 reflectVector, half perceptualRoughness)
{
#if !defined(_GLOSSYREFLECTIONS_OFF)
half roughness = perceptualRoughness * (1.7 - 0.7 * perceptualRoughness);
half mip = roughness * UNITY_SPECCUBE_LOD_STEPS;
half4 rgbm = UNITY_SAMPLE_TEXCUBE_LOD(unity_SpecCube0, reflectVector, mip);
return DecodeHDR(rgbm, unity_SpecCube0_HDR);
return _GlossyEnvironmentColor;
}
half3 LightweightEnvironmentBRDF(BRDFData brdfData, half3 indirectDiffuse, half3 indirectSpecular, half roughness2, half fresnelTerm)
{
half3 c = indirectDiffuse * brdfData.diffuse;
float surfaceReduction = 1.0 / (roughness2 + 1.0);
c += surfaceReduction * indirectSpecular * lerp(brdfData.specular, brdfData.grazingTerm, fresnelTerm);
return c;
}
// Based on Minimalist CookTorrance BRDF

half3 LightweightBDRF(BRDFData brdfData, half roughness2, half3 normal, half3 lightDirection, half3 viewDir)
{
#ifndef _SPECULARHIGHLIGHTS_OFF
half3 halfDir = Unity_SafeNormalize(lightDirection + viewDir);
half3 halfDir = SafeNormalize(lightDirection + viewDir);
half NoH = saturate(dot(normal, halfDir));
half LoH = saturate(dot(lightDirection, halfDir));

#endif
}
half3 LightweightBRDFIndirect(BRDFData brdfData, UnityIndirect indirect, half roughness2, half fresnelTerm)
half3 LightingLambert(half3 lightColor, half3 lightDir, half3 normal)
half3 c = indirect.diffuse * brdfData.diffuse;
float surfaceReduction = 1.0 / (roughness2 + 1.0);
c += surfaceReduction * indirect.specular * lerp(brdfData.specular, brdfData.grazingTerm, fresnelTerm);
return c;
half NdotL = saturate(dot(normal, lightDir));
return lightColor * NdotL;
UnityIndirect LightweightGI(float4 lightmapUV, half3 normalWorld, half3 reflectVec, half occlusion, half perceptualRoughness)
half3 LightingSpecular(half3 lightColor, half3 lightDir, half3 normal, half3 viewDir, half4 specularGloss, half shininess)
UnityIndirect o = (UnityIndirect)0;
half3 halfVec = SafeNormalize(lightDir + viewDir);
half NdotH = saturate(dot(normal, halfVec));
half3 specularReflection = specularGloss.rgb * pow(NdotH, shininess) * specularGloss.a;
return lightColor * specularReflection;
}
#ifdef LIGHTMAP_ON
o.diffuse += (DecodeLightmap(UNITY_SAMPLE_TEX2D(unity_Lightmap, lightmapUV.xy))) * occlusion;
#else
o.diffuse = ShadeSH9(half4(normalWorld, 1.0)) * occlusion;
half CookieAttenuation(float3 worldPos)
{
#ifdef _MAIN_LIGHT_COOKIE
#ifdef _MAIN_DIRECTIONAL_LIGHT
float2 cookieUV = mul(_WorldToLight, float4(worldPos, 1.0)).xy;
return tex2D(_MainLightCookie, cookieUV).a;
#elif defined(_MAIN_SPOT_LIGHT)
float4 projPos = mul(_WorldToLight, float4(worldPos, 1.0));
float2 cookieUV = projPos.xy / projPos.w + 0.5;
return tex2D(_MainLightCookie, cookieUV).a;
#endif // POINT LIGHT cookie not supported
#ifndef _GLOSSYREFLECTIONS_OFF
Unity_GlossyEnvironmentData g;
g.roughness = perceptualRoughness;
g.reflUVW = reflectVec;
o.specular = Unity_GlossyEnvironment(UNITY_PASS_TEXCUBE(unity_SpecCube0), unity_SpecCube0_HDR, g) * occlusion;
#else
o.specular = _GlossyEnvironmentColor * occlusion;
#endif
return 1;
}
// Matches Unity Vanila attenuation
half DistanceAttenuation(half3 distanceSqr, half4 distanceAttenuation)
{
// We use a shared distance attenuation for additional directional and puctual lights
// for directional lights attenuation will be 1
half quadFalloff = distanceAttenuation.x;
half denom = distanceSqr * quadFalloff + 1.0;
half lightAtten = 1.0 / denom;
return o;
// 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)
// smoothFactor = (lightRangeSqr - distanceSqr) / (lightRangeSqr - fadeDistance)
// We can rewrite that to fit a MAD by doing
// distanceSqr * (1.0 / (fadeDistanceSqr - lightRangeSqr)) + (-lightRangeSqr / (fadeDistanceSqr - lightRangeSqr)
// distanceSqr * distanceAttenuation.y + distanceAttenuation.z
half smoothFactor = saturate(distanceSqr * distanceAttenuation.y + distanceAttenuation.z);
return lightAtten * smoothFactor;
half SpotAttenuation(half3 spotDirection, half3 lightDirection, float4 attenuationParams)
half SpotAttenuation(half3 spotDirection, half3 lightDirection, half4 spotAttenuation)
{
// Spot Attenuation with a linear falloff can be defined as
// (SdotL - cosOuterAngle) / (cosInnerAngle - cosOuterAngle)

// SdotL * spotAttenuation.x + spotAttenuation.y
// attenuationParams.x = invAngleRange
// attenuationParams.y = (-cosOuterAngle invAngleRange)
return saturate(SdotL * attenuationParams.x + attenuationParams.y);
return saturate(SdotL * spotAttenuation.x + spotAttenuation.y);
// In per-vertex falloff there's no smooth falloff to light range. A hard cut will be noticed
inline half ComputeVertexLightAttenuation(LightInput lightInput, half3 normal, float3 worldPos, out half3 lightDirection)
// Attenuation smoothly decreases to light range.
inline half ComputeLightAttenuation(LightInput lightInput, half3 normal, float3 worldPos, out half3 lightDirection)
float4 attenuationParams = lightInput.atten;
float3 posToLightVec = lightInput.pos - worldPos * lightInput.pos.w;
float distanceSqr = max(dot(posToLightVec, posToLightVec), 0.001);
// normalized light dir
lightDirection = half3(posToLightVec * rsqrt(distanceSqr));
// attenuationParams.z = kQuadFallOff = (25.0) / (lightRange * lightRange)
// attenuationParams.w = lightRange * lightRange
half lightAtten = half(1.0 / (1.0 + distanceSqr * attenuationParams.z));
lightAtten *= SpotAttenuation(lightInput.spotDir.xyz, lightDirection, attenuationParams);
return lightAtten;
}
// In per-pixel falloff attenuation smoothly decreases to light range.
inline half ComputePixelLightAttenuation(LightInput lightInput, half3 normal, float3 worldPos, out half3 lightDirection)
{
float4 attenuationParams = lightInput.atten;
float u = (distanceSqr * attenuationParams.z) / attenuationParams.w;
half lightAtten = tex2D(_AttenuationTexture, float2(u, 0.0)).a;
lightAtten *= SpotAttenuation(lightInput.spotDir.xyz, lightDirection, attenuationParams);
half lightAtten = DistanceAttenuation(distanceSqr, lightInput.distanceAttenuation);
lightAtten *= SpotAttenuation(lightInput.spotDirection.xyz, lightDirection, lightInput.spotAttenuation);
inline half ComputeMainLightAttenuation(LightInput lightInput, half3 normal, float3 worldPos, out half3 lightDirection)
inline half ComputeMainLightAttenuation(LightInput lightInput, half3 normalWS, float3 positionWS, out half3 lightDirection)
return 1.0;
half attenuation = 1.0;
return ComputePixelLightAttenuation(lightInput, normal, worldPos, lightDirection);
half attenuation = ComputeLightAttenuation(lightInput, normalWS, positionWS, lightDirection);
// Cookies and shadows are only computed for main light
attenuation *= CookieAttenuation(positionWS);
attenuation *= LIGHTWEIGHT_SHADOW_ATTENUATION(positionWS, normalWS, lightDirection);
return attenuation;
inline half3 LightingLambert(half3 diffuseColor, half3 lightDir, half3 normal, half atten)
half3 VertexLighting(float3 positionWS, half3 normalWS)
half NdotL = saturate(dot(normal, lightDir));
return diffuseColor * (NdotL * atten);
}
half3 vertexLightColor = half3(0.0, 0.0, 0.0);
#if defined(_VERTEX_LIGHTS)
int vertexLightStart = _AdditionalLightCount.x;
int vertexLightEnd = min(_AdditionalLightCount.y, unity_LightIndicesOffsetAndCount.y);
for (int lightIter = vertexLightStart; lightIter < vertexLightEnd; ++lightIter)
{
LightInput light;
INITIALIZE_LIGHT(light, lightIter);
inline half3 LightingBlinnPhong(half3 diffuseColor, half4 specularGloss, half3 lightDir, half3 normal, half3 viewDir, half atten)
{
half NdotL = saturate(dot(normal, lightDir));
half3 diffuse = diffuseColor * NdotL;
half3 lightDirection;
half atten = ComputeLightAttenuation(light, normalWS, positionWS, lightDirection);
half3 lightColor = light.color * atten;
vertexLightColor += LightingLambert(lightColor, lightDirection, normalWS);
}
#endif
half3 halfVec = normalize(lightDir + viewDir);
half NdotH = saturate(dot(normal, halfVec));
half3 specular = specularGloss.rgb * pow(NdotH, _Shininess * 128.0) * specularGloss.a;
return (diffuse + specular) * atten;
return vertexLightColor;
half4 LightweightFragmentPBR(half4 lightmapUV, float3 positionWS, half3 normalWS, half3 tangentWS, half3 bitangentWS,
half3 viewDirectionWS, half fogFactor, half3 albedo, half metallic, half3 specular, half smoothness,
half3 normalTS, half ambientOcclusion, half3 emission, half alpha)
half4 LightweightFragmentPBR(float3 positionWS, half3 normalWS, half3 viewDirectionWS, half3 indirectDiffuse, half3 vertexLighting, half3 albedo, half metallic, half3 specular, half smoothness, half occlusion, half3 emission, half alpha)
half3 vertexNormal = normalWS;
#if _NORMALMAP
normalWS = TangentToWorldNormal(normalTS, tangentWS, bitangentWS, normalWS);
#else
normalWS = normalize(normalWS);
#endif
UnityIndirect indirectLight = LightweightGI(lightmapUV, normalWS, reflectVec, ambientOcclusion, brdfData.perceptualRoughness);
indirectDiffuse *= occlusion;
half3 indirectSpecular = GlossyEnvironment(reflectVec, brdfData.perceptualRoughness) * occlusion;
half fresnelTerm = Pow4(1.0 - saturate(dot(normalWS, viewDirectionWS)));
half3 color = LightweightBRDFIndirect(brdfData, indirectLight, roughness2, fresnelTerm);
half fresnelTerm = _Pow4(1.0 - saturate(dot(normalWS, viewDirectionWS)));
half3 color = LightweightEnvironmentBRDF(brdfData, indirectDiffuse, indirectSpecular, roughness2, fresnelTerm);
lightAtten *= LIGHTWEIGHT_SHADOW_ATTENUATION(positionWS, normalize(vertexNormal), _ShadowLightDirection.xyz);
color += vertexLighting * brdfData.diffuse;
#ifdef _ADDITIONAL_LIGHTS
int pixelLightCount = min(_AdditionalLightCount.x, unity_LightIndicesOffsetAndCount.y);

INITIALIZE_LIGHT(light, lightIter);
half lightAtten = ComputePixelLightAttenuation(light, normalWS, positionWS, lightDirectionWS);
half lightAtten = ComputeLightAttenuation(light, normalWS, positionWS, lightDirectionWS);
half NdotL = saturate(dot(normalWS, lightDirectionWS));
half3 radiance = light.color * (lightAtten * NdotL);

color += emission;
return half4(color, alpha);
}
half4 LightweightFragmentLambert(float3 positionWS, half3 normalWS, half3 viewDirectionWS, half fogFactor, half3 diffuseGI, half3 diffuse, half3 emission, half alpha)
{
half3 lightDirection;
half3 diffuseColor = diffuseGI;
LightInput mainLight;
INITIALIZE_MAIN_LIGHT(mainLight);
half lightAtten = ComputeMainLightAttenuation(mainLight, normalWS, positionWS, lightDirection);
half3 lightColor = mainLight.color * lightAtten;
diffuseColor += LightingLambert(lightColor, lightDirection, normalWS);
#ifdef _ADDITIONAL_LIGHTS
int pixelLightCount = min(_AdditionalLightCount.x, unity_LightIndicesOffsetAndCount.y);
for (int lightIter = 0; lightIter < pixelLightCount; ++lightIter)
{
LightInput lightData;
INITIALIZE_LIGHT(lightData, lightIter);
lightAtten = ComputeLightAttenuation(lightData, normalWS, positionWS, lightDirection);
lightColor = lightData.color * lightAtten;
diffuseColor += LightingLambert(lightColor, lightDirection, normalWS);
}
#endif // _ADDITIONAL_LIGHTS
// Computes fog factor per-vertex
ApplyFog(color, fogFactor);
return OutputColor(color, alpha);
half3 finalColor = diffuseColor * diffuse + emission;
// Computes Fog Factor per vextex
ApplyFog(finalColor, fogFactor);
half4 color = half4(finalColor, alpha);
return OUTPUT_COLOR(color);
}
half4 LightweightFragmentBlinnPhong(float3 positionWS, half3 normalWS, half3 viewDirectionWS, half fogFactor, half3 diffuseGI, half3 diffuse, half4 specularGloss, half shininess, half3 emission, half alpha)
{
half3 lightDirection;
half3 diffuseColor = diffuseGI;
half3 specularColor;
LightInput mainLight;
INITIALIZE_MAIN_LIGHT(mainLight);
half lightAtten = ComputeMainLightAttenuation(mainLight, normalWS, positionWS, lightDirection);
half3 lightColor = mainLight.color * lightAtten;
diffuseColor += LightingLambert(lightColor, lightDirection, normalWS);
specularColor = LightingSpecular(lightColor, lightDirection, normalWS, viewDirectionWS, specularGloss, shininess);
#ifdef _ADDITIONAL_LIGHTS
int pixelLightCount = min(_AdditionalLightCount.x, unity_LightIndicesOffsetAndCount.y);
for (int lightIter = 0; lightIter < pixelLightCount; ++lightIter)
{
LightInput lightData;
INITIALIZE_LIGHT(lightData, lightIter);
lightAtten = ComputeLightAttenuation(lightData, normalWS, positionWS, lightDirection);
lightColor = lightData.color * lightAtten;
diffuseColor += LightingLambert(lightColor, lightDirection, normalWS);
specularColor += LightingSpecular(lightColor, lightDirection, normalWS, viewDirectionWS, specularGloss, shininess);
}
#endif // _ADDITIONAL_LIGHTS
half3 finalColor = diffuseColor * diffuse + emission;
finalColor += specularColor;
// Computes Fog Factor per vextex
ApplyFog(finalColor, fogFactor);
half4 color = half4(finalColor, alpha);
return OUTPUT_COLOR(color);
}
#endif

303
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPassLit.cginc


#include "LightweightLighting.cginc"
#ifdef _SPECULAR_SETUP
#define SAMPLE_METALLICSPECULAR(uv) tex2D(_SpecGlossMap, uv)
#else
#define SAMPLE_METALLICSPECULAR(uv) tex2D(_MetallicGlossMap, uv)
#endif
half4 _Color;
sampler2D _MainTex; half4 _MainTex_ST;
half _Cutoff;
half _Glossiness;
half _GlossMapScale;
half _SmoothnessTextureChannel;
half _Metallic;
sampler2D _MetallicGlossMap;
half4 _SpecColor;
sampler2D _SpecGlossMap;
half _BumpScale;
sampler2D _BumpMap;
half _OcclusionStrength;
sampler2D _OcclusionMap;
half4 _EmissionColor;
sampler2D _EmissionMap;
half _Shininess;
struct LightweightVertexInput
{
float4 vertex : POSITION;

struct LightweightVertexOutput
{
float2 uv : TEXCOORD0;
float4 ambientOrLightmapUV : TEXCOORD1; // xy: lightmapUV, zw: dynamicLightmapUV OR color from SH
float4 posWS : TEXCOORD2;
float4 uv01 : TEXCOORD0; // xy: main UV, zw: lightmap UV (directional / non-directional)
float3 posWS : TEXCOORD1;
half3 tangent : TEXCOORD3;
half3 binormal : TEXCOORD4;
half3 normal : TEXCOORD5;
half3 tangent : TEXCOORD2;
half3 binormal : TEXCOORD3;
half3 normal : TEXCOORD4;
half3 normal : TEXCOORD3;
half3 normal : TEXCOORD2;
half4 viewDir : TEXCOORD6; // xyz: viewDir
half4 fogFactorAndVertexLight : TEXCOORD7; // x: fogFactor, yzw: vertex light
half3 viewDir : TEXCOORD5;
half4 fogFactorAndVertexLight : TEXCOORD6; // x: fogFactor, yzw: vertex light
#if defined(EVALUATE_SH_VERTEX) || defined(EVALUATE_SH_MIXED)
half4 vertexSH : TEXCOORD7;
#endif
inline void InitializeStandardLitSurfaceData(LightweightVertexOutput IN, out SurfaceData outSurfaceData)
inline half Alpha(half albedoAlpha)
float2 uv = IN.uv;
half4 albedoAlpha = tex2D(_MainTex, uv);
#if defined(_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A)
half alpha = _Color.a;
#else
half alpha = albedoAlpha * _Color.a;
#endif
half4 specGloss = MetallicSpecGloss(uv, albedoAlpha);
outSurfaceData.albedo = LIGHTWEIGHT_GAMMA_TO_LINEAR(albedoAlpha.rgb) * _Color.rgb;
#if defined(_ALPHATEST_ON)
clip(alpha - _Cutoff);
#endif
#if _METALLIC_SETUP
outSurfaceData.metallic = specGloss.r;
outSurfaceData.specular = half3(0.0h, 0.0h, 0.0h);
return alpha;
}
half3 Normal(float2 uv)
{
#if _NORMALMAP
return UnpackNormalScale(tex2D(_BumpMap, uv), _BumpScale);
outSurfaceData.metallic = 1.0h;
outSurfaceData.specular = specGloss.rgb;
return half3(0.0h, 0.0h, 1.0h);
}
outSurfaceData.smoothness = specGloss.a;
outSurfaceData.normal = Normal(uv);
outSurfaceData.occlusion = OcclusionLW(uv);
outSurfaceData.emission = EmissionLW(uv);
outSurfaceData.emission += IN.fogFactorAndVertexLight.yzw;
outSurfaceData.alpha = Alpha(albedoAlpha.a);
half SpecularGloss(half2 uv, half alpha)
{
half4 specularGloss = half4(0, 0, 0, 1);
#ifdef _SPECGLOSSMAP
specularGloss = tex2D(_SpecGlossMap, uv);
specularGloss.rgb = LIGHTWEIGHT_GAMMA_TO_LINEAR(specularGloss.rgb);
#elif defined(_SPECULAR_COLOR)
specularGloss = _SpecColor;
#endif
#ifdef _GLOSSINESS_FROM_BASE_ALPHA
specularGloss.a = alpha;
#endif
return specularGloss;
void InitializeSurfaceInput(LightweightVertexOutput IN, out SurfaceInput outSurfaceInput)
half4 MetallicSpecGloss(float2 uv, half albedoAlpha)
#if LIGHTMAP_ON
outSurfaceInput.lightmapUV = float4(IN.ambientOrLightmapUV.xy, 0.0, 0.0);
half4 specGloss;
#ifdef _METALLICSPECGLOSSMAP
specGloss = specGloss = SAMPLE_METALLICSPECULAR(uv);
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
specGloss.a = albedoAlpha * _GlossMapScale;
#else
specGloss.a *= _GlossMapScale;
#endif
#else // _METALLICSPECGLOSSMAP
#if _SPECULAR_SETUP
specGloss.rgb = _SpecColor.rgb;
outSurfaceInput.lightmapUV = float4(0.0, 0.0, 0.0, 0.0);
specGloss.rgb = _Metallic.rrr;
#if _NORMALMAP
outSurfaceInput.tangentWS = IN.tangent;
outSurfaceInput.bitangentWS = IN.binormal;
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
specGloss.a = albedoAlpha * _GlossMapScale;
#else
specGloss.a = _Glossiness;
#endif
#endif
return specGloss;
}
half Occlusion(float2 uv)
{
#ifdef _OCCLUSIONMAP
#if (SHADER_TARGET < 30)
// SM20: instruction count limitation
// SM20: simpler occlusion
return tex2D(_OcclusionMap, uv).g;
#else
half occ = tex2D(_OcclusionMap, uv).g;
return _LerpOneTo(occ, _OcclusionStrength);
#endif
#else
return 1.0;
#endif
}
half3 Emission(float2 uv)
{
#ifndef _EMISSION
return 0;
#else
return LIGHTWEIGHT_GAMMA_TO_LINEAR(tex2D(_EmissionMap, uv).rgb) * _EmissionColor.rgb;
#endif
}
inline void InitializeStandardLitSurfaceData(LightweightVertexOutput IN, out SurfaceData outSurfaceData)
{
float2 uv = IN.uv01.xy;
half4 albedoAlpha = tex2D(_MainTex, uv);
half4 specGloss = MetallicSpecGloss(uv, albedoAlpha);
outSurfaceData.albedo = LIGHTWEIGHT_GAMMA_TO_LINEAR(albedoAlpha.rgb) * _Color.rgb;
#if _SPECULAR_SETUP
outSurfaceData.metallic = 1.0h;
outSurfaceData.specular = specGloss.rgb;
outSurfaceInput.tangentWS = half3(1.0h, 0.0h, 0.0h);
outSurfaceInput.bitangentWS = half3(0.0h, 1.0h, 0.0h);
outSurfaceData.metallic = specGloss.r;
outSurfaceData.specular = half3(0.0h, 0.0h, 0.0h);
outSurfaceInput.normalWS = IN.normal;
outSurfaceInput.positionWS = IN.posWS;
outSurfaceInput.viewDirectionWS = IN.viewDir;
outSurfaceInput.fogFactor = IN.fogFactorAndVertexLight.x;
outSurfaceData.smoothness = specGloss.a;
outSurfaceData.normal = Normal(uv);
outSurfaceData.occlusion = Occlusion(uv);
outSurfaceData.emission = Emission(uv);
outSurfaceData.alpha = Alpha(albedoAlpha.a);
}
LightweightVertexOutput LitPassVertex(LightweightVertexInput v)

UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
o.uv01.xy = TRANSFORM_TEX(v.texcoord, _MainTex);
#ifdef LIGHTMAP_ON
o.uv01.zw = v.lightmapUV * unity_LightmapST.xy + unity_LightmapST.zw;
#endif
float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
o.posWS.xyz = worldPos;
half3 viewDir = normalize(_WorldSpaceCameraPos - worldPos);
o.viewDir.xyz = viewDir;
half3 normal = normalize(UnityObjectToWorldNormal(v.normal));
float3 positionWS = mul(unity_ObjectToWorld, v.vertex).xyz;
half3 viewDirectionWS = SafeNormalize(_WorldSpaceCameraPos - positionWS);
half sign = v.tangent.w * unity_WorldTransformParams.w;
o.tangent = normalize(mul((half3x3)unity_ObjectToWorld, v.tangent.xyz));
o.binormal = cross(normal, o.tangent) * sign;
o.normal = normal;
OutputTangentToWorld(v.tangent, v.normal, o.tangent, o.binormal, o.normal);
o.normal = normal;
o.normal = UnityObjectToWorldNormal(v.normal);
#ifdef LIGHTMAP_ON
o.ambientOrLightmapUV.xy = v.lightmapUV * unity_LightmapST.xy + unity_LightmapST.zw;
// TODO: Dynamic Lightmap
o.ambientOrLightmapUV.zw = float2(0.0, 0.0);
// TODO: Currently there's no way to pass in ambient contribution to fragmentPBR.
// We should allow to create custom ambient computation for things like SH evaluation, lightmap, ambient color etc.
//#else
// o.ambientOrLightmapUV = half4(SHEvalLinearL2(half4(normal, 1.0)), 0.0h);
#endif
o.fogFactorAndVertexLight.yzw = half3(0.0h, 0.0h, 0.0h);
#if defined(_VERTEX_LIGHTS)
half3 diffuse = half3(1.0, 1.0, 1.0);
int vertexLightStart = _AdditionalLightCount.x;
int vertexLightEnd = min(_AdditionalLightCount.y, unity_LightIndicesOffsetAndCount.y);
for (int lightIter = vertexLightStart; lightIter < vertexLightEnd; ++lightIter)
{
LightInput lightData;
INITIALIZE_LIGHT(lightData, lightIter);
float4 clipPos = UnityObjectToClipPos(v.vertex);
half3 lightDirection;
half atten = ComputeVertexLightAttenuation(lightData, normal, worldPos, lightDirection);
o.fogFactorAndVertexLight.yzw += LightingLambert(diffuse, lightDirection, normal, atten) * lightData.color;
}
#if defined(EVALUATE_SH_VERTEX) || defined(EVALUATE_SH_MIXED)
o.vertexSH = half4(EvaluateSHPerVertex(o.normal), 0.0);
float4 clipPos = UnityObjectToClipPos(v.vertex);
o.posWS = positionWS;
o.viewDir = viewDirectionWS;
o.fogFactorAndVertexLight.yzw = VertexLighting(positionWS, o.normal);
return o;
}

InitializeStandardLitSurfaceData(IN, surfaceData);
SurfaceInput surfaceInput;
InitializeSurfaceInput(IN, surfaceInput);
#if _NORMALMAP
half3 normalWS = TangentToWorldNormal(surfaceData.normal, IN.tangent, IN.binormal, IN.normal);
#else
half3 normalWS = normalize(IN.normal);
#endif
#if LIGHTMAP_ON
half3 indirectDiffuse = SampleLightmap(IN.uv01.zw, normalWS);
#else
half3 indirectDiffuse = EvaluateSHPerPixel(normalWS, IN.vertexSH);
#endif
float fogFactor = IN.fogFactorAndVertexLight.x;
half4 color = LightweightFragmentPBR(IN.posWS, normalWS, IN.viewDir, indirectDiffuse, IN.fogFactorAndVertexLight.yzw, surfaceData.albedo, surfaceData.metallic, surfaceData.specular, surfaceData.smoothness, surfaceData.occlusion, surfaceData.emission, surfaceData.alpha);
return LightweightFragmentPBR(surfaceInput.lightmapUV, surfaceInput.positionWS, surfaceInput.normalWS, surfaceInput.tangentWS, surfaceInput.bitangentWS, surfaceInput.viewDirectionWS, surfaceInput.fogFactor, surfaceData.albedo, surfaceData.metallic, surfaceData.specular, surfaceData.smoothness, surfaceData.normal, surfaceData.occlusion, surfaceData.emission, surfaceData.alpha);
// Computes fog factor per-vertex
ApplyFog(color.rgb, fogFactor);
return OUTPUT_COLOR(color);
float2 uv = IN.uv;
float2 uv = IN.uv01.xy;
float2 lightmapUV = IN.uv01.zw;
half4 diffuseAlpha = tex2D(_MainTex, uv);
half3 diffuse = LIGHTWEIGHT_GAMMA_TO_LINEAR(diffuseAlpha.rgb) * _Color.rgb;

half alpha = diffuseAlpha.a * _Color.a;
#endif
// Keep for compatibility reasons. Shader Inpector throws a warning when using cutoff
// due overdraw performance impact.
#ifdef _ALPHATEST_ON
clip(alpha - _Cutoff);
#endif

half3 normalWorld = TangentToWorldNormal(normalTangent, IN.tangent, IN.binormal, IN.normal);
half3 normalWS = TangentToWorldNormal(normalTangent, IN.tangent, IN.binormal, IN.normal);
half3 normalWorld = normalize(IN.normal);
half3 normalWS = normalize(IN.normal);
half4 specularGloss;
SpecularGloss(uv, alpha, specularGloss);
half3 emission = Emission(uv);
half3 viewDir = IN.viewDir.xyz;
float3 worldPos = IN.posWS.xyz;
half3 lightDirection;
half3 viewDirectionWS = SafeNormalize(IN.viewDir.xyz);
float3 positionWS = IN.posWS.xyz;
half3 color = DecodeLightmap(UNITY_SAMPLE_TEX2D(unity_Lightmap, IN.ambientOrLightmapUV.xy)) * diffuse;
half3 diffuseGI = SampleLightmap(lightmapUV, normalWS);
half3 color = (ShadeSH9(half4(normalWorld, 1.0)) + IN.ambientOrLightmapUV.xyz) * diffuse;
half3 diffuseGI = EvaluateSHPerPixel(normalWS, IN.vertexSH);
LightInput lightInput;
INITIALIZE_MAIN_LIGHT(lightInput);
half lightAtten = ComputeMainLightAttenuation(lightInput, normalWorld, worldPos, lightDirection);
lightAtten *= LIGHTWEIGHT_SHADOW_ATTENUATION(worldPos, normalize(IN.normal), _ShadowLightDirection.xyz);
#if defined(_SPECGLOSSMAP) || defined(_SPECULAR_COLOR)
color += LightingBlinnPhong(diffuse, specularGloss, lightDirection, normalWorld, viewDir, lightAtten) * lightInput.color;
#else
color += LightingLambert(diffuse, lightDirection, normalWorld, lightAtten) * lightInput.color;
#if _VERTEX_LIGHTS
diffuseGI += IN.fogFactorAndVertexLight.yzw;
#ifdef _ADDITIONAL_LIGHTS
int pixelLightCount = min(_AdditionalLightCount.x, unity_LightIndicesOffsetAndCount.y);
for (int lightIter = 0; lightIter < pixelLightCount; ++lightIter)
{
LightInput lightData;
INITIALIZE_LIGHT(lightData, lightIter);
half lightAtten = ComputePixelLightAttenuation(lightData, normalWorld, worldPos, lightDirection);
half shininess = _Shininess * 128.0h;
half fogFactor = IN.fogFactorAndVertexLight.x;
color += LightingBlinnPhong(diffuse, specularGloss, lightDirection, normalWorld, viewDir, lightAtten) * lightData.color;
half4 specularGloss = SpecularGloss(uv, alpha);
return LightweightFragmentBlinnPhong(positionWS, normalWS, viewDirectionWS, fogFactor, diffuseGI, diffuse, specularGloss, shininess, emission, alpha);
color += LightingLambert(diffuse, lightDirection, normalWorld, lightAtten) * lightData.color;
return LightweightFragmentLambert(positionWS, normalWS, viewDirectionWS, fogFactor, diffuseGI, diffuse, emission, alpha);
}
#endif // _ADDITIONAL_LIGHTS
color += EmissionLW(uv);
color += IN.fogFactorAndVertexLight.yzw;
// Computes Fog Factor per vextex
ApplyFog(color, IN.fogFactorAndVertexLight.x);
return OutputColor(color, alpha);
};
#endif

1
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightShadows.cginc


float4x4 _WorldToShadow[MAX_SHADOW_CASCADES];
float4 _DirShadowSplitSpheres[MAX_SHADOW_CASCADES];
half4 _ShadowData;
half4 _ShadowLightDirection;
inline half ShadowAttenuation(float3 shadowCoord)
{

13
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightStandard.shader


#pragma target 3.0
// -------------------------------------
#pragma shader_feature _METALLIC_SETUP _SPECULAR_SETUP
#pragma shader_feature _OCCLUSIONMAP
#pragma shader_feature _OCCLUSIONMAP
#pragma shader_feature _SPECULAR_SETUP
#pragma multi_compile _ _MAIN_LIGHT_COOKIE
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ _HARD_SHADOWS _SOFT_SHADOWS _HARD_SHADOWS_CASCADES _SOFT_SHADOWS_CASCADES
#pragma multi_compile _ _VERTEX_LIGHTS

#pragma vertex LitPassVertex
#pragma fragment LitPassFragment
#include "UnityStandardInput.cginc"
#include "LightweightPassLit.cginc"
ENDCG
}

Tags{"Lightmode" = "ShadowCaster"}
Tags{"LightMode" = "ShadowCaster"}
ZWrite On ZTest LEqual

Pass
{
Tags{"Lightmode" = "DepthOnly"}
Tags{"LightMode" = "DepthOnly"}
ColorMask 0
CGPROGRAM
#pragma target 2.0

48
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightStandardSimpleLighting.shader


#pragma shader_feature _NORMALMAP
#pragma shader_feature _EMISSION
#pragma multi_compile _ _MAIN_LIGHT_COOKIE
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ _HARD_SHADOWS _SOFT_SHADOWS _HARD_SHADOWS_CASCADES _SOFT_SHADOWS_CASCADES
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile_fog

#pragma fragment LitPassFragmentSimple
#include "UnityStandardInput.cginc"
#include "LightweightPassLit.cginc"
ENDCG
}

Tags{"Lightmode" = "DepthOnly"}
ZWrite On
ColorMask 0
CGPROGRAM
#pragma target 2.0

CGPROGRAM
#define UNITY_SETUP_BRDF_INPUT SpecularSetup
#pragma vertex vert_meta
#pragma fragment frag_meta_ld
#pragma vertex LightweightVertexMeta
#pragma fragment LightweightFragmentMeta
#pragma shader_feature _EMISSION
#pragma shader_feature _SPECGLOSSMAP

#include "UnityStandardMeta.cginc"
#include "LightweightCore.cginc"
#include "LightweightPassLit.cginc"
#include "UnityMetaPass.cginc"
fixed4 frag_meta_ld(v2f_meta i) : SV_Target
struct MetaVertexInput
{
float4 vertex : POSITION;
half3 normal : NORMAL;
float2 uv0 : TEXCOORD0;
float2 uv1 : TEXCOORD1;
float2 uv2 : TEXCOORD2;
#ifdef _TANGENT_TO_WORLD
half4 tangent : TANGENT;
#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct MetaVertexOuput
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
MetaVertexOuput LightweightVertexMeta(MetaVertexInput v)
{
MetaVertexOuput o;
o.pos = UnityMetaVertexPosition(v.vertex, v.uv1.xy, v.uv2.xy, unity_LightmapST, unity_DynamicLightmapST);
o.uv = TRANSFORM_TEX(v.uv0, _MainTex);
return o;
}
fixed4 LightweightFragmentMeta(MetaVertexOuput i) : SV_Target
o.Albedo = Albedo(i.uv);
half4 specularColor;
SpecularGloss(i.uv.xy, 1.0, specularColor);
o.SpecularColor = specularColor;
o.Albedo = _Color.rgb * tex2D(_MainTex, i.uv).rgb;
o.SpecularColor = SpecularGloss(i.uv.xy, 1.0);
#ifdef _EMISSION
o.Emission += LIGHTWEIGHT_GAMMA_TO_LINEAR(tex2D(_EmissionMap, i.uv).rgb) * _EmissionColor;

4
TestbedPipelines/BasicRenderPipeline/BasicRenderPipeline.cs


public bool UseIntermediateRenderTargetBlit;
#if UNITY_EDITOR
[UnityEditor.MenuItem("RenderPipeline/Create BasicRenderPipeline")]
[UnityEditor.MenuItem("Assets/Create/Render Pipeline/Basic/Render Pipeline", priority = CoreUtils.assetCreateMenuPriority1)]
static void CreateBasicRenderPipeline()
{
var instance = ScriptableObject.CreateInstance<BasicRenderPipeline>();

CommandBufferPool.Release(blitIntermediateRTCmd);
}
// Main entry point for our scriptable render loop
public static void Render(ScriptableRenderContext context, IEnumerable<Camera> cameras, bool useIntermediateBlitPath)

2
TestbedPipelines/Fptl/FPTLRenderPipeline.asset


type: 3}
buildPerVoxelLightListShader: {fileID: 7200000, guid: 4c2d6eb0553e2514bba3ea9a85d8c53c,
type: 3}
enableClustered: 0
enableClustered: 1
disableFptlWhenClustered: 0
enableBigTilePrepass: 1
enableDrawLightBoundsDebug: 0

41
TestbedPipelines/Fptl/FptlLighting.cs


public class FptlLighting : RenderPipelineAsset
{
#if UNITY_EDITOR
[UnityEditor.MenuItem("RenderPipeline/Create FPTLRenderPipeline")]
[UnityEditor.MenuItem("Assets/Create/Render Pipeline/FPTL/Render Pipeline", priority = CoreUtils.assetCreateMenuPriority1)]
static void CreateRenderLoopFPTL()
{
var instance = ScriptableObject.CreateInstance<FptlLighting>();

private static ComputeBuffer s_AABBBoundsBuffer;
private static ComputeBuffer s_LightList;
private static ComputeBuffer s_DirLightList;
private static ComputeBuffer s_LightIndices;
private static ComputeBuffer s_BigTileLightList; // used for pre-pass coarse culling on 64x64 tiles
private static int s_GenListPerBigTileKernel;

s_AABBBoundsBuffer.Release();
s_ConvexBoundsBuffer.Release();
s_LightDataBuffer.Release();
s_LightIndices.Release();
ReleaseResolutionDependentBuffers();
s_DirLightList.Release();

if (s_LightDataBuffer != null)
s_LightDataBuffer.Release();
if (s_LightIndices != null)
s_LightIndices.Release();
ReleaseResolutionDependentBuffers();
if (s_DirLightList != null)

s_ConvexBoundsBuffer = new ComputeBuffer(MaxNumLights, System.Runtime.InteropServices.Marshal.SizeOf(typeof(SFiniteLightBound)));
s_LightDataBuffer = new ComputeBuffer(MaxNumLights, System.Runtime.InteropServices.Marshal.SizeOf(typeof(SFiniteLightData)));
s_DirLightList = new ComputeBuffer(MaxNumDirLights, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DirectionalLight)));
s_LightIndices = null; // only used in traditional forward, will be created on demand
buildScreenAABBShader.SetBuffer(s_GenAABBKernel, "g_data", s_ConvexBoundsBuffer);
//m_BuildScreenAABBShader.SetBuffer(kGenAABBKernel, "g_vBoundsBuffer", m_aabbBoundsBuffer);

{
sorting = { flags = SortFlags.CommonOpaque },
//@TODO: need to get light probes + LPPV too?
rendererConfiguration = RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe
rendererConfiguration = RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe | RendererConfiguration.ProvideLightIndices | RendererConfiguration.ProvideReflectionProbeIndices
};
var filterSettings = new FilterRenderersSettings(true){renderQueueRange = RenderQueueRange.opaque};
loop.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);

bool haveTiledSolution = opaquesOnly || enableClustered;
cmd.EnableShaderKeyword(haveTiledSolution ? "TILED_FORWARD" : "REGULAR_FORWARD");
cmd.SetViewProjectionMatrices(camera.worldToCameraMatrix, camera.projectionMatrix);
cmd.SetGlobalBuffer("g_vLightListMeshInst", s_LightIndices);
loop.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);

var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("ForwardSinglePass"))
{
sorting = { flags = SortFlags.CommonOpaque },
rendererConfiguration = RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe
sorting = { flags = opaquesOnly ? SortFlags.CommonOpaque : SortFlags.CommonTransparent },
rendererConfiguration = RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe | RendererConfiguration.ProvideLightIndices | RendererConfiguration.ProvideReflectionProbeIndices
};
var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = opaquesOnly ? RenderQueueRange.opaque : RenderQueueRange.transparent };

var boundData = new SFiniteLightBound[numVolumes];
var worldToView = WorldToCamera(camera);
var lightIndexMap = inputs.GetLightIndexMap();
for (int i = 0; i < lightIndexMap.Length; i++)
{
lightIndexMap[i] = -1;
}
int lightIndexCount = inputs.GetLightIndicesCount();
if (s_LightIndices == null || lightIndexCount > s_LightIndices.count)
{
// The light indices buffer is too small, resize
if (s_LightIndices != null)
s_LightIndices.Release();
s_LightIndices = new ComputeBuffer(lightIndexCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(int)));
}
uint lightIndex = 0;
foreach (var cl in inputs.visibleLights)
{
var range = cl.range;

{
boundData[idxOut] = bound;
lightData[idxOut] = light;
lightIndexMap[lightIndex] = idxOut;
lightIndex++;
}
int numLightsOut = 0;
for(int v=0; v<numVolTypes; v++) numLightsOut += numEntries[LightDefinitions.DIRECT_LIGHT, v];

idxOut = numEntries2nd[i, j] + offsets[i, j]; ++numEntries2nd[i, j];
boundData[idxOut] = bndData;
lightData[idxOut] = lgtData;
lightIndexMap[lightIndex] = idxOut;
lightIndex++;
inputs.SetLightIndexMap(lightIndexMap);
int numProbesOut = 0;
for(int v=0; v<numVolTypes; v++) numProbesOut += numEntries[LightDefinitions.REFLECTION_LIGHT, v];

s_ConvexBoundsBuffer.SetData(boundData);
s_LightDataBuffer.SetData(lightData);
inputs.FillLightIndices(s_LightIndices);
return numLightsOut + numProbesOut;
}

{
VoxelLightListGeneration(cmd, camera, numLights, projscr, invProjscr);
}
}
void PushGlobalParams(Camera camera, ScriptableRenderContext loop, Matrix4x4 viewToWorld, Matrix4x4 scrProj, Matrix4x4 incScrProj, int numDirLights)

8
TestbedPipelines/Fptl/RegularForwardLightingUtils.hlsl


StructuredBuffer<SFiniteLightData> g_vLightData;
StructuredBuffer<uint> g_vLightListMeshInst; // build on CPU if in use. direct lights first, then reflection probes. (don't support Buffer yet in unity, so using structured)
uniform int g_numLights;
uniform int g_numReflectionProbes;
uniform uint4 unity_LightIndicesOffsetAndCount;
uniform uint4 unity_ReflectionProbeIndicesOffsetAndCount;
start = model==REFLECTION_LIGHT ? g_numLights : 0; // offset by numLights entries
nrLights = model==REFLECTION_LIGHT ? g_numReflectionProbes : g_numLights;
start = model==REFLECTION_LIGHT ? unity_ReflectionProbeIndicesOffsetAndCount.x : unity_LightIndicesOffsetAndCount.x;
nrLights = model==REFLECTION_LIGHT ? unity_ReflectionProbeIndicesOffsetAndCount.y : unity_LightIndicesOffsetAndCount.y;
}
uint FetchIndex(const uint start, const uint l)

66
TestbedPipelines/OnTileDeferredPipeline/OnTileDeferredRenderPipeline.cs


using System;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

public class OnTileDeferredRenderPipeline : RenderPipelineAsset {
#if UNITY_EDITOR
[UnityEditor.MenuItem("RenderPipeline/OnTileDeferredPipeline/Create Pipeline Asset", false, 17)]
[UnityEditor.MenuItem("Assets/Create/Render Pipeline/On Tile Deferred/Render Pipeline", priority = CoreUtils.assetCreateMenuPriority1)]
static void CreateDeferredRenderPipeline()
{
var instance = ScriptableObject.CreateInstance<OnTileDeferredRenderPipeline> ();

[UnityEditor.MenuItem("RenderPipeline/OnTileDeferredPipeline/Material Upgraders/Upgrade Standard Shader Materials")]
[UnityEditor.MenuItem("Edit/Render Pipeline/Upgrade/On Tile Deferred/Upgrade Standard Shader Materials", priority = CoreUtils.editMenuPriority2)]
static void SetupDeferredRenderPipelineMaterials()
{
Renderer[] _renderers = Component.FindObjectsOfType<Renderer> ();

if (_material == null)
continue;
if (_material.shader.name.Contains ("Standard (Specular setup)")) {
_material.shader = Shader.Find("Standard-SRP (Specular setup)");
} else if (_material.shader.name.Contains ("Standard")) {

{
return new OnTileDeferredRenderPipelineInstance(this);
}
[SerializeField] ShadowSettings m_ShadowSettings = new ShadowSettings();
ShadowSetup m_ShadowSetup;

// TODO: When graphics/renderpass lands, replace code that uses boolean below with SystemInfo.supportsReadOnlyDepth
#if UNITY_EDITOR || UNITY_STANDALONE
static bool s_SupportsReadOnlyDepth = true;
#else
#else
static bool s_SupportsReadOnlyDepth = false;
#endif

s_GBufferEmission = new RenderPassAttachment(RenderTextureFormat.ARGBHalf) { hideFlags = HideFlags.HideAndDontSave };
s_Depth = new RenderPassAttachment(RenderTextureFormat.Depth) { hideFlags = HideFlags.HideAndDontSave };
s_CameraTarget = s_GBufferAlbedo;
s_GBufferEmission.Clear(new Color(0.0f, 0.0f, 0.0f, 0.0f), 1.0f, 0);
s_Depth.Clear(new Color(), 1.0f, 0);

m_ReflectionNearAndFarClipMaterial.SetInt("_DstABlend", (int)BlendMode.Zero);
m_ReflectionNearAndFarClipMaterial.SetInt("_CullMode", (int)CullMode.Off);
m_ReflectionNearAndFarClipMaterial.SetInt("_CompareFunc", (int)CompareFunction.Always);
m_CookieTexArray = new TextureCache2D();
m_CubeCookieTexArray = new TextureCacheCubemap();
m_CubeReflTexArray = new TextureCacheCubemap();

void ExecuteRenderLoop(Camera camera, CullResults cullResults, ScriptableRenderContext loop)
{
using (RenderPass rp = new RenderPass (loop, camera.pixelWidth, camera.pixelHeight, 1, s_SupportsReadOnlyDepth ?
using (RenderPass rp = new RenderPass (loop, camera.pixelWidth, camera.pixelHeight, 1, s_SupportsReadOnlyDepth ?
using (new RenderPass.SubPass (rp, s_SupportsReadOnlyDepth ?
using (new RenderPass.SubPass (rp, s_SupportsReadOnlyDepth ?
new[] { s_GBufferAlbedo, s_GBufferSpecRough, s_GBufferNormal, s_GBufferEmission } :
new[] { s_GBufferAlbedo, s_GBufferSpecRough, s_GBufferNormal, s_GBufferEmission, s_GBufferRedF32 }, null)) {
using (var cmd = new CommandBuffer { name = "Create G-Buffer" }) {

loop.ExecuteCommandBuffer (cmd);
// render opaque objects using Deferred pass
var drawSettings = new DrawRendererSettings (camera, new ShaderPassName ("Deferred")) {
sorting = { flags = SortFlags.CommonOpaque },

}
//Lighting Pass
using (new RenderPass.SubPass(rp, new[] { s_GBufferEmission },
using (new RenderPass.SubPass(rp, new[] { s_GBufferEmission },
new[] { s_GBufferAlbedo, s_GBufferSpecRough, s_GBufferNormal, s_SupportsReadOnlyDepth ? s_Depth : s_GBufferRedF32 }, true))
{
using (var cmd = new CommandBuffer { name = "Deferred Lighting and Reflections Pass"} )

}
}
}
// Utilites
static Matrix4x4 GetFlipMatrix()
{

{
return camera.projectionMatrix * GetFlipMatrix();
}
Matrix4x4 PerspectiveCotanMatrix(float cotangent, float zNear, float zFar )
{
float deltaZ = zNear - zFar;

Matrix4x4 scaled = Matrix4x4.Scale (combinedExtent * 2.0f);
mat = mat * Matrix4x4.Translate (boxOffset) * scaled;
var probeRadius = combinedExtent.magnitude;
var viewDistance = eyePlane.GetDistanceToPoint(boxOffset);
bool intersectsNear = viewDistance - probeRadius <= nearDistanceFudged;

// draw the base probe
// TODO: (cleanup) dont use builtins like unity_SpecCube0
{
{
var props = new MaterialPropertyBlock ();
props.SetFloat ("_LightAsQuad", 1.0f);

Matrix4x4 temp3 = PerspectiveCotanMatrix (chsa, 0.0f, range);
return temp2 * temp1 * temp3 * worldToLight;
}
void RenderSpotlight(VisibleLight light, CommandBuffer cmd, MaterialPropertyBlock properties, bool renderAsQuad, bool intersectsNear, bool deferred)
{
float range = light.range;

// Setup Spot Rendering mesh matrix
float sideLength = range / chsa;
// scalingFactor corrosoponds to the scale factor setting (and wether file scale is used) of mesh in Unity mesh inspector.
// A scale factor setting in Unity of 0.01 would require this to be set to 100. A scale factor setting of 1, is just 1 here.
// scalingFactor corrosoponds to the scale factor setting (and wether file scale is used) of mesh in Unity mesh inspector.
// A scale factor setting in Unity of 0.01 would require this to be set to 100. A scale factor setting of 1, is just 1 here.
lightToWorld = lightToWorld * Matrix4x4.Scale (new Vector3(sideLength*SpotLightMeshScaleFactor, sideLength*SpotLightMeshScaleFactor, range*SpotLightMeshScaleFactor));
//set default cookie for spot light if there wasnt one added to the light manually

Vector3 lightPos = light.localToWorld.GetColumn (3); //position
float range = light.range;
// scalingFactor corrosoponds to the scale factor setting (and wether file scale is used) of mesh in Unity mesh inspector.
// A scale factor setting in Unity of 0.01 would require this to be set to 100. A scale factor setting of 1, is just 1 here.
// scalingFactor corrosoponds to the scale factor setting (and wether file scale is used) of mesh in Unity mesh inspector.
// A scale factor setting in Unity of 0.01 would require this to be set to 100. A scale factor setting of 1, is just 1 here.
if (cookie != null)
if (cookie != null)
else
else
if (renderAsQuad)
if (renderAsQuad)
else if (intersectsNear)
else if (intersectsNear)
else
else
cmd.DrawMesh (m_PointLightMesh, matrix, m_FiniteDeferredLightingMaterial, 0, 0, properties);
}

void RenderLightsDeferred (Camera camera, CullResults inputs, CommandBuffer cmd, ScriptableRenderContext loop)
{
int lightCount = inputs.visibleLights.Count;
for (int lightNum = 0; lightNum < lightCount; lightNum++)
for (int lightNum = 0; lightNum < lightCount; lightNum++)
{
VisibleLight light = inputs.visibleLights[lightNum];

Vector3 lightPos = light.localToWorld.GetColumn (3); //position
Vector3 lightDir = light.localToWorld.GetColumn (2); //z axis
float range = light.range;

float chsa = GetCotanHalfSpotAngle (light.spotAngle);
// Setup Light Matrix
m_LightMatrix[i] = SpotlightMatrix (light, worldToLight, range, chsa);
m_LightMatrix[i] = SpotlightMatrix (light, worldToLight, range, chsa);
} else if (light.lightType == LightType.Directional) {
m_LightData[i].x = LightDefinitions.DIRECTIONAL_LIGHT;

var decodeVals = rl.hdr;
// C is reflection volume center in world space (NOT same as cube map capture point)
var e = bnds.extents;
var C = mat.MultiplyPoint(boxOffset);
var e = bnds.extents;
var C = mat.MultiplyPoint(boxOffset);
var combinedExtent = e + new Vector3(blendDistance, blendDistance, blendDistance);
Vector3 vx = mat.GetColumn(0);

cmd.SetGlobalFloat ("_useLegacyCookies", UseLegacyCookies?1.0f:0.0f);
cmd.SetGlobalFloat ("_transparencyShadows", TransparencyShadows ? 1.0f : 0.0f);
}
}
}

5
Tests/GraphicsTests/Framework/Editor/TestFrameworkCustomBuild.cs


private static readonly string s_TestSceneFolder = "/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes";
private static readonly string s_BuildFolder = "/TestScenesBuild";
[MenuItem("RenderPipeline/TestFramework/Build-iOS")]
[MenuItem("Internal/RenderPipeline/TestFramework/Build-iOS")]
public static void BuildiOS()
{
TestFrameworkCustomBuild builder = new TestFrameworkCustomBuild();

[MenuItem("RenderPipeline/TestFramework/Build-iOS", true)]
[MenuItem("Internal/RenderPipeline/TestFramework/Build-iOS", true)]
public static bool ValidateBuildiOS()
{
#if UNITY_STANDALONE_OSX

4
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Scripts/Editor/GraphicTestTools.cs


public class GraphicTestTools
{
[MenuItem("GraphicTest Tools/Make Material Scene Instance")]
[MenuItem("Internal/GraphicTest Tools/Make Material Scene Instance")]
public static void MakeMaterialSceneInstance()
{
foreach(Object obj in Selection.objects)

}
}
[MenuItem("GraphicTest Tools/Update All Material Placers")]
[MenuItem("Internal/GraphicTest Tools/Update All Material Placers")]
public static void UpdateAllPlacers()
{
MultiMaterialPlacer[] placers = Object.FindObjectsOfType<MultiMaterialPlacer>();

5
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Shaders/DistordFromTex.shader


Properties
{
_Tex("InputTex", 2D) = "white" {}
_Scale("Scale", Float) = 2
_Bias("Bias", Float) = -1
}
SubShader
{

#pragma target 3.0
sampler2D _Tex;
float _Scale, _Bias;
float4 frag(v2f_customrendertexture IN) : COLOR
{

c.rg = c.rg * 2 - 1;
c.rg = c.rg * _Scale + _Bias;
return c;
}

1001
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/Distortion/Distord_TexRemap.exr
文件差异内容过多而无法显示
查看文件

4
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/Distortion/Distord_TexRemap.mat


m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Distord_TexRemap
m_Shader: {fileID: 4800000, guid: d133630aa023e0f4e89581914056f837, type: 3}
m_Shader: {fileID: 4800000, guid: 7f033e9aeb69daa47b4469d53c547419, type: 3}
m_ShaderKeywords: _ALBEDOAFFECTEMISSIVE_OFF _ALPHACUTOFFENABLE_OFF _DEPTHOFFSETENABLE_OFF
_DISTORTIONENABLE_OFF _DOUBLESIDEDENABLE_OFF _ENABLESPECULAROCCLUSION_OFF _ENABLEWIND_OFF
_PREREFRACTIONPASS_OFF

- _AlphaCutoff: 0.5
- _AlphaCutoffEnable: 0
- _Anisotropy: 0
- _Bias: -1
- _BlendMode: 0
- _CoatCoverage: 1
- _CoatIOR: 0.5

- _PPDPrimitiveWidth: 1
- _PreRefractionPass: 0
- _RefractionMode: 0
- _Scale: 2
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2
- _Smoothness: 1

882
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion.unity
文件差异内容过多而无法显示
查看文件

4
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion/Lit_Distortion.mat


m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _AORemapMax: 1
- _AORemapMin: 0
- _ATDistance: 1
- _AlbedoAffectEmissive: 0
- _AlphaCutoff: 0.5

- _DistortionEnable: 1
- _DistortionScale: 15
- _DistortionSrcBlend: 1
- _DistortionVectorBias: 0
- _DistortionVectorScale: 1
- _DoubleSidedEnable: 0
- _DoubleSidedNormalMode: 1
- _Drag: 1

12
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/001_SimpleCube.unity


m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.18028378, g: 0.22571412, b: 0.30692285, a: 1}
m_IndirectSpecularColor: {r: 0.18029502, g: 0.22572649, b: 0.30692935, a: 1}
m_GIWorkflowMode: 0
m_GIWorkflowMode: 1
m_GISettings:
serializedVersion: 2
m_BounceScale: 1

m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 1
m_EnableBakedLightmaps: 0
m_EnableRealtimeLightmaps: 1
m_LightmapEditorSettings:
serializedVersion: 9

m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_LightingDataAsset: {fileID: 0}
m_LightingDataAsset: {fileID: 112000002, guid: fd8f2c6386dc54f158818f3b4ce8a20d,
type: 2}
m_UseShadowmask: 1
--- !u!196 &4
NavMeshSettings:

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 380492249}
m_Enabled: 1
m_ExtensionPropertyValues: []
--- !u!124 &380492251
Behaviour:
m_ObjectHideFlags: 0

m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
m_StereoMirrorMode: 0
--- !u!4 &380492254
Transform:
m_ObjectHideFlags: 0

renderPipeline: {fileID: 11400000, guid: e6987eea1dd29074597d54ed91a54a26, type: 2}
cameraToUse: {fileID: 380492253}
hdr: 0
msaaSamples: 1
width: 1280
height: 720
--- !u!1 &707831285

7
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/002_Camera_Clip.unity


LightmapSettings:
m_ObjectHideFlags: 0
serializedVersion: 11
m_GIWorkflowMode: 0
m_GIWorkflowMode: 1
m_GISettings:
serializedVersion: 2
m_BounceScale: 1

m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 1
m_EnableBakedLightmaps: 0
m_EnableRealtimeLightmaps: 1
m_LightmapEditorSettings:
serializedVersion: 9

renderPipeline: {fileID: 11400000, guid: e6987eea1dd29074597d54ed91a54a26, type: 2}
cameraToUse: {fileID: 971756574}
hdr: 0
msaaSamples: 1
width: 1280
height: 720
--- !u!81 &971756571

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 971756569}
m_Enabled: 1
m_ExtensionPropertyValues: []
--- !u!124 &971756572
Behaviour:
m_ObjectHideFlags: 0

m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
m_StereoMirrorMode: 0
--- !u!4 &971756575
Transform:
m_ObjectHideFlags: 0

10
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/003_Camera_Ortho.unity


LightmapSettings:
m_ObjectHideFlags: 0
serializedVersion: 11
m_GIWorkflowMode: 0
m_GIWorkflowMode: 1
m_GISettings:
serializedVersion: 2
m_BounceScale: 1

m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 1
m_EnableBakedLightmaps: 0
m_EnableRealtimeLightmaps: 1
m_LightmapEditorSettings:
serializedVersion: 9

m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_LightingDataAsset: {fileID: 0}
m_LightingDataAsset: {fileID: 112000002, guid: da948721f81544d0ebdfaf7b4881c199,
type: 2}
m_UseShadowmask: 1
--- !u!196 &4
NavMeshSettings:

renderPipeline: {fileID: 11400000, guid: e6987eea1dd29074597d54ed91a54a26, type: 2}
cameraToUse: {fileID: 971756574}
hdr: 0
msaaSamples: 1
width: 1280
height: 720
--- !u!81 &971756571

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 971756569}
m_Enabled: 1
m_ExtensionPropertyValues: []
--- !u!124 &971756572
Behaviour:
m_ObjectHideFlags: 0

m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
m_StereoMirrorMode: 0
--- !u!4 &971756575
Transform:
m_ObjectHideFlags: 0

13
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/004_Camera_TargetTexture.unity


LightmapSettings:
m_ObjectHideFlags: 0
serializedVersion: 11
m_GIWorkflowMode: 0
m_GIWorkflowMode: 1
m_GISettings:
serializedVersion: 2
m_BounceScale: 1

m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 1
m_EnableRealtimeLightmaps: 1
m_EnableBakedLightmaps: 0
m_EnableRealtimeLightmaps: 0
m_LightmapEditorSettings:
serializedVersion: 9
m_Resolution: 2

m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_LightingDataAsset: {fileID: 0}
m_LightingDataAsset: {fileID: 112000002, guid: c40554504d2504a44a6ff29317f16d61,
type: 2}
m_UseShadowmask: 1
--- !u!196 &4
NavMeshSettings:

renderPipeline: {fileID: 11400000, guid: e6987eea1dd29074597d54ed91a54a26, type: 2}
cameraToUse: {fileID: 971756574}
hdr: 0
msaaSamples: 1
width: 1280
height: 720
--- !u!81 &971756571

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 971756569}
m_Enabled: 1
m_ExtensionPropertyValues: []
--- !u!124 &971756572
Behaviour:
m_ObjectHideFlags: 0

m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
m_StereoMirrorMode: 0
--- !u!4 &971756575
Transform:
m_ObjectHideFlags: 0

m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
m_StereoMirrorMode: 0
--- !u!4 &1604351919
Transform:
m_ObjectHideFlags: 0

143
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/005_LitBakedEmission.unity


LightmapSettings:
m_ObjectHideFlags: 0
serializedVersion: 11
m_GIWorkflowMode: 0
m_GIWorkflowMode: 1
m_GISettings:
serializedVersion: 2
m_BounceScale: 1

m_FinalGatherRayCount: 256
m_ReflectionCompression: 2
m_MixedBakeMode: 1
m_BakeBackend: 0
m_BakeBackend: 1
m_PVRSampling: 1
m_PVRDirectSampleCount: 32
m_PVRSampleCount: 500

m_PVRFilterTypeAO: 0
m_PVRFilteringMode: 1
m_PVRCulling: 1
m_PVRCulling: 0
m_PVRFilteringGaussRadiusDirect: 1
m_PVRFilteringGaussRadiusIndirect: 5
m_PVRFilteringGaussRadiusAO: 2

objectReference: {fileID: 0}
- target: {fileID: 400000, guid: b56f0b54c8a1042f3ae9a8904a576f5d, type: 3}
propertyPath: m_RootOrder
value: 2
value: 1
objectReference: {fileID: 0}
- target: {fileID: 400000, guid: b56f0b54c8a1042f3ae9a8904a576f5d, type: 3}
propertyPath: m_LocalScale.x

renderPipeline: {fileID: 11400000, guid: e6987eea1dd29074597d54ed91a54a26, type: 2}
cameraToUse: {fileID: 971756574}
hdr: 0
msaaSamples: 1
width: 1280
height: 720
--- !u!81 &971756571

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 971756569}
m_Enabled: 1
m_ExtensionPropertyValues: []
--- !u!124 &971756572
Behaviour:
m_ObjectHideFlags: 0

m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
m_StereoMirrorMode: 0
--- !u!4 &971756575
Transform:
m_ObjectHideFlags: 0

m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1161206970
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 1161206972}
- component: {fileID: 1161206971}
m_Layer: 0
m_Name: Directional Light
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!108 &1161206971
Light:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1161206970}
m_Enabled: 1
serializedVersion: 8
m_Type: 1
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Intensity: 1
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: 2
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_ColorTemperature: 6570
m_UseColorTemperature: 0
m_ShadowRadius: 0
m_ShadowAngle: 1
--- !u!4 &1161206972
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1161206970}
m_LocalRotation: {x: 0.7132504, y: 0, z: 0, w: 0.7009094}
m_LocalPosition: {x: 0, y: 3, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 91, y: 0, z: 0}
--- !u!1 &1354589631
GameObject:
m_ObjectHideFlags: 0

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 &1755136017
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 1755136019}
- component: {fileID: 1755136018}
m_Layer: 0
m_Name: TEMPLIGHT_DELETE ME
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!108 &1755136018
Light:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1755136017}
m_Enabled: 1
serializedVersion: 8
m_Type: 1
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Intensity: 0.001
m_Range: 10
m_SpotAngle: 30
m_CookieSize: 10
m_Shadows:
m_Type: 1
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_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_ColorTemperature: 6570
m_UseColorTemperature: 0
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!4 &1755136019
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1755136017}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 1.2441416, y: 3.61, z: -3.0811512}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 3
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}

4
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/005_LitBakedEmission/005_LitBakeEmission_Sphere.mat


m_PrefabInternal: {fileID: 0}
m_Name: 005_LitBakeEmission_Sphere
m_Shader: {fileID: 4800000, guid: 8d2bb70cbf9db8d4da26e15b26e74248, type: 3}
m_ShaderKeywords: _EMISSION _SPECULAR_COLOR
m_ShaderKeywords: _EMISSION _GLOSSINESS_FROM_BASE_ALPHA _SPECULAR_COLOR
m_LightmapFlags: 2
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _ZWrite: 1
m_Colors:
- _Color: {r: 0, g: 0, b: 0, a: 1}
- _EmissionColor: {r: 1, g: 0, b: 0, a: 1}
- _EmissionColor: {r: 2, g: 0, b: 0, a: 1}
- _ReflectColor: {r: 1, g: 1, b: 1, a: 1}
- _SpecColor: {r: 0, g: 0, b: 0, a: 1}

8
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/005_LitBakedEmission/LightingData.asset
文件差异内容过多而无法显示
查看文件

2
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/005_LitBakedEmission/LightingData.asset.meta


fileFormatVersion: 2
guid: 6a963d0bc4caa4faa93b9ab261a08f9f
timeCreated: 1504609165
timeCreated: 1509369649
licenseType: Pro
NativeFormatImporter:
externalObjects: {}

1001
Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/005_LitBakedEmission/Lightmap-0_comp_light.exr
文件差异内容过多而无法显示
查看文件

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

正在加载...
取消
保存