浏览代码

merged with master

/sample_game
Peter Andreasen 7 年前
当前提交
2ef7d649
共有 224 个文件被更改,包括 2896 次插入2291 次删除
  1. 25
      SampleScenes/HDTest/GraphicTest/Parallax Occlusion Mapping/Material/POM - Wood.mat
  2. 24
      SampleScenes/HDTest/GraphicTest/Tessellation/Material/Tessellation - Wood.mat
  3. 461
      SampleScenes/HDTest/HDRenderLoopTest.unity
  4. 2
      ScriptableRenderPipeline/Core/Camera/CameraSwitcher.cs
  5. 1
      ScriptableRenderPipeline/Core/Camera/FreeCamera.cs
  6. 7
      ScriptableRenderPipeline/Core/Debugging/DebugActionManager.cs
  7. 6
      ScriptableRenderPipeline/Core/Debugging/DebugItemHandler.cs
  8. 4
      ScriptableRenderPipeline/Core/Debugging/DebugItemUI.cs
  9. 1
      ScriptableRenderPipeline/Core/Debugging/DebugMenuManager.cs
  10. 3
      ScriptableRenderPipeline/Core/Debugging/DebugMenuState.cs
  11. 3
      ScriptableRenderPipeline/Core/Debugging/DebugMenuUI.cs
  12. 4
      ScriptableRenderPipeline/Core/Debugging/DebugMenuUpdater.cs
  13. 12
      ScriptableRenderPipeline/Core/Debugging/DebugPanel.cs
  14. 10
      ScriptableRenderPipeline/Core/Debugging/DebugPanelUI.cs
  15. 1
      ScriptableRenderPipeline/Core/Debugging/Debugging.cs
  16. 4
      ScriptableRenderPipeline/Core/Debugging/Editor/DebugMenuEditor.cs
  17. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateBool.cs
  18. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateColor.cs
  19. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateFloat.cs
  20. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateInt.cs
  21. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateUInt.cs
  22. 3
      ScriptableRenderPipeline/Core/Inputs/InputRegistering.cs
  23. 6
      ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/Shadow.hlsl
  24. 309
      ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/ShadowAlgorithms.hlsl
  25. 4
      ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/ShadowSampling.hlsl
  26. 32
      ScriptableRenderPipeline/Core/ShaderLibrary/Wind.hlsl
  27. 4
      ScriptableRenderPipeline/Core/Shadow/Shadow.cs
  28. 2
      ScriptableRenderPipeline/Core/Singleton.cs
  29. 88
      ScriptableRenderPipeline/Core/TextureCache.cs
  30. 7
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs
  31. 5
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs.hlsl
  32. 8
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.hlsl
  33. 4
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayLatlong.shader
  34. 4
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugFullScreen.shader
  35. 4
      ScriptableRenderPipeline/HDRenderPipeline/Debug/LightingDebugPanel.cs
  36. 92
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineInspector.cs
  37. 85
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs
  38. 695
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
  39. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.asset
  40. 34
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.cs
  41. 390
      ScriptableRenderPipeline/HDRenderPipeline/HDStringConstants.cs
  42. 17
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/ScreenSpaceAmbientOcclusion.cs
  43. 884
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Editor/HDLightEditor.cs
  44. 135
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/EditorLightUtilities.cs
  45. 2
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/Deferred.compute
  46. 23
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/ShadowDispatch.hlsl
  47. 107
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs
  48. 3
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs.hlsl
  49. 2
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.hlsl
  50. 14
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePassLoop.hlsl
  51. 5
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/builddispatchindirect.compute
  52. 6
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Volumetrics/HomogeneousFog.cs
  53. 12
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Volumetrics/VolumetricLighting.cs
  54. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs
  55. 27
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/Editor/LayeredLitUI.cs
  56. 61
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader
  57. 88
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader
  58. 136
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs
  59. 72
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/LitUI.cs
  60. 31
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs
  61. 33
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs.hlsl
  62. 227
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl
  63. 73
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader
  64. 58
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitData.hlsl
  65. 29
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitDataInternal.hlsl
  66. 6
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitProperties.hlsl
  67. 120
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.hlsl
  68. 82
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader
  69. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.DisneyDiffuse.cs
  70. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.GGX.cs
  71. 15
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitDepthPass.hlsl
  72. 8
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitMetaPass.hlsl
  73. 21
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitVelocityPass.hlsl
  74. 259
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringProfile.cs
  75. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/BaseUnlitUI.cs
  76. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/UnlitUI.cs
  77. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.cs
  78. 3
      ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/HDRenderPipelineResources.asset
  79. 2
      ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/HDRenderPipelineResources.asset.meta
  80. 60
      ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/RenderPipelineResources.cs
  81. 4
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Editor/CommonSettingsEditor.cs
  82. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawSssProfile.shader
  83. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader
  84. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/SceneSettings.cs
  85. 1
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/SceneSettingsManager.cs
  86. 1
      ScriptableRenderPipeline/HDRenderPipeline/ShaderConfig.cs
  87. 1
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPass.cs
  88. 13
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/TessellationShare.hlsl
  89. 10
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/VaryingMesh.hlsl
  90. 43
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/VertMesh.hlsl
  91. 8
      ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesFunctions.hlsl
  92. 6
      ScriptableRenderPipeline/HDRenderPipeline/Sky/GGXConvolve.shader
  93. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Editor/HDRISkyEditor.cs
  94. 12
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/HDRISkyRenderer.cs
  95. 4
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Resources/SkyHDRI.shader
  96. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/Editor/ProceduralSkyEditor.cs
  97. 10
      ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkyRenderer.cs
  98. 17
      ScriptableRenderPipeline/HDRenderPipeline/Sky/RuntimeFilterIBL.cs
  99. 46
      ScriptableRenderPipeline/HDRenderPipeline/Sky/SkyManager.cs
  100. 2
      ScriptableRenderPipeline/HDRenderPipeline/Wind/ShaderWindSettings.cs

25
SampleScenes/HDTest/GraphicTest/Parallax Occlusion Mapping/Material/POM - Wood.mat


m_PrefabInternal: {fileID: 0}
m_Name: POM - Wood
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _HEIGHTMAP _NORMALMAP _NORMALMAP_TANGENT_SPACE _PER_PIXEL_DISPLACEMENT
m_ShaderKeywords: _DEPTHOFFSET_ON _HEIGHTMAP _NORMALMAP _NORMALMAP_TANGENT_SPACE
_PER_PIXEL_DISPLACEMENT
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _BaseColorMap:
m_Texture: {fileID: 2800000, guid: 927434958f610214aa6a4179f134f5fd, type: 3}
m_Scale: {x: 2, y: 2}
m_Offset: {x: 0, y: 0}
- _BentNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BentNormalMapOS:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BumpMap:
m_Texture: {fileID: 0}

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _AlbedoAffectEmissive: 0
- _CoatCoverage: 1
- _CoatIOR: 0.5
- _DepthOffsetEnable: 0
- _DepthOffsetEnable: 1
- _DetailAOScale: 1
- _DetailAlbedoScale: 1
- _DetailHeightScale: 1

- _EmissiveColorMode: 1
- _EmissiveIntensity: 0
- _EnablePerPixelDisplacement: 1
- _EnableSpecularOcclusion: 0
- _HeightAmplitude: 1.27
- _HeightCenter: 0.5
- _HeightAmplitude: 1
- _HeightCenter: 1
- _HeightMax: 100
- _HeightMin: 0
- _HorizonFade: 1
- _InitialBend: 1
- _MaterialID: 1

- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2
- _Smoothness: 0.5
- _SmoothnessRemapMax: 1
- _SmoothnessRemapMin: 0
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1

24
SampleScenes/HDTest/GraphicTest/Tessellation/Material/Tessellation - Wood.mat


m_Name: Tessellation - Wood
m_Shader: {fileID: 4800000, guid: 756bac9090102564582875f4c7e30202, type: 3}
m_ShaderKeywords: _HEIGHTMAP _NORMALMAP _NORMALMAP_TANGENT_SPACE _TESSELLATION_DISPLACEMENT
_TESSELLATION_TILING_SCALE
_TESSELLATION_OBJECT_SCALE _TESSELLATION_TILING_SCALE
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

- _BaseColorMap:
m_Texture: {fileID: 2800000, guid: 927434958f610214aa6a4179f134f5fd, type: 3}
m_Scale: {x: 2, y: 2}
m_Offset: {x: 0, y: 0}
- _BentNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BentNormalMapOS:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BumpMap:
m_Texture: {fileID: 0}

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _AlbedoAffectEmissive: 0
- _CoatCoverage: 1
- _CoatIOR: 0.5
- _CullMode: 2
- _Cutoff: 0.5
- _DepthOffsetEnable: 0

- _EmissiveColorMode: 1
- _EmissiveIntensity: 0
- _EnablePerPixelDisplacement: 0
- _EnableSpecularOcclusion: 0
- _HeightAmplitude: 1.27
- _HeightCenter: 0.5
- _HeightAmplitude: 1
- _HeightCenter: 1
- _HeightMax: 100
- _HeightMin: 0
- _HorizonFade: 1
- _InitialBend: 1
- _MaterialID: 1

- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2
- _Smoothness: 0.5
- _SmoothnessRemapMax: 1
- _SmoothnessRemapMin: 0
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1

- _TessellationFactorMinDistance: 20
- _TessellationFactorTriangleSize: 100
- _TessellationMode: 1
- _TessellationObjectScale: 0
- _TessellationObjectScale: 1
- _TessellationShapeFactor: 0.75
- _TessellationTilingScale: 1
- _TexWorldScale: 1

461
SampleScenes/HDTest/HDRenderLoopTest.unity


- {fileID: 1737381188}
- {fileID: 1083738368}
m_Father: {fileID: 0}
m_RootOrder: 23
m_RootOrder: 24
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &68487706
GameObject:

m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &113580755
MonoBehaviour:
m_ObjectHideFlags: 0
m_ObjectHideFlags: 2
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 113580753}

m_ShadowAngle: 0
--- !u!114 &113580757
MonoBehaviour:
m_ObjectHideFlags: 0
m_ObjectHideFlags: 2
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 113580753}

- 0.2
- 0.2
shadowAlgorithm: 0
shadowVariant: 0
shadowVariant: 4
format: 0
data:
shadowDatas: []
format: 4
data: 0bd7a33b0000803f
shadowDatas:
- format: 4
data: 0bd7a33b0000803f
--- !u!1 &122368350
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 122368351}
- component: {fileID: 122368354}
- component: {fileID: 122368353}
- component: {fileID: 122368352}
m_Layer: 0
m_Name: PlaneWood_POM
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &122368351
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 122368350}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -10, y: 0, z: 0}
m_LocalScale: {x: -1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 874252442}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!23 &122368352
MeshRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 122368350}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 066ad54931fe38b4fa252c05cede10e1, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!64 &122368353
MeshCollider:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 122368350}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 3
m_Convex: 0
m_CookingOptions: 14
m_SkinWidth: 0.01
m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &122368354
MeshFilter:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 122368350}
m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0}
--- !u!1 &129451982
GameObject:
m_ObjectHideFlags: 0

- {fileID: 744696322}
- {fileID: 1854618466}
m_Father: {fileID: 0}
m_RootOrder: 13
m_RootOrder: 14
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &146321727
GameObject:

format: 0
data:
shadowDatas: []
--- !u!1 &195260445
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 195260446}
- component: {fileID: 195260449}
- component: {fileID: 195260448}
- component: {fileID: 195260447}
m_Layer: 0
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &195260446
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 195260445}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -5, y: -0.5, z: 5.5}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 874252442}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!23 &195260447
MeshRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 195260445}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 73c176f402d2c2f4d929aa5da7585d17, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!65 &195260448
BoxCollider:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 195260445}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!33 &195260449
MeshFilter:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 195260445}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!1 &209784732
GameObject:
m_ObjectHideFlags: 0

- {fileID: 1943835612}
- {fileID: 611007879}
m_Father: {fileID: 0}
m_RootOrder: 22
m_RootOrder: 23
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &473569563
GameObject:

- {fileID: 262492847}
- {fileID: 726298021}
m_Father: {fileID: 0}
m_RootOrder: 24
m_RootOrder: 25
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &501648654
GameObject:

- {fileID: 2082383796}
- {fileID: 733865594}
m_Father: {fileID: 0}
m_RootOrder: 17
m_RootOrder: 18
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1001 &653798720
Prefab:

- {fileID: 682868817}
- {fileID: 1148469244}
m_Father: {fileID: 0}
m_RootOrder: 15
m_RootOrder: 16
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &851265586
GameObject:

format: 0
data:
shadowDatas: []
--- !u!1 &874252441
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 874252442}
m_Layer: 0
m_Name: Test - Displacement Mapping With Depth Offset
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &874252442
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 874252441}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 10, y: 1, z: -14}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 1950745466}
- {fileID: 122368351}
- {fileID: 885480688}
- {fileID: 195260446}
m_Father: {fileID: 0}
m_RootOrder: 13
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &885480687
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 885480688}
- component: {fileID: 885480691}
- component: {fileID: 885480690}
- component: {fileID: 885480689}
m_Layer: 0
m_Name: PlaneWood_Tess
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &885480688
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 885480687}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 874252442}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!23 &885480689
MeshRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 885480687}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: f6dfdaa6d241dc94bb8816edbe111721, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!64 &885480690
MeshCollider:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 885480687}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 3
m_Convex: 0
m_CookingOptions: 14
m_SkinWidth: 0.01
m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &885480691
MeshFilter:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 885480687}
m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0}
--- !u!1 &891124079
GameObject:
m_ObjectHideFlags: 0

- {fileID: 2145183178}
- {fileID: 659590037}
m_Father: {fileID: 0}
m_RootOrder: 19
m_RootOrder: 20
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &970745596
GameObject:

- {fileID: 1314434839}
- {fileID: 1413658393}
m_Father: {fileID: 0}
m_RootOrder: 25
m_RootOrder: 26
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1035351685
GameObject:

- {fileID: 835886986}
- {fileID: 834722896}
m_Father: {fileID: 0}
m_RootOrder: 18
m_RootOrder: 19
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1083738367
GameObject:

- {fileID: 213621735}
- {fileID: 1566813408}
m_Father: {fileID: 0}
m_RootOrder: 26
m_RootOrder: 27
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1226270484
GameObject:

- {fileID: 831940005}
- {fileID: 1235762388}
m_Father: {fileID: 0}
m_RootOrder: 14
m_RootOrder: 15
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1227501373
GameObject:

- {fileID: 1988224186}
- {fileID: 1555751256}
m_Father: {fileID: 0}
m_RootOrder: 20
m_RootOrder: 21
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1484421573
GameObject:

- {fileID: 1063426084}
- {fileID: 476925262}
m_Father: {fileID: 0}
m_RootOrder: 21
m_RootOrder: 22
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1640077383
GameObject:

- {fileID: 993426561}
- {fileID: 1559142268}
m_Father: {fileID: 0}
m_RootOrder: 16
m_RootOrder: 17
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1808459746
GameObject:

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

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

m_ShowCustomSorter: 0
breakBeforeColorGrading: 0
m_BeforeTransparentBundles: []
m_BeforeStackBundles: []
m_BeforeStackBundles:
- assemblyQualifiedName: HalfToneOpaque, Assembly-CSharp, Version=0.0.0.0, Culture=neutral,
PublicKeyToken=null
m_AfterStackBundles: []
--- !u!114 &1828470168
MonoBehaviour:

format: 0
data:
shadowDatas: []
--- !u!1 &1950745465
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 1950745466}
- component: {fileID: 1950745469}
- component: {fileID: 1950745468}
- component: {fileID: 1950745467}
m_Layer: 0
m_Name: Point light
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1950745466
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1950745465}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: -5, y: 2, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 874252442}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &1950745467
MonoBehaviour:
m_ObjectHideFlags: 2
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1950745465}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c6c2871f720b2af4e9210febdac74517, type: 3}
m_Name:
m_EditorClassIdentifier:
shadowResolution: 1024
shadowDimmer: 1
shadowFadeDistance: 10000
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05
- 0.2
- 0.3
shadowCascadeBorders:
- 0.2
- 0.2
- 0.2
- 0.2
shadowAlgorithm: 0
shadowVariant: 4
shadowPrecision: 0
shadowData:
format: 4
data: 0bd7a33b0000803f
shadowDatas:
- format: 4
data: 0bd7a33b0000803f
--- !u!114 &1950745468
MonoBehaviour:
m_ObjectHideFlags: 2
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1950745465}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 7a68c43fe1f2a47cfa234b5eeaa98012, type: 3}
m_Name:
m_EditorClassIdentifier:
m_InnerSpotPercent: 0
lightDimmer: 1
fadeDistance: 10000
affectDiffuse: 1
affectSpecular: 1
lightTypeExtent: 0
spotLightShape: 0
shapeLength: 0
shapeWidth: 0
shapeRadius: 0
maxSmoothness: 1
applyRangeAttenuation: 1
useOldInspector: 0
showAdditionalSettings: 1
--- !u!108 &1950745469
Light:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1950745465}
m_Enabled: 1
serializedVersion: 8
m_Type: 2
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Intensity: 40
m_Range: 20
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.5
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!1 &1968535689
GameObject:
m_ObjectHideFlags: 0

2
ScriptableRenderPipeline/Core/Camera/CameraSwitcher.cs


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

1
ScriptableRenderPipeline/Core/Camera/FreeCamera.cs


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

7
ScriptableRenderPipeline/Core/Debugging/DebugActionManager.cs


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

persistent.repeatMode = DebugActionRepeatMode.Never;
AddAction(DebugAction.MakePersistent, persistent);
AddAction(DebugAction.MoveVertical, new DebugActionDesc { axisTrigger = kDPadVertical, repeatMode = DebugActionRepeatMode.Delay, repeatDelay = 0.2f });
AddAction(DebugAction.MoveHorizontal, new DebugActionDesc { axisTrigger = kDPadHorizontal, repeatMode = DebugActionRepeatMode.Delay, repeatDelay = 0.2f });
AddAction(DebugAction.MoveVertical, new DebugActionDesc { axisTrigger = kDPadVertical, repeatMode = DebugActionRepeatMode.Delay, repeatDelay = 0.4f });
AddAction(DebugAction.MoveHorizontal, new DebugActionDesc { axisTrigger = kDPadHorizontal, repeatMode = DebugActionRepeatMode.Delay, repeatDelay = 0.4f });
}
DebugActionManager()

6
ScriptableRenderPipeline/Core/Debugging/DebugItemHandler.cs


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

public abstract bool OnEditorGUIImpl();
public void OnEditorGUI()
{
if (m_DebugItem.runtimeOnly)
return;
if(OnEditorGUIImpl())
{
DebugMenuUI.changed = true;

4
ScriptableRenderPipeline/Core/Debugging/DebugItemUI.cs


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

1
ScriptableRenderPipeline/Core/Debugging/DebugMenuManager.cs


using System;
using System.Linq;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

3
ScriptableRenderPipeline/Core/Debugging/DebugMenuState.cs


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

3
ScriptableRenderPipeline/Core/Debugging/DebugMenuUI.cs


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

4
ScriptableRenderPipeline/Core/Debugging/DebugMenuUpdater.cs


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

12
ScriptableRenderPipeline/Core/Debugging/DebugPanel.cs


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

public enum DebugItemFlag
{
None,
DynamicDisplay,
EditorOnly
None = 0,
DynamicDisplay = 1 << 0,
EditorOnly = 1 << 1,
RuntimeOnly = 1 << 2
}
public class DebugItem

public DebugItemHandler handler { get { return m_Handler; } }
public DebugItemFlag flags { get { return m_Flags; } }
public bool readOnly { get { return m_Setter == null; } }
public bool editorOnly { get { return (flags & DebugItemFlag.EditorOnly) != 0; } }
public bool runtimeOnly { get { return (flags & DebugItemFlag.RuntimeOnly) != 0; } }
public DebugItem(string name, string panelName, Type type, Func<object> getter, Action<object> setter, DebugItemFlag flags = DebugItemFlag.None, DebugItemHandler handler = null)
{

10
ScriptableRenderPipeline/Core/Debugging/DebugPanelUI.cs


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

for (int i = 0; i < m_DebugPanel.itemCount; i++)
{
DebugItem item = m_DebugPanel.GetDebugItem(i);
if(!((item.flags & DebugItemFlag.EditorOnly) != 0))
#if UNITY_EDITOR
// We don't want runtime only items even in the "player" debug menu if we are in the editor.
if (item.runtimeOnly)
continue;
#endif
if(!item.editorOnly)
{
DebugItemHandler handler = item.handler; // Should never be null, we have at least the default handler
m_ItemsUI.Add(handler.BuildGUI(parent));

1
ScriptableRenderPipeline/Core/Debugging/Debugging.cs


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

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


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

4
ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateBool.cs


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

4
ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateColor.cs


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

4
ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateFloat.cs


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

4
ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateInt.cs


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

4
ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateUInt.cs


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

3
ScriptableRenderPipeline/Core/Inputs/InputRegistering.cs


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

6
ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/Shadow.hlsl


#ifndef SHADOW_HLSL
#ifndef SHADOW_HLSL
#define SHADOW_HLSL
//
// Shadow master include header.

// Shadow context definition and initialization, i.e. resource binding (project header, must be kept in sync with C# runtime)
#define SHADOW_CONTEXT_INCLUDE
#include "../../ShadowIncludes.inl"
#include "../../ShadowIncludes.hlsl"
#undef SHADOW_CONTEXT_INCLUDE
// helper function to extract shadowmap data from the ShadowData struct

// include project specific shadow dispatcher. If this file is not empty, it MUST define which default shadows it's overriding
#define SHADOW_DISPATCH_INCLUDE
#include "../../ShadowIncludes.inl"
#include "../../ShadowIncludes.hlsl"
#undef SHADOW_DISPATCH_INCLUDE
// if shadow dispatch is empty we'll fall back to default shadow sampling implementations

309
ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/ShadowAlgorithms.hlsl


// calc TCs
float2 posTC = posNDC * 0.5 + 0.5;
closestSampleNDC = (floor(posTC * sd.textureSize.zw) + 0.5) * sd.texelSizeRcp.zw * 2.0 - 1.0.xx;
return (posTC * sd.scaleOffset.xy + sd.scaleOffset.zw) * sd.textureSize.xy;
return uint2( (posTC * sd.scaleOffset.xy + sd.scaleOffset.zw) * sd.textureSize.xy );
}
int EvalShadow_GetCubeFaceID( float3 dir )

//
#define kMaxShadowCascades 4
#define SHADOW_REPEAT_CASCADE( _x ) _x, _x, _x, _x
int EvalShadow_GetSplitSphereIndexForDirshadows( float3 positionWS, float4 dirShadowSplitSpheres[4], out float relDistance )
{

payloadOffset++;
float4 borders = asfloat( shadowContext.payloads[payloadOffset] );
payloadOffset++;
float border = borders[shadowSplitIndex];
float alpha = border <= 0.0 ? 0.0 : saturate( (relDistance - (1.0 - border)) / border );
ShadowData sd = shadowContext.shadowDatas[index + 1 + shadowSplitIndex];
// normal based bias

/* Be careful of this code, we need it here before the if statement otherwise the compiler screws up optimizing dirShadowSplitSpheres VGPRs away */
float border = borders[shadowSplitIndex];
float alpha = border <= 0.0 ? 0.0 : saturate( (relDistance - (1.0 - border)) / border );
float4 splitSphere = dirShadowSplitSpheres[shadowSplitIndex];
float3 cascadeDir = normalize( -splitSphere.xyz + dirShadowSplitSpheres[min(3,shadowSplitIndex+1)].xyz );
float3 wposDir = normalize( -splitSphere.xyz + positionWS );
// Be careful of this code, we need it here before the if statement otherwise the compiler screws up optimizing dirShadowSplitSpheres VGPRs away
float3 splitSphere = dirShadowSplitSpheres[shadowSplitIndex].xyz;
float3 cascadeDir = normalize( -splitSphere + dirShadowSplitSpheres[min( shadowSplitIndex+1, kMaxShadowCascades-1 )].xyz );
float3 wposDir = normalize( -splitSphere + positionWS );
alpha = cascDot > 0.0 ? alpha : lerp( alpha, 0.0, saturate( -cascDot * 4.0 ) );
alpha = cascDot > 0.0 ? alpha : lerp( alpha, 0.0, saturate( -cascDot * 4.0 ) );
// sample the texture
uint texIdx, sampIdx;
float slice;

UnpackShadowType( sd.shadowType, shadowType, shadowAlgorithm );
float shadow = SampleShadow_SelectAlgorithm( shadowContext, sd, payloadOffset, posTC, sd.bias, slice, shadowAlgorithm, texIdx, sampIdx );
float shadow = SampleShadow_SelectAlgorithm( shadowContext, sd, payloadOffset, posTC, sd.bias, slice, shadowAlgorithm, texIdx, sampIdx );
float shadow1 = 1.0;
float shadow1 = 1.0;
[branch]
if( alpha > 0.0 )
{
sd = shadowContext.shadowDatas[index + 1 + shadowSplitIndex];

UnpackShadowmapId( sd.id, slice );
[branch]
if( all( abs( posNDC.xy ) <= (1.0 - sd.texelSizeRcp.zw * 0.5) ) )
shadow1 = SampleShadow_SelectAlgorithm( shadowContext, sd, orig_payloadOffset, posTC, sd.bias, slice, shadowAlgorithm, texIdx, sampIdx );
}

}
#define EvalShadow_CascadedDepth_( _samplerType ) \
float EvalShadow_CascadedDepth_Blend( ShadowContext shadowContext, uint shadowAlgorithm, Texture2DArray tex, _samplerType samp, float3 positionWS, float3 normalWS, int index, float3 L ) \
{ \
/* load the right shadow data for the current face */ \
float4 dirShadowSplitSpheres[kMaxShadowCascades]; \
uint payloadOffset = EvalShadow_LoadSplitSpheres( shadowContext, index, dirShadowSplitSpheres ); \
float relDistance; \
int shadowSplitIndex = EvalShadow_GetSplitSphereIndexForDirshadows( positionWS, dirShadowSplitSpheres, relDistance ); \
if( shadowSplitIndex < 0 ) \
return 1.0; \
\
float4 scales = asfloat( shadowContext.payloads[payloadOffset] ); \
payloadOffset++; \
float4 borders = asfloat( shadowContext.payloads[payloadOffset] ); \
payloadOffset++; \
ShadowData sd = shadowContext.shadowDatas[index + 1 + shadowSplitIndex]; \
/* normal based bias */ \
float3 orig_pos = positionWS; \
uint orig_payloadOffset = payloadOffset; \
positionWS += EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), scales[shadowSplitIndex] * sd.texelSizeRcp.zw, sd.normalBias ); \
\
/* Be careful of this code, we need it here before the if statement otherwise the compiler screws up optimizing dirShadowSplitSpheres VGPRs away */ \
float border = borders[shadowSplitIndex]; \
float alpha = border <= 0.0 ? 0.0 : saturate( (relDistance - (1.0 - border)) / border ); \
float4 splitSphere = dirShadowSplitSpheres[shadowSplitIndex]; \
float3 cascadeDir = normalize( -splitSphere.xyz + dirShadowSplitSpheres[min(kMaxShadowCascades-1,shadowSplitIndex+1)].xyz ); \
float3 wposDir = normalize( -splitSphere.xyz + positionWS ); \
float cascDot = dot( cascadeDir, wposDir ); \
alpha = cascDot > 0.0 ? alpha : lerp( alpha, 0.0, saturate( -cascDot * 4.0 ) ); \
\
/* get shadowmap texcoords */ \
float3 posNDC; \
float3 posTC = EvalShadow_GetTexcoords( sd, positionWS, posNDC, true ); \
/* sample the texture */ \
float slice; \
UnpackShadowmapId( sd.id, slice ); \
\
float shadow = SampleShadow_SelectAlgorithm( shadowContext, sd, payloadOffset, posTC, sd.bias, slice, shadowAlgorithm, tex, samp ); \
\
shadowSplitIndex++; \
float shadow1 = 1.0; \
if( shadowSplitIndex < kMaxShadowCascades ) \
{ \
shadow1 = shadow; \
\
[branch] \
if( alpha > 0.0 ) \
{ \
sd = shadowContext.shadowDatas[index + 1 + shadowSplitIndex]; \
positionWS = orig_pos + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), scales[shadowSplitIndex] * sd.texelSizeRcp.zw, sd.normalBias ); \
posTC = EvalShadow_GetTexcoords( sd, positionWS, posNDC, false ); \
/* sample the texture */ \
UnpackShadowmapId( sd.id, slice ); \
\
if( all( abs( posNDC.xy ) <= (1.0 - sd.texelSizeRcp.zw * 0.5) ) ) \
shadow1 = SampleShadow_SelectAlgorithm( shadowContext, sd, orig_payloadOffset, posTC, sd.bias, slice, shadowAlgorithm, tex, samp ); \
} \
} \
shadow = lerp( shadow, shadow1, alpha ); \
return shadow; \
#define EvalShadow_CascadedDepth_( _samplerType ) \
float EvalShadow_CascadedDepth_Blend( ShadowContext shadowContext, uint shadowAlgorithms[kMaxShadowCascades], Texture2DArray tex, _samplerType samp, float3 positionWS, float3 normalWS, int index, float3 L ) \
{ \
/* load the right shadow data for the current face */ \
float4 dirShadowSplitSpheres[kMaxShadowCascades]; \
uint payloadOffset = EvalShadow_LoadSplitSpheres( shadowContext, index, dirShadowSplitSpheres ); \
float relDistance; \
int shadowSplitIndex = EvalShadow_GetSplitSphereIndexForDirshadows( positionWS, dirShadowSplitSpheres, relDistance ); \
if( shadowSplitIndex < 0 ) \
return 1.0; \
\
float4 scales = asfloat( shadowContext.payloads[payloadOffset] ); \
payloadOffset++; \
float4 borders = asfloat( shadowContext.payloads[payloadOffset] ); \
payloadOffset++; \
float border = borders[shadowSplitIndex]; \
float alpha = border <= 0.0 ? 0.0 : saturate( (relDistance - (1.0 - border)) / border ); \
\
ShadowData sd = shadowContext.shadowDatas[index + 1 + shadowSplitIndex]; \
/* normal based bias */ \
float3 orig_pos = positionWS; \
uint orig_payloadOffset = payloadOffset; \
positionWS += EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), scales[shadowSplitIndex] * sd.texelSizeRcp.zw, sd.normalBias ); \
/* Be careful of this code, we need it here before the if statement otherwise the compiler screws up optimizing dirShadowSplitSpheres VGPRs away */ \
float3 splitSphere = dirShadowSplitSpheres[shadowSplitIndex].xyz; \
float3 cascadeDir = normalize( -splitSphere + dirShadowSplitSpheres[min( shadowSplitIndex+1, kMaxShadowCascades-1 )].xyz ); \
float3 wposDir = normalize( -splitSphere + positionWS ); \
float cascDot = dot( cascadeDir, wposDir ); \
alpha = cascDot > 0.0 ? alpha : lerp( alpha, 0.0, saturate( -cascDot * 4.0 ) ); \
\
/* get shadowmap texcoords */ \
float3 posNDC; \
float3 posTC = EvalShadow_GetTexcoords( sd, positionWS, posNDC, true ); \
\
/* sample the texture */ \
float slice; \
UnpackShadowmapId( sd.id, slice ); \
\
float shadow = SampleShadow_SelectAlgorithm( shadowContext, sd, payloadOffset, posTC, sd.bias, slice, shadowAlgorithms[shadowSplitIndex], tex, samp ); \
float shadow1 = 1.0; \
\
shadowSplitIndex++; \
if( shadowSplitIndex < kMaxShadowCascades ) \
{ \
shadow1 = shadow; \
\
if( alpha > 0.0 ) \
{ \
sd = shadowContext.shadowDatas[index + 1 + shadowSplitIndex]; \
positionWS = orig_pos + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), scales[shadowSplitIndex] * sd.texelSizeRcp.zw, sd.normalBias ); \
posTC = EvalShadow_GetTexcoords( sd, positionWS, posNDC, false ); \
/* sample the texture */ \
UnpackShadowmapId( sd.id, slice ); \
\
[branch] \
if( all( abs( posNDC.xy ) <= (1.0 - sd.texelSizeRcp.zw * 0.5) ) ) \
shadow1 = SampleShadow_SelectAlgorithm( shadowContext, sd, orig_payloadOffset, posTC, sd.bias, slice, shadowAlgorithms[shadowSplitIndex], tex, samp ); \
} \
} \
shadow = lerp( shadow, shadow1, alpha ); \
return shadow; \
} \
\
float EvalShadow_CascadedDepth_Blend( ShadowContext shadowContext, uint shadowAlgorithm, Texture2DArray tex, _samplerType samp, float3 positionWS, float3 normalWS, int index, float3 L ) \
{ \
uint shadowAlgorithms[kMaxShadowCascades] = { SHADOW_REPEAT_CASCADE( shadowAlgorithm ) }; \
return EvalShadow_CascadedDepth_Blend( shadowContext, shadowAlgorithms, tex, samp, positionWS, normalWS, index, L ); \
EvalShadow_CascadedDepth_( SamplerComparisonState )
EvalShadow_CascadedDepth_( SamplerState )
#undef EvalShadow_CascadedDepth_

float EvalShadow_CascadedDepth_Dither( ShadowContext shadowContext, float3 positionWS, float3 normalWS, int index, float3 L )
{
// load the right shadow data for the current face
float4 dirShadowSplitSpheres[4];
float4 dirShadowSplitSpheres[kMaxShadowCascades];
uint payloadOffset = EvalShadow_LoadSplitSpheres( shadowContext, index, dirShadowSplitSpheres );
float relDistance;
int shadowSplitIndex = EvalShadow_GetSplitSphereIndexForDirshadows( positionWS, dirShadowSplitSpheres, relDistance );

float3 posNDC;
float3 posTC = EvalShadow_GetTexcoords( sd, positionWS, posNDC, true );
if( shadowSplitIndex < (kMaxShadowCascades-1) )
int nextSplit = min( shadowSplitIndex+1, kMaxShadowCascades-1 );
float3 splitSphere = dirShadowSplitSpheres[shadowSplitIndex].xyz;
float3 cascadeDir = normalize( -splitSphere + dirShadowSplitSpheres[min( 3, shadowSplitIndex + 1 )].xyz );
float3 wposDir = normalize( -splitSphere + positionWS );
float cascDot = dot( cascadeDir, wposDir );
alpha = cascDot > 0.0 ? alpha : lerp( alpha, 0.0, saturate( -cascDot * 4.0 ) );
if( shadowSplitIndex < nextSplit && step( EvalShadow_hash12( posTC.xy ), alpha ) )
float4 splitSphere = dirShadowSplitSpheres[shadowSplitIndex];
float3 cascadeDir = normalize( -splitSphere.xyz + dirShadowSplitSpheres[shadowSplitIndex+1].xyz );
float3 wposDir = normalize( -splitSphere.xyz + positionWS );
float cascDot = dot( cascadeDir, wposDir );
alpha = cascDot > 0.0 ? alpha : lerp( alpha, 0.0, saturate( -cascDot * 4.0 ) );
if( step( EvalShadow_hash12( posTC.xy ), alpha ) )
{
shadowSplitIndex++;
sd = shadowContext.shadowDatas[index + 2 + shadowSplitIndex];
positionWS = orig_pos + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), scales[shadowSplitIndex+1] * sd.texelSizeRcp.zw, sd.normalBias );
posTC = EvalShadow_GetTexcoords( sd, positionWS );
}
sd = shadowContext.shadowDatas[index + 1 + nextSplit];
positionWS = orig_pos + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), scales[nextSplit] * sd.texelSizeRcp.zw, sd.normalBias );
posTC = EvalShadow_GetTexcoords( sd, positionWS );
}
// sample the texture
uint texIdx, sampIdx;

return shadowSplitIndex < (kMaxShadowCascades-1) ? shadow : lerp( shadow, 1.0, alpha );
}
#define EvalShadow_CascadedDepth_( _samplerType ) \
float EvalShadow_CascadedDepth_Dither( ShadowContext shadowContext, uint shadowAlgorithm, Texture2DArray tex, _samplerType samp, float3 positionWS, float3 normalWS, int index, float3 L ) \
{ \
/* load the right shadow data for the current face */ \
float4 dirShadowSplitSpheres[kMaxShadowCascades]; \
uint payloadOffset = EvalShadow_LoadSplitSpheres( shadowContext, index, dirShadowSplitSpheres ); \
float relDistance; \
int shadowSplitIndex = EvalShadow_GetSplitSphereIndexForDirshadows( positionWS, dirShadowSplitSpheres, relDistance ); \
if( shadowSplitIndex < 0 ) \
return 1.0; \
\
float4 scales = asfloat( shadowContext.payloads[payloadOffset] ); \
payloadOffset++; \
float4 borders = asfloat( shadowContext.payloads[payloadOffset] ); \
payloadOffset++; \
float border = borders[shadowSplitIndex]; \
float alpha = border <= 0.0 ? 0.0 : saturate( (relDistance - (1.0 - border)) / border ); \
\
ShadowData sd = shadowContext.shadowDatas[index + 1 + shadowSplitIndex]; \
/* normal based bias */ \
float3 orig_pos = positionWS; \
positionWS += EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), scales[shadowSplitIndex] * sd.texelSizeRcp.zw, sd.normalBias ); \
/* get shadowmap texcoords */ \
float3 posNDC; \
float3 posTC = EvalShadow_GetTexcoords( sd, positionWS, posNDC, true ); \
\
if( shadowSplitIndex < (kMaxShadowCascades-1) ) \
{ \
float4 splitSphere = dirShadowSplitSpheres[shadowSplitIndex]; \
float3 cascadeDir = normalize( -splitSphere.xyz + dirShadowSplitSpheres[shadowSplitIndex+1].xyz ); \
float3 wposDir = normalize( -splitSphere.xyz + positionWS ); \
float cascDot = dot( cascadeDir, wposDir ); \
alpha = cascDot > 0.0 ? alpha : lerp( alpha, 0.0, saturate( -cascDot * 4.0 ) ); \
\
if( step( EvalShadow_hash12( posTC.xy ), alpha ) ) \
{ \
sd = shadowContext.shadowDatas[index + 2 + shadowSplitIndex]; \
positionWS = orig_pos + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), scales[shadowSplitIndex+1] * sd.texelSizeRcp.zw, sd.normalBias ); \
posTC = EvalShadow_GetTexcoords( sd, positionWS ); \
} \
} \
/* sample the texture */ \
float slice; \
UnpackShadowmapId( sd.id, slice ); \
float shadow = SampleShadow_SelectAlgorithm( shadowContext, sd, payloadOffset, posTC, sd.bias, slice, shadowAlgorithm, tex, samp ); \
return shadowSplitIndex < (kMaxShadowCascades-1) ? shadow : lerp( shadow, 1.0, alpha ); \
#define EvalShadow_CascadedDepth_( _samplerType ) \
float EvalShadow_CascadedDepth_Dither( ShadowContext shadowContext, uint shadowAlgorithms[kMaxShadowCascades], Texture2DArray tex, _samplerType samp, float3 positionWS, float3 normalWS, int index, float3 L ) \
{ \
/* load the right shadow data for the current face */ \
float4 dirShadowSplitSpheres[kMaxShadowCascades]; \
uint payloadOffset = EvalShadow_LoadSplitSpheres( shadowContext, index, dirShadowSplitSpheres ); \
float relDistance; \
int shadowSplitIndex = EvalShadow_GetSplitSphereIndexForDirshadows( positionWS, dirShadowSplitSpheres, relDistance ); \
if( shadowSplitIndex < 0 ) \
return 1.0; \
\
float4 scales = asfloat( shadowContext.payloads[payloadOffset] ); \
payloadOffset++; \
float4 borders = asfloat( shadowContext.payloads[payloadOffset] ); \
payloadOffset++; \
float border = borders[shadowSplitIndex]; \
float alpha = border <= 0.0 ? 0.0 : saturate( (relDistance - (1.0 - border)) / border ); \
\
ShadowData sd = shadowContext.shadowDatas[index + 1 + shadowSplitIndex]; \
/* normal based bias */ \
float3 orig_pos = positionWS; \
positionWS += EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), scales[shadowSplitIndex] * sd.texelSizeRcp.zw, sd.normalBias ); \
/* get shadowmap texcoords */ \
float3 posNDC; \
float3 posTC = EvalShadow_GetTexcoords( sd, positionWS, posNDC, true ); \
\
int nextSplit = min( shadowSplitIndex+1, kMaxShadowCascades-1 ); \
float3 splitSphere = dirShadowSplitSpheres[shadowSplitIndex].xyz; \
float3 cascadeDir = normalize( -splitSphere + dirShadowSplitSpheres[nextSplit].xyz ); \
float3 wposDir = normalize( -splitSphere + positionWS ); \
float cascDot = dot( cascadeDir, wposDir ); \
alpha = cascDot > 0.0 ? alpha : lerp( alpha, 0.0, saturate( -cascDot * 4.0 ) ); \
\
if( shadowSplitIndex != nextSplit && step( EvalShadow_hash12( posTC.xy ), alpha ) ) \
{ \
sd = shadowContext.shadowDatas[index + 1 + nextSplit]; \
positionWS = orig_pos + EvalShadow_NormalBias( normalWS, saturate( dot( normalWS, L ) ), scales[nextSplit] * sd.texelSizeRcp.zw, sd.normalBias ); \
posTC = EvalShadow_GetTexcoords( sd, positionWS ); \
} \
/* sample the texture */ \
float slice; \
UnpackShadowmapId( sd.id, slice ); \
float shadow = SampleShadow_SelectAlgorithm( shadowContext, sd, payloadOffset, posTC, sd.bias, slice, shadowAlgorithms[shadowSplitIndex], tex, samp ); \
return shadowSplitIndex < (kMaxShadowCascades-1) ? shadow : lerp( shadow, 1.0, alpha ); \
} \
\
float EvalShadow_CascadedDepth_Dither( ShadowContext shadowContext, uint shadowAlgorithm, Texture2DArray tex, _samplerType samp, float3 positionWS, float3 normalWS, int index, float3 L ) \
{ \
uint shadowAlgorithms[kMaxShadowCascades] = { SHADOW_REPEAT_CASCADE( shadowAlgorithm ) }; \
return EvalShadow_CascadedDepth_Dither( shadowContext, shadowAlgorithms, tex, samp, positionWS, normalWS, index, L ); \
EvalShadow_CascadedDepth_( SamplerComparisonState )
EvalShadow_CascadedDepth_( SamplerState )
#undef EvalShadow_CascadedDepth_

float4 closestWS = mul( closestNDC, sd.shadowToWorld );
return closestWS.xyz / closestWS.w;
}
float3 EvalShadow_GetClosestSample_Cascade( ShadowContext shadowContext, Texture2DArray tex, float3 positionWS, float3 normalWS, int index, float4 L )
{
// load the right shadow data for the current face
float4 dirShadowSplitSpheres[4];
uint payloadOffset = EvalShadow_LoadSplitSpheres( shadowContext, index, dirShadowSplitSpheres );
float relDistance;
int shadowSplitIndex = EvalShadow_GetSplitSphereIndexForDirshadows( positionWS, dirShadowSplitSpheres, relDistance );
if( shadowSplitIndex < 0 )
return 1.0;
float4 scales = asfloat( shadowContext.payloads[payloadOffset] );
payloadOffset++;
float4 borders = asfloat( shadowContext.payloads[payloadOffset] );
payloadOffset++;
ShadowData sd = shadowContext.shadowDatas[index + 1 + shadowSplitIndex];
float4 closestNDC = { 0,0,0,1 };
uint2 texelIdx = EvalShadow_GetTexcoords( sd, positionWS, closestNDC.xy );
// load the texel
uint texIdx, sampIdx;
float slice;
UnpackShadowmapId( sd.id, texIdx, sampIdx, slice );
closestNDC.z = LOAD_TEXTURE2D_ARRAY_LOD( tex, texelIdx, slice, 0 ).x;
// reconstruct depth position
float4 closestWS = mul( closestNDC, sd.shadowToWorld );
return closestWS.xyz / closestWS.w;
}

4
ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/ShadowSampling.hlsl


float2 fetchesUV[9];
SampleShadow_ComputeSamples_Tent_5x5(shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV);
for (int i = 0; i < 9; i++)
for( int i = 0; i < 9; i++ )
return shadow;
}

32
ScriptableRenderPipeline/Core/ShaderLibrary/Wind.hlsl


void ApplyWind( inout float3 worldPos,
inout float3 worldNormal,
float3 rootWP,
float stiffness,
float drag,
float shiverDrag,
float shiverDirectionality,
float initialBend,
float shiverMask,
float4 time)
void ApplyWindDisplacement( inout float3 positionWS,
float3 normalWS,
float3 rootWP,
float stiffness,
float drag,
float shiverDrag,
float shiverDirectionality,
float initialBend,
float shiverMask,
float4 time)
WindData wind = GetAnalyticalWind(worldPos, rootWP, drag, shiverDrag, initialBend, time);
WindData wind = GetAnalyticalWind(positionWS, rootWP, drag, shiverDrag, initialBend, time);
if(wind.Strength > 0.0f)
if (wind.Strength > 0.0f)
float att = AttenuateTrunk(distance(worldPos, rootWP), stiffness);
float att = AttenuateTrunk(distance(positionWS, rootWP), stiffness);
worldPos = Rotate(rootWP, worldPos, rotAxis, (wind.Strength) * 0.001 * att);
positionWS = Rotate(rootWP, positionWS, rotAxis, (wind.Strength) * 0.001 * att);
float3 shiverDirection = normalize(lerp(worldNormal, normalize(wind.Direction + wind.ShiverDirection), shiverDirectionality));
worldPos += wind.ShiverStrength * shiverDirection * shiverMask;
float3 shiverDirection = normalize(lerp(normalWS, normalize(wind.Direction + wind.ShiverDirection), shiverDirectionality));
positionWS += wind.ShiverStrength * shiverDirection * shiverMask;
}
}

4
ScriptableRenderPipeline/Core/Shadow/Shadow.cs


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

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

2
ScriptableRenderPipeline/Core/Singleton.cs


using UnityEngine.SceneManagement;
namespace UnityEngine.Experimental.Rendering
{
[ExecuteInEditMode]

88
ScriptableRenderPipeline/Core/TextureCache.cs


{
protected int m_NumMipLevels;
#if UNITY_EDITOR
static int s_TextureCacheIdGenerator = 0;
int m_TextureCacheId = 0;
static bool s_ForceReinjectGlobalFirst = false;
static bool s_ForceReinjectGlobalSecond = false;
static int s_GlobalSecondSetByTexCacheID = -1;
// here we receive the in-editor updated textures. These must be reinjected into
// any texture cache which has a stale copy of it. However, we don't have a this-pointer to the texture cache
// so instead we defer this to NewFrame() where we force reinject.
// Ideally we'd build up a list here of textures which are to be reinjected but unfortunately the texture we receive
// is an intermediate one and not the final compressed one. So instead we will have to reinject all in NewFrame().
internal class AssetReloader : UnityEditor.AssetPostprocessor
{
void OnPostprocessTexture(Texture texture)
{
s_ForceReinjectGlobalFirst = true;
s_ForceReinjectGlobalSecond = false;
s_GlobalSecondSetByTexCacheID = -1;
}
}
#endif
public static bool isMobileBuildTarget
{
get

private struct SSliceEntry
{
public uint texId;
public uint countLRU;
public uint texId;
public uint countLRU;
#if UNITY_EDITOR
public Hash128 hash;
#endif
};
private int m_NumTextures;

return sliceIndex;
var texId = (uint)texture.GetInstanceID();
#if UNITY_EDITOR
var hash = texture.imageContentsHash;
#endif
//assert(TexID!=g_InvalidTexID);
if (texId == g_InvalidTexID) return 0;

// search for existing copy
if (m_LocatorInSliceArray.ContainsKey(texId))
int cachedSlice;
if (m_LocatorInSliceArray.TryGetValue(texId, out cachedSlice))
sliceIndex = m_LocatorInSliceArray[texId];
sliceIndex = cachedSlice;
Debug.Assert(m_SliceArray[sliceIndex].texId == texId);
Debug.Assert(m_SliceArray[sliceIndex].texId == texId);
#if UNITY_EDITOR
bSwapSlice = bSwapSlice || (m_SliceArray[sliceIndex].hash != hash);
#endif
}
// If no existing copy found in the array

}
}
// wrap up
Debug.Assert(bFoundAvailOrExistingSlice, "The texture cache doesn't have enough space to store all textures. Please either increase the size of the texture cache, or use fewer unique textures.");
if (bFoundAvailOrExistingSlice)

if (bSwapSlice) // if this was a miss
{
#if UNITY_EDITOR
m_SliceArray[sliceIndex].hash = hash;
#endif
// transfer new slice to sliceIndex from source texture
TransferToSlice(sliceIndex, texture);
}

//for(int q=1; q<m_numTextures; q++)
// assert(m_SliceArray[m_SortedIdxArray[q-1]].CountLRU>=m_SliceArray[m_SortedIdxArray[q]].CountLRU);
#if UNITY_EDITOR
// one or more textures got updated in editor. Unfortunately we do not know exactly which since
// OnPostprocessTexture() receives intermediate uncompressed textures. So we will have to reinject all slices to force an update.
if(s_ForceReinjectGlobalSecond && s_GlobalSecondSetByTexCacheID==m_TextureCacheId)
{
s_ForceReinjectGlobalSecond = false;
s_GlobalSecondSetByTexCacheID = -1;
}
if(s_ForceReinjectGlobalFirst)
{
s_ForceReinjectGlobalSecond = true;
s_GlobalSecondSetByTexCacheID = m_TextureCacheId;
s_ForceReinjectGlobalFirst = false;
}
if(s_ForceReinjectGlobalSecond)
{
// all texture caches must loop through and force a reinject on all entries when this is true.
for(int i = 0; i < m_NumTextures; i++)
{
var texID = m_SliceArray[i].texId;
if(texID!=g_InvalidTexID)
{
Texture texture = (Texture) EditorUtility.InstanceIDToObject((int) texID);
if(texture!=null) TransferToSlice(i, texture);
}
}
}
#endif
}
protected TextureCache()

#if UNITY_EDITOR
m_TextureCacheId = s_TextureCacheIdGenerator; // assign an ID so we can tell the caches apart
++s_TextureCacheIdGenerator; // static/global
#endif
}
public virtual void TransferToSlice(int sliceIndex, Texture texture)

7
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs


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

{
if (!isDebugViewMaterialInit)
{
List<RenderPipelineMaterial> materialList = Utilities.GetRenderPipelineMaterialList();
List<RenderPipelineMaterial> materialList = CoreUtils.GetRenderPipelineMaterialList();
// TODO: Share this code to retrieve deferred material with HDRenderPipeline
// Find first material that have non 0 Gbuffer count and assign it as deferredMaterial

None = 0,
Tessellation = DebugViewGbuffer.BakeDiffuseLightingWithAlbedoPlusEmissive + 1,
PerPixelDisplacement,
VertexDisplacement,
DepthOffset,
Lightmap,
}

public bool displayOpaqueObjects = true;
public bool displayTransparentObjects = true;
public bool enableDistortion = true;
public bool enableGaussianPyramid = true;
public bool enableSSSAndTransmission = true;
}

{
None,
// Lighting
MinLightingFullScreenDebug,
MinLightingFullScreenDebug,
SSAO,
SSAOBeforeFiltering,
DeferredShadows,

5
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs.hlsl


#define DEBUGVIEWPROPERTIES_NONE (0)
#define DEBUGVIEWPROPERTIES_TESSELLATION (12)
#define DEBUGVIEWPROPERTIES_PER_PIXEL_DISPLACEMENT (13)
#define DEBUGVIEWPROPERTIES_DEPTH_OFFSET (14)
#define DEBUGVIEWPROPERTIES_LIGHTMAP (15)
#define DEBUGVIEWPROPERTIES_VERTEX_DISPLACEMENT (14)
#define DEBUGVIEWPROPERTIES_DEPTH_OFFSET (15)
#define DEBUGVIEWPROPERTIES_LIGHTMAP (16)
//
// UnityEngine.Experimental.Rendering.HDPipeline.FullScreenDebugMode: static fields

8
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.hlsl


#endif
break;
case DEBUGVIEWPROPERTIES_VERTEX_DISPLACEMENT:
#ifdef _VERTEX_DISPLACEMENT // Caution: This define is related to a shader features (But it may become a standard features for HD
result = float3(1.0, 0.0, 0.0);
#else
result = float3(0.0, 0.0, 0.0);
#endif
break;
case DEBUGVIEWPROPERTIES_DEPTH_OFFSET:
#ifdef _DEPTHOFFSET_ON // Caution: This define is related to a shader features (But it may become a standard features for HD
result = float3(1.0, 0.0, 0.0);

4
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayLatlong.shader


Pass
{
ZWrite Off
ZTest Off
Blend One Zero
ZTest Always
Blend Off
Cull Off
HLSLPROGRAM

4
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugFullScreen.shader


Pass
{
ZWrite Off
ZTest Off
Blend One Zero
ZTest Always
Blend Off
Cull Off
HLSLPROGRAM

4
ScriptableRenderPipeline/HDRenderPipeline/Debug/LightingDebugPanel.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine;
using System;
#if UNITY_EDITOR

92
ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineInspector.cs


using System;
using System.Reflection;
using System.Linq.Expressions;
using UnityEditor.Experimental.Rendering;
//using EditorGUIUtility=UnityEditor.EditorGUIUtility;

public readonly GUIContent renderingSettingsLabel = new GUIContent("Rendering Settings");
public readonly GUIContent useForwardRenderingOnly = new GUIContent("Use Forward Rendering Only");
public readonly GUIContent useDepthPrepassWithDeferredRendering = new GUIContent("Use Depth Prepass with Deferred rendering");
public readonly GUIContent renderAlphaTestOnlyInDeferredPrepass = new GUIContent("Alpha Test only");
// Texture Settings
public readonly GUIContent textureSettings = new GUIContent("Texture Settings");

// Tile pass Settings
public readonly GUIContent tileLightLoopSettings = new GUIContent("Tile Light Loop Settings");
public readonly GUIContent enableTileAndCluster = new GUIContent("Enable tile/clustered", "Toggle");
public readonly GUIContent enableComputeLightEvaluation = new GUIContent("Enable Compute Light Evaluation", "Toggle");
public readonly GUIContent enableComputeLightVariants = new GUIContent("Enable Compute Light Variants", "Toggle");
public readonly GUIContent enableComputeMaterialVariants = new GUIContent("Enable Compute Material Variants", "Toggle");
public readonly GUIContent enableClustered = new GUIContent("Enable clustered", "Toggle");
public readonly GUIContent enableFptlForOpaqueWhenClustered = new GUIContent("Enable Fptl For Opaque When Clustered", "Toggle");
public readonly GUIContent enableBigTilePrepass = new GUIContent("Enable big tile prepass", "Toggle");
public readonly GUIContent tileDebugByCategory = new GUIContent("Enable Debug By Category", "Toggle");
public readonly GUIContent enableTileAndCluster = new GUIContent("Enable tile/clustered");
public readonly GUIContent enableComputeLightEvaluation = new GUIContent("Enable Compute Light Evaluation");
public readonly GUIContent enableComputeLightVariants = new GUIContent("Enable Compute Light Variants");
public readonly GUIContent enableComputeMaterialVariants = new GUIContent("Enable Compute Material Variants");
public readonly GUIContent enableClustered = new GUIContent("Enable clustered");
public readonly GUIContent enableFptlForOpaqueWhenClustered = new GUIContent("Enable Fptl For Opaque When Clustered");
public readonly GUIContent enableBigTilePrepass = new GUIContent("Enable big tile prepass");
public readonly GUIContent tileDebugByCategory = new GUIContent("Enable Debug By Category");
// Sky Settings
public readonly GUIContent skyParams = new GUIContent("Sky Settings");

// Rendering Settings
SerializedProperty m_RenderingUseForwardOnly = null;
SerializedProperty m_RenderingUseDepthPrepass = null;
SerializedProperty m_RenderingUseDepthPrepassAlphaTestOnly = null;
// Subsurface Scattering Settings
// Old SSS Model >>>

SerializedProperty m_PointCookieSize = null;
SerializedProperty m_ReflectionCubemapSize = null;
private void InitializeProperties()
void InitializeProperties()
m_DefaultDiffuseMaterial = serializedObject.FindProperty("m_DefaultDiffuseMaterial");
m_DefaultShader = serializedObject.FindProperty("m_DefaultShader");
// Following way of getting property allow to handle change of properties name with serializations
using (var p = new PropertyFetcher<HDRenderPipelineAsset>(serializedObject))
{
m_DefaultDiffuseMaterial = p.FindProperty("m_DefaultDiffuseMaterial");
m_DefaultShader = p.FindProperty("m_DefaultShader");
// Tile settings
m_enableTileAndCluster = FindProperty(x => x.tileSettings.enableTileAndCluster);
m_enableComputeLightEvaluation = FindProperty(x => x.tileSettings.enableComputeLightEvaluation);
m_enableComputeLightVariants = FindProperty(x => x.tileSettings.enableComputeLightVariants);
m_enableComputeMaterialVariants = FindProperty(x => x.tileSettings.enableComputeMaterialVariants);
m_enableClustered = FindProperty(x => x.tileSettings.enableClustered);
m_enableFptlForOpaqueWhenClustered = FindProperty(x => x.tileSettings.enableFptlForOpaqueWhenClustered);
m_enableBigTilePrepass = FindProperty(x => x.tileSettings.enableBigTilePrepass);
// Shadow settings
m_ShadowAtlasWidth = FindProperty(x => x.shadowInitParams.shadowAtlasWidth);
m_ShadowAtlasHeight = FindProperty(x => x.shadowInitParams.shadowAtlasHeight);
// Tile settings
m_enableTileAndCluster = p.FindProperty(x => x.tileSettings.enableTileAndCluster);
m_enableComputeLightEvaluation = p.FindProperty(x => x.tileSettings.enableComputeLightEvaluation);
m_enableComputeLightVariants = p.FindProperty(x => x.tileSettings.enableComputeLightVariants);
m_enableComputeMaterialVariants = p.FindProperty(x => x.tileSettings.enableComputeMaterialVariants);
m_enableClustered = p.FindProperty(x => x.tileSettings.enableClustered);
m_enableFptlForOpaqueWhenClustered = p.FindProperty(x => x.tileSettings.enableFptlForOpaqueWhenClustered);
m_enableBigTilePrepass = p.FindProperty(x => x.tileSettings.enableBigTilePrepass);
// Texture settings
m_SpotCookieSize = FindProperty(x => x.textureSettings.spotCookieSize);
m_PointCookieSize = FindProperty(x => x.textureSettings.pointCookieSize);
m_ReflectionCubemapSize = FindProperty(x => x.textureSettings.reflectionCubemapSize);
// Shadow settings
m_ShadowAtlasWidth = p.FindProperty(x => x.shadowInitParams.shadowAtlasWidth);
m_ShadowAtlasHeight = p.FindProperty(x => x.shadowInitParams.shadowAtlasHeight);
// Rendering settings
m_RenderingUseForwardOnly = FindProperty(x => x.renderingSettings.useForwardRenderingOnly);
m_RenderingUseDepthPrepass = FindProperty(x => x.renderingSettings.useDepthPrepassWithDeferredRendering);
// Texture settings
m_SpotCookieSize = p.FindProperty(x => x.textureSettings.spotCookieSize);
m_PointCookieSize = p.FindProperty(x => x.textureSettings.pointCookieSize);
m_ReflectionCubemapSize = p.FindProperty(x => x.textureSettings.reflectionCubemapSize);
// Subsurface Scattering Settings
// Old SSS Model >>>
m_UseDisneySSS = FindProperty(x => x.sssSettings.useDisneySSS);
// <<< Old SSS Model
m_Profiles = FindProperty(x => x.sssSettings.profiles);
m_NumProfiles = m_Profiles.FindPropertyRelative("Array.size");
}
// Rendering settings
m_RenderingUseForwardOnly = p.FindProperty(x => x.renderingSettings.useForwardRenderingOnly);
m_RenderingUseDepthPrepass = p.FindProperty(x => x.renderingSettings.useDepthPrepassWithDeferredRendering);
m_RenderingUseDepthPrepassAlphaTestOnly = p.FindProperty(x => x.renderingSettings.renderAlphaTestOnlyInDeferredPrepass);
SerializedProperty FindProperty<TValue>(Expression<Func<HDRenderPipelineAsset, TValue>> expr)
{
var path = Utilities.GetFieldPath(expr);
return serializedObject.FindProperty(path);
// Subsurface Scattering Settings
// Old SSS Model >>>
m_UseDisneySSS = p.FindProperty(x => x.sssSettings.useDisneySSS);
// <<< Old SSS Model
m_Profiles = p.FindProperty(x => x.sssSettings.profiles);
m_NumProfiles = m_Profiles.FindPropertyRelative("Array.size");
}
}
static void HackSetDirty(RenderPipelineAsset asset)

if (!m_RenderingUseForwardOnly.boolValue) // If we are deferred
{
EditorGUILayout.PropertyField(m_RenderingUseDepthPrepass, styles.useDepthPrepassWithDeferredRendering);
if(m_RenderingUseDepthPrepass.boolValue)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_RenderingUseDepthPrepassAlphaTestOnly, styles.renderAlphaTestOnlyInDeferredPrepass);
EditorGUI.indentLevel--;
}
}
EditorGUI.indentLevel--;

85
ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs


using UnityEngine;
using UnityEditor;
using UnityEngine.SceneManagement;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityObject = UnityEngine.Object;
[UnityEditor.MenuItem("HDRenderPipeline/Add \"Additional Light-shadow Data\" (if not present)")]
[MenuItem("HDRenderPipeline/Add \"Additional Light-shadow Data\" (if not present)")]
Light[] lights = GameObject.FindObjectsOfType(typeof(Light)) as Light[];
var lights = UnityObject.FindObjectsOfType(typeof(Light)) as Light[];
foreach (Light light in lights)
foreach (var light in lights)
{
}
{
}
[UnityEditor.MenuItem("HDRenderPipeline/Add \"Additional Camera Data\" (if not present)")]
[MenuItem("HDRenderPipeline/Add \"Additional Camera Data\" (if not present)")]
Camera[] cameras = GameObject.FindObjectsOfType(typeof(Camera)) as Camera[];
var cameras = UnityObject.FindObjectsOfType(typeof(Camera)) as Camera[];
foreach (Camera camera in cameras)
foreach (var camera in cameras)
{
}
}
}

{
Object[] materials = Resources.FindObjectsOfTypeAll<Material>();
foreach (Object obj in materials)
var materials = Resources.FindObjectsOfTypeAll<Material>();
foreach (var mat in materials)
Material mat = obj as Material;
if (mat.shader.name == "HDRenderPipeline/LayeredLit" || mat.shader.name == "HDRenderPipeline/LayeredLitTessellation")
{
LayeredLitGUI.SynchronizeAllLayers(mat);

static void RemoveMaterialKeywords(Material material)
{
string[] keywordsToRemove = material.shaderKeywords;
foreach (var keyword in keywordsToRemove)
{
foreach (var keyword in material.shaderKeywords)
}
}
// The goal of this script is to help maintenance of data that have already been produced but need to update to the latest shader code change.

{
try
{
Object[] materials = Resources.FindObjectsOfTypeAll<Material>();
var materials = Resources.FindObjectsOfTypeAll<Material>();
Material mat = materials[i] as Material;
var mat = materials[i];
EditorUtility.DisplayProgressBar(
"Setup materials Keywords...",

[MenuItem("HDRenderPipeline/Test/Remove tessellation materials (not reversible)")]
static void RemoveTessellationMaterials()
{
Object[] materials = Resources.FindObjectsOfTypeAll<Material>();
var materials = Resources.FindObjectsOfTypeAll<Material>();
Shader litShader = Shader.Find("HDRenderPipeline/Lit");
Shader layeredLitShader = Shader.Find("HDRenderPipeline/LayeredLit");
var litShader = Shader.Find("HDRenderPipeline/Lit");
var layeredLitShader = Shader.Find("HDRenderPipeline/LayeredLit");
foreach (Object obj in materials)
foreach (var mat in materials)
Material mat = obj as Material;
if (mat.shader.name == "HDRenderPipeline/LitTessellation")
{
mat.shader = litShader;

[MenuItem("HDRenderPipeline/Export Sky to Image")]
static void ExportSkyToImage()
{
HDRenderPipeline renderpipeline = UnityEngine.Experimental.Rendering.RenderPipelineManager.currentPipeline as HDRenderPipeline;
if(renderpipeline == null)
var renderpipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
if (renderpipeline == null)
Texture2D result = renderpipeline.ExportSkyToTexture();
if(result == null)
{
var result = renderpipeline.ExportSkyToTexture();
if (result == null)
}
byte[] bytes = null;
bytes = result.EncodeToEXR(Texture2D.EXRFlags.CompressZIP);
Object.DestroyImmediate(result);
byte[] bytes = result.EncodeToEXR(Texture2D.EXRFlags.CompressZIP);
UnityObject.DestroyImmediate(result);
string assetPath = EditorUtility.SaveFilePanel("Export Sky", "Assets", "SkyExport", "exr");
if (!string.IsNullOrEmpty(assetPath))

[MenuItem("GameObject/HD Render Pipeline/Scene Settings", false, 10)]
static void CreateCustomGameObject(MenuCommand menuCommand)
{
GameObject sceneSettings = new GameObject("Scene Settings");
var sceneSettings = new GameObject("Scene Settings");
GameObjectUtility.SetParentAndAlign(sceneSettings, menuCommand.context as GameObject);
Undo.RegisterCreatedObjectUndo(sceneSettings, "Create " + sceneSettings.name);
Selection.activeObject = sceneSettings;

class DoCreateNewAsset<AssetType> : UnityEditor.ProjectWindowCallback.EndNameEditAction where AssetType : ScriptableObject
class DoCreateNewAsset<TAssetType> : ProjectWindowCallback.EndNameEditAction where TAssetType : ScriptableObject
var newAsset = ScriptableObject.CreateInstance<AssetType>();
newAsset.name = System.IO.Path.GetFileName(pathName);
var newAsset = CreateInstance<TAssetType>();
newAsset.name = Path.GetFileName(pathName);
AssetDatabase.CreateAsset(newAsset, pathName);
ProjectWindowUtil.ShowCreatedAsset(newAsset);
}

class DoCreateNewAssetHDRISkySettings : DoCreateNewAsset<HDRISkySettings> {}
class DoCreateNewAssetProceduralSkySettings : DoCreateNewAsset<ProceduralSkySettings> {}
class DoCreateNewAssetSSAOSettings : DoCreateNewAsset<ScreenSpaceAmbientOcclusionSettings> {}
Texture2D icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetSSSProfile>(), "New SSS Profile.asset", icon, null);
}

Texture2D icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetCommonSettings>(), "New CommonSettings.asset", icon, null);
}

Texture2D icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetHDRISkySettings>(), "New HDRISkySettings.asset", icon, null);
}

Texture2D icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetProceduralSkySettings>(), "New ProceduralSkySettings.asset", icon, null);
}

Texture2D icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetSSAOSettings>(), "New AmbientOcclusionSettings.asset", icon, null);
}
}

695
ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs


using System.Collections.Generic;
using UnityEngine.Rendering;
using System;
using System.Linq;
using System.Diagnostics;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.Experimental.Rendering.HDPipeline.TilePass;

{
public bool useForwardRenderingOnly = false; // TODO: Currently there is no way to strip the extra forward shaders generated by the shaders compiler, so we can switch dynamically.
public bool useDepthPrepassWithDeferredRendering = false;
public bool renderAlphaTestOnlyInDeferredPrepass = false;
// We have to fall back to forward-only rendering when scene view is using wireframe rendering mode --
// as rendering everything in wireframe + deferred do not play well together

}
}
// This holds all the matrix data we need for rendering, including data from the previous frame
// (which is the main reason why we need to keep them around for a minimum of one frame).
// HDCameras are automatically created & updated from a source camera and will be destroyed if
// not used during a frame.
public class HDCamera
{
public Matrix4x4 viewMatrix;
public Matrix4x4 projMatrix;
public Matrix4x4 nonJitteredProjMatrix;
public Vector4 screenSize;
public Vector4[] frustumPlaneEquations;
public Camera camera;
public Matrix4x4 viewProjMatrix
{
get { return projMatrix * viewMatrix; }
}
public Matrix4x4 nonJitteredViewProjMatrix
{
get { return nonJitteredProjMatrix * viewMatrix; }
}
public bool isFirstFrame
{
get { return m_FirstFrame; }
}
public Vector4 invProjParam
{
// Ref: An Efficient Depth Linearization Method for Oblique View Frustums, Eq. 6.
get { var p = projMatrix; return new Vector4(p.m20 / (p.m00 * p.m23), p.m21 / (p.m11 * p.m23), -1.0f / p.m23, (-p.m22 + p.m20 * p.m02 / p.m00 + p.m21 * p.m12 / p.m11) / p.m23); }
}
// View-projection matrix from the previous frame.
public Matrix4x4 prevViewProjMatrix;
// We need to keep track of these when camera relative rendering is enabled so we can take
// camera translation into account when generating camera motion vectors
public Vector3 cameraPos;
public Vector3 prevCameraPos;
// The only way to reliably keep track of a frame change right now is to compare the frame
// count Unity gives us. We need this as a single camera could be rendered several times per
// frame and some matrices only have to be computed once. Realistically this shouldn't
// happen, but you never know...
int m_LastFrameActive;
// Always true for cameras that just got added to the pool - needed for previous matrices to
// avoid one-frame jumps/hiccups with temporal effects (motion blur, TAA...)
bool m_FirstFrame;
public HDCamera(Camera cam)
{
camera = cam;
frustumPlaneEquations = new Vector4[6];
Reset();
}
public void Update(PostProcessLayer postProcessLayer)
{
// If TAA is enabled projMatrix will hold a jittered projection matrix. The original,
// non-jittered projection matrix can be accessed via nonJitteredProjMatrix.
bool taaEnabled = camera.cameraType == CameraType.Game
&& Utilities.IsTemporalAntialiasingActive(postProcessLayer);
Matrix4x4 nonJitteredCameraProj = camera.projectionMatrix;
Matrix4x4 cameraProj = taaEnabled
? postProcessLayer.temporalAntialiasing.GetJitteredProjectionMatrix(camera)
: nonJitteredCameraProj;
// The actual projection matrix used in shaders is actually massaged a bit to work across all platforms
// (different Z value ranges etc.)
Matrix4x4 gpuProj = GL.GetGPUProjectionMatrix(cameraProj, true); // Had to change this from 'false'
Matrix4x4 gpuView = camera.worldToCameraMatrix;
Matrix4x4 gpuNonJitteredProj = GL.GetGPUProjectionMatrix(nonJitteredCameraProj, true);
Vector3 pos = camera.transform.position;
if (ShaderConfig.s_CameraRelativeRendering != 0)
{
// Zero out the translation component.
gpuView.SetColumn(3, new Vector4(0, 0, 0, 1));
}
Matrix4x4 gpuVP = gpuNonJitteredProj * gpuView;
// A camera could be rendered multiple times per frame, only updates the previous view proj & pos if needed
if (m_LastFrameActive != Time.frameCount)
{
if (m_FirstFrame)
{
prevCameraPos = pos;
prevViewProjMatrix = gpuVP;
}
else
{
prevCameraPos = cameraPos;
prevViewProjMatrix = nonJitteredViewProjMatrix;
}
m_FirstFrame = false;
}
viewMatrix = gpuView;
projMatrix = gpuProj;
nonJitteredProjMatrix = gpuNonJitteredProj;
cameraPos = pos;
screenSize = new Vector4(camera.pixelWidth, camera.pixelHeight, 1.0f / camera.pixelWidth, 1.0f / camera.pixelHeight);
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(viewProjMatrix);
for (int i = 0; i < 6; i++)
{
frustumPlaneEquations[i] = new Vector4(planes[i].normal.x, planes[i].normal.y, planes[i].normal.z, planes[i].distance);
}
m_LastFrameActive = Time.frameCount;
}
public void Reset()
{
m_LastFrameActive = -1;
m_FirstFrame = true;
}
static Dictionary<Camera, HDCamera> m_Cameras = new Dictionary<Camera, HDCamera>();
static List<Camera> m_Cleanup = new List<Camera>(); // Recycled to reduce GC pressure
// Grab the HDCamera tied to a given Camera and update it.
public static HDCamera Get(Camera camera, PostProcessLayer postProcessLayer)
{
HDCamera hdcam;
if (!m_Cameras.TryGetValue(camera, out hdcam))
{
hdcam = new HDCamera(camera);
m_Cameras.Add(camera, hdcam);
}
hdcam.Update(postProcessLayer);
return hdcam;
}
// Look for any camera that hasn't been used in the last frame and remove them for the pool.
public static void CleanUnused()
{
int frameCheck = Time.frameCount - 1;
foreach (var kvp in m_Cameras)
{
if (kvp.Value.m_LastFrameActive != frameCheck)
m_Cleanup.Add(kvp.Key);
}
foreach (var cam in m_Cleanup)
m_Cameras.Remove(cam);
m_Cleanup.Clear();
}
public void SetupGlobalParams(CommandBuffer cmd)
{
cmd.SetGlobalMatrix(HDShaderIDs._ViewMatrix, viewMatrix);
cmd.SetGlobalMatrix(HDShaderIDs._InvViewMatrix, viewMatrix.inverse);
cmd.SetGlobalMatrix(HDShaderIDs._ProjMatrix, projMatrix);
cmd.SetGlobalMatrix(HDShaderIDs._InvProjMatrix, projMatrix.inverse);
cmd.SetGlobalMatrix(HDShaderIDs._NonJitteredViewProjMatrix, nonJitteredViewProjMatrix);
cmd.SetGlobalMatrix(HDShaderIDs._ViewProjMatrix, viewProjMatrix);
cmd.SetGlobalMatrix(HDShaderIDs._InvViewProjMatrix, viewProjMatrix.inverse);
cmd.SetGlobalVector(HDShaderIDs._InvProjParam, invProjParam);
cmd.SetGlobalVector(HDShaderIDs._ScreenSize, screenSize);
cmd.SetGlobalMatrix(HDShaderIDs._PrevViewProjMatrix, prevViewProjMatrix);
cmd.SetGlobalVectorArray(HDShaderIDs._FrustumPlanes, frustumPlaneEquations);
}
// Does not modify global settings. Used for shadows, low res. rendering, etc.
public void OverrideGlobalParams(Material material)
{
material.SetMatrix(HDShaderIDs._ViewMatrix, viewMatrix);
material.SetMatrix(HDShaderIDs._InvViewMatrix, viewMatrix.inverse);
material.SetMatrix(HDShaderIDs._ProjMatrix, projMatrix);
material.SetMatrix(HDShaderIDs._InvProjMatrix, projMatrix.inverse);
material.SetMatrix(HDShaderIDs._NonJitteredViewProjMatrix, nonJitteredViewProjMatrix);
material.SetMatrix(HDShaderIDs._ViewProjMatrix, viewProjMatrix);
material.SetMatrix(HDShaderIDs._InvViewProjMatrix, viewProjMatrix.inverse);
material.SetVector(HDShaderIDs._InvProjParam, invProjParam);
material.SetVector(HDShaderIDs._ScreenSize, screenSize);
material.SetMatrix(HDShaderIDs._PrevViewProjMatrix, prevViewProjMatrix);
material.SetVectorArray(HDShaderIDs._FrustumPlanes, frustumPlaneEquations);
}
public void SetupComputeShader(ComputeShader cs, CommandBuffer cmd)
{
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));
cmd.SetComputeVectorParam(cs, HDShaderIDs._ScreenParams, Shader.GetGlobalVector(HDShaderIDs._ScreenParams));
cmd.SetComputeVectorParam(cs, HDShaderIDs._ZBufferParams, Shader.GetGlobalVector(HDShaderIDs._ZBufferParams));
cmd.SetComputeVectorParam(cs, HDShaderIDs._WorldSpaceCameraPos, Shader.GetGlobalVector(HDShaderIDs._WorldSpaceCameraPos));
}
}
public class GBufferManager
{
public const int MaxGbuffer = 8;

Material m_CopyStencilForSplitLighting;
Material m_CopyStencilForRegularLighting;
GPUCopy m_GPUCopy;
// Various set of material use in render loop
ComputeShader m_SubsurfaceScatteringCS { get { return m_Asset.renderPipelineResources.subsurfaceScatteringCS; } }

Material m_SssHorizontalFilterAndCombinePass;
// <<< Old SSS Model
ComputeShader m_GaussianPyramidCS { get { return m_Asset.renderPipelineResources.gaussianPyramidCS; } }
int m_GaussianPyramidKernel;
ComputeShader m_DepthPyramidCS { get { return m_Asset.renderPipelineResources.depthPyramidCS; } }
int m_DepthPyramidKernel;
Material m_CameraMotionVectorsMaterial;
// Debug material

#if UNITY_EDITOR
#endif
// Various buffer
readonly int m_CameraColorBuffer;

// <<< Old SSS Model
readonly int m_VelocityBuffer;
readonly int m_DistortionBuffer;
readonly int m_GaussianPyramidColorBuffer;
readonly int m_DepthPyramidBuffer;
readonly int m_DeferredShadowBuffer;

// <<< Old SSS Model
readonly RenderTargetIdentifier m_VelocityBufferRT;
readonly RenderTargetIdentifier m_DistortionBufferRT;
readonly RenderTargetIdentifier m_GaussianPyramidColorBufferRT;
readonly RenderTargetIdentifier m_DepthPyramidBufferRT;
RenderTextureDescriptor m_GaussianPyramidColorBufferDesc;
RenderTextureDescriptor m_DepthPyramidBufferDesc;
readonly RenderTargetIdentifier m_DeferredShadowBufferRT;

private RenderTargetIdentifier m_CameraDepthBufferCopyRT;
private RenderTargetIdentifier m_CameraStencilBufferCopyRT;
private RenderTargetIdentifier m_HTileRT;
// Post-processing context and screen-space effects (recycled on every frame to avoid GC alloc)
readonly PostProcessRenderContext m_PostProcessContext;
readonly ScreenSpaceAmbientOcclusionEffect m_SsaoEffect;

All = 255 // 0xFF - 8 bit
}
RenderStateBlock m_DepthStateOpaque;
RenderStateBlock m_DepthStateOpaqueWithPrepass;
// Detect when windows size is changing
int m_CurrentWidth;
int m_CurrentHeight;

// Debugging
MaterialPropertyBlock m_SharedPropertyBlock = new MaterialPropertyBlock();
DebugDisplaySettings m_DebugDisplaySettings = new DebugDisplaySettings();
static DebugDisplaySettings s_NeutraDebugDisplaySettings = new DebugDisplaySettings();
static DebugDisplaySettings s_NeutralDebugDisplaySettings = new DebugDisplaySettings();
DebugDisplaySettings m_CurrentDebugDisplaySettings = null;
private int m_DebugFullScreenTempRT;

public HDRenderPipeline(HDRenderPipelineAsset asset)
{
m_Asset = asset;
m_GPUCopy = new GPUCopy(asset.renderPipelineResources.copyChannelCS);
m_MaterialList = Utilities.GetRenderPipelineMaterialList();
m_MaterialList = CoreUtils.GetRenderPipelineMaterialList();
// Find first material that have non 0 Gbuffer count and assign it as deferredMaterial
m_DeferredMaterial = null;
foreach (RenderPipelineMaterial material in m_MaterialList)

CreateSssMaterials(sssSettings.useDisneySSS);
m_CopyStencilForSplitLighting = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/CopyStencilBuffer");
m_CopyStencilForSplitLighting = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/CopyStencilBuffer");
m_CopyStencilForRegularLighting = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/CopyStencilBuffer");
m_CopyStencilForRegularLighting = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/CopyStencilBuffer");
m_CameraMotionVectorsMaterial = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/CameraMotionVectors");
m_CameraMotionVectorsMaterial = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/CameraMotionVectors");
InitializeDebugMaterials();

m_DistortionBuffer = HDShaderIDs._DistortionTexture;
m_DistortionBufferRT = new RenderTargetIdentifier(m_DistortionBuffer);
m_GaussianPyramidKernel = m_GaussianPyramidCS.FindKernel("KMain");
m_GaussianPyramidColorBuffer = HDShaderIDs._GaussianPyramidColorTexture;
m_GaussianPyramidColorBufferRT = new RenderTargetIdentifier(m_GaussianPyramidColorBuffer);
m_GaussianPyramidColorBufferDesc = new RenderTextureDescriptor(2, 2, RenderTextureFormat.ARGBHalf, 0)
{
useMipMap = true,
autoGenerateMips = false
};
m_DepthPyramidKernel = m_DepthPyramidCS.FindKernel("KMain");
m_DepthPyramidBuffer = HDShaderIDs._DepthPyramidTexture;
m_DepthPyramidBufferRT = new RenderTargetIdentifier(m_DepthPyramidBuffer);
m_DepthPyramidBufferDesc = new RenderTextureDescriptor(2, 2, RenderTextureFormat.RFloat, 0)
{
useMipMap = true,
autoGenerateMips = false
};
m_DistortionBuffer = HDShaderIDs._DistortionTexture;
m_DistortionBufferRT = new RenderTargetIdentifier(m_DistortionBuffer);
m_DeferredShadowBuffer = HDShaderIDs._DeferredShadowTexture;
m_DeferredShadowBufferRT = new RenderTargetIdentifier(m_DeferredShadowBuffer);

m_DebugDisplaySettings.RegisterDebug();
m_DebugFullScreenTempRT = HDShaderIDs._DebugFullScreenTexture;
InitializeRenderStateBlocks();
RegisterDebug();
}
void RegisterDebug()
{
// These need to be Runtime Only because those values are hold by the HDRenderPipeline asset so if user change them through the editor debug menu they might change the value in the asset without noticing it.
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Forward Only", () => (bool)m_Asset.renderingSettings.useForwardRenderingOnly, (value) => m_Asset.renderingSettings.useForwardRenderingOnly = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Deferred Depth Prepass", () => (bool)m_Asset.renderingSettings.useDepthPrepassWithDeferredRendering, (value) => m_Asset.renderingSettings.useDepthPrepassWithDeferredRendering = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Deferred Depth Prepass ATest Only", () => (bool)m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass, (value) => m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Tile/Cluster", () => (bool)m_Asset.tileSettings.enableTileAndCluster, (value) => m_Asset.tileSettings.enableTileAndCluster = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Big Tile", () => (bool)m_Asset.tileSettings.enableBigTilePrepass, (value) => m_Asset.tileSettings.enableBigTilePrepass = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Cluster", () => (bool)m_Asset.tileSettings.enableClustered, (value) => m_Asset.tileSettings.enableClustered = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Compute Lighting", () => (bool)m_Asset.tileSettings.enableComputeLightEvaluation, (value) => m_Asset.tileSettings.enableComputeLightEvaluation = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Light Classification", () => (bool)m_Asset.tileSettings.enableComputeLightVariants, (value) => m_Asset.tileSettings.enableComputeLightVariants = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Material Classification", () => (bool)m_Asset.tileSettings.enableComputeMaterialVariants, (value) => m_Asset.tileSettings.enableComputeMaterialVariants = (bool)value, DebugItemFlag.RuntimeOnly);
m_DebugViewMaterialGBuffer = Utilities.CreateEngineMaterial(m_Asset.renderPipelineResources.debugViewMaterialGBufferShader);
m_DebugDisplayLatlong = Utilities.CreateEngineMaterial(m_Asset.renderPipelineResources.debugDisplayLatlongShader);
m_DebugFullScreen = Utilities.CreateEngineMaterial(m_Asset.renderPipelineResources.debugFullScreenShader);
#if UNITY_EDITOR
m_ErrorMaterial = Utilities.CreateEngineMaterial("Hidden/InternalErrorShader");
#endif
m_DebugViewMaterialGBuffer = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugViewMaterialGBufferShader);
m_DebugDisplayLatlong = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugDisplayLatlongShader);
m_DebugFullScreen = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugFullScreenShader);
m_ErrorMaterial = CoreUtils.CreateEngineMaterial("Hidden/InternalErrorShader");
}
public void CreateSssMaterials(bool useDisneySSS)

Utilities.Destroy(m_CombineLightingPass);
m_CombineLightingPass = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/CombineLighting");
CoreUtils.Destroy(m_CombineLightingPass);
m_CombineLightingPass = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/CombineLighting");
Utilities.Destroy(m_SssVerticalFilterPass);
m_SssVerticalFilterPass = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/SubsurfaceScattering");
CoreUtils.Destroy(m_SssVerticalFilterPass);
m_SssVerticalFilterPass = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/SubsurfaceScattering");
Utilities.Destroy(m_SssHorizontalFilterAndCombinePass);
m_SssHorizontalFilterAndCombinePass = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/SubsurfaceScattering");
CoreUtils.Destroy(m_SssHorizontalFilterAndCombinePass);
m_SssHorizontalFilterAndCombinePass = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/SubsurfaceScattering");
void InitializeRenderStateBlocks()
{
m_DepthStateOpaque.depthState = new DepthState(true, CompareFunction.LessEqual);
m_DepthStateOpaque.mask = RenderStateMask.Depth;
// When doing a prepass, we don't need to write the depth anymore.
// Moreover, we need to use DepthEqual because for alpha tested materials we don't do the clip in the shader anymore (otherwise HiZ does not work on PS4)
m_DepthStateOpaqueWithPrepass.depthState = new DepthState(false, CompareFunction.Equal);
m_DepthStateOpaqueWithPrepass.mask = RenderStateMask.Depth;
}
public void OnSceneLoad()
{
// Recreate the textures which went NULL

m_MaterialList.ForEach(material => material.Cleanup());
Utilities.Destroy(m_DebugViewMaterialGBuffer);
Utilities.Destroy(m_DebugDisplayLatlong);
Utilities.Destroy(m_DebugFullScreen);
#if UNITY_EDITOR
Utilities.Destroy(m_ErrorMaterial);
#endif
CoreUtils.Destroy(m_DebugViewMaterialGBuffer);
CoreUtils.Destroy(m_DebugDisplayLatlong);
CoreUtils.Destroy(m_DebugFullScreen);
CoreUtils.Destroy(m_ErrorMaterial);
m_SkyManager.Cleanup();

public void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd, SubsurfaceScatteringSettings sssParameters)
{
using (new Utilities.ProfilingSample("Push Global Parameters", cmd))
using (new ProfilingSample(cmd, "Push Global Parameters"))
{
hdCamera.SetupGlobalParams(cmd);

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

{
if (NeedStencilBufferCopy())
{
using (new Utilities.ProfilingSample("Copy StencilBuffer", cmd))
using (new ProfilingSample(cmd, "Copy StencilBuffer"))
Utilities.DrawFullScreen(cmd, m_CopyStencilForSplitLighting, m_CameraStencilBufferCopyRT, m_CameraDepthStencilBufferRT);
Utilities.DrawFullScreen(cmd, m_CopyStencilForRegularLighting, m_CameraStencilBufferCopyRT, m_CameraDepthStencilBufferRT);
CoreUtils.DrawFullScreen(cmd, m_CopyStencilForSplitLighting, m_CameraStencilBufferCopyRT, m_CameraDepthStencilBufferRT);
CoreUtils.DrawFullScreen(cmd, m_CopyStencilForRegularLighting, m_CameraStencilBufferCopyRT, m_CameraDepthStencilBufferRT);
cmd.ClearRandomWriteTargets();
}
}

if (camera.cameraType == CameraType.Reflection || camera.cameraType == CameraType.Preview)
{
// Neutral allow to disable all debug settings
m_CurrentDebugDisplaySettings = s_NeutraDebugDisplaySettings;
m_CurrentDebugDisplaySettings = s_NeutralDebugDisplaySettings;
}
else
{

// 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 Utilities.ProfilingSample("Forward", cmd))
using (new ProfilingSample(cmd, "Forward"))
Utilities.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.ClearColor | ClearFlag.ClearDepth);
ShaderPassName[] arrayShaderPassName = { HDShaderPassNames.m_ForwardName };
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Color | ClearFlag.Depth);
ShaderPassName[] arrayShaderPassName = { HDShaderPassNames.s_ForwardName };
RenderOpaqueRenderList(m_CullResults, camera, renderContext, cmd, arrayShaderPassName);
RenderTransparentRenderList(m_CullResults, camera, renderContext, cmd, arrayShaderPassName);
}

RenderGBuffer(m_CullResults, camera, renderContext, cmd);
// If full forward rendering, we did not do any rendering yet, so don't need to copy the buffer.
// If Deferred then the depth buffer is full (regular GBuffer + ForwardOnly depth prepass are done so we can copy it safely.
if (!m_Asset.renderingSettings.useForwardRenderingOnly)
{
CopyDepthBufferIfNeeded(cmd);
}
// In both forward and deferred, everything opaque should have been rendered at this point so we can safely copy the depth buffer for later processing.
CopyDepthBufferIfNeeded(cmd);
RenderPyramidDepth(camera, cmd);
// Required for the SSS and the shader feature classification pass.
PrepareAndBindStencilTexture(cmd);

}
else
{
using (new Utilities.ProfilingSample("Build Light list and render shadows", cmd))
using (new ProfilingSample(cmd, "Build Light list and render shadows"))
{
// TODO: Everything here (SSAO, Shadow, Build light list, deffered shadow, material and light classification can be parallelize with Async compute)
m_SsaoEffect.Render(ssaoSettingsToUse, this, hdCamera, renderContext, cmd, m_Asset.renderingSettings.useForwardRenderingOnly);

SubsurfaceScatteringPass(hdCamera, cmd, m_Asset.sssSettings);
RenderForward(m_CullResults, camera, renderContext, cmd, true);
#if UNITY_EDITOR
#endif
// If full forward rendering, we did just rendered everything, so we can copy the depth buffer
// If Deferred nothing needs copying anymore.
if (m_Asset.renderingSettings.useForwardRenderingOnly)
{
CopyDepthBufferIfNeeded(cmd);
}
RenderGaussianPyramidColor(camera, cmd);
#if UNITY_EDITOR
#endif
//
// Render volumetric lighting
VolumetricLightingPass(hdCamera, cmd);

if (camera.cameraType == CameraType.Reflection)
{
using (new Utilities.ProfilingSample("Blit to final RT", cmd))
using (new ProfilingSample(cmd, "Blit to final RT"))
{
// Simple blit
cmd.Blit(m_CameraColorBufferRT, BuiltinRenderTextureType.CameraTarget);

renderContext.Submit();
}
void RenderOpaqueRenderList(CullResults cull, Camera camera, ScriptableRenderContext renderContext, CommandBuffer cmd, ShaderPassName passName, RendererConfiguration rendererConfiguration = 0, Material overrideMaterial = null)
void RenderOpaqueRenderList(CullResults cull,
Camera camera,
ScriptableRenderContext renderContext,
CommandBuffer cmd,
ShaderPassName passName,
RendererConfiguration rendererConfiguration = 0,
RenderQueueRange? inRenderQueueRange = null,
RenderStateBlock? stateBlock = null,
Material overrideMaterial = null)
RenderOpaqueRenderList(cull, camera, renderContext, cmd, new ShaderPassName[] { passName }, rendererConfiguration, overrideMaterial);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, new ShaderPassName[] { passName }, rendererConfiguration, inRenderQueueRange, stateBlock, overrideMaterial);
void RenderOpaqueRenderList(CullResults cull, Camera camera, ScriptableRenderContext renderContext, CommandBuffer cmd, ShaderPassName[] passNames, RendererConfiguration rendererConfiguration = 0, Material overrideMaterial = null)
void RenderOpaqueRenderList(CullResults cull,
Camera camera,
ScriptableRenderContext renderContext,
CommandBuffer cmd,
ShaderPassName[] passNames,
RendererConfiguration rendererConfiguration = 0,
RenderQueueRange? inRenderQueueRange = null,
RenderStateBlock? stateBlock = null,
Material overrideMaterial = null)
{
if (!m_CurrentDebugDisplaySettings.renderingDebugSettings.displayOpaqueObjects)
return;

{
drawSettings.SetShaderPassName(i, passNames[i]);
}
var filterSettings = new FilterRenderersSettings(true) {renderQueueRange = RenderQueueRange.opaque};
renderContext.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);
var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = inRenderQueueRange == null ? RenderQueueRange.opaque : inRenderQueueRange.Value };
if(stateBlock == null)
renderContext.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);
else
renderContext.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, stateBlock.Value);
void RenderTransparentRenderList(CullResults cull, Camera camera, ScriptableRenderContext renderContext, CommandBuffer cmd, ShaderPassName passName, RendererConfiguration rendererConfiguration = 0, Material overrideMaterial = null)
void RenderTransparentRenderList( CullResults cull,
Camera camera,
ScriptableRenderContext renderContext,
CommandBuffer cmd,
ShaderPassName passName,
RendererConfiguration rendererConfiguration = 0,
RenderStateBlock? stateBlock = null,
Material overrideMaterial = null)
RenderTransparentRenderList(cull, camera, renderContext, cmd, new ShaderPassName[] { passName }, rendererConfiguration, overrideMaterial);
RenderTransparentRenderList(cull, camera, renderContext, cmd, new ShaderPassName[] { passName }, rendererConfiguration, stateBlock, overrideMaterial);
void RenderTransparentRenderList(CullResults cull, Camera camera, ScriptableRenderContext renderContext, CommandBuffer cmd, ShaderPassName[] passNames, RendererConfiguration rendererConfiguration = 0, Material overrideMaterial = null)
void RenderTransparentRenderList( CullResults cull,
Camera camera,
ScriptableRenderContext renderContext,
CommandBuffer cmd,
ShaderPassName[] passNames,
RendererConfiguration rendererConfiguration = 0,
RenderStateBlock? stateBlock = null,
Material overrideMaterial = null)
{
if (!m_CurrentDebugDisplaySettings.renderingDebugSettings.displayTransparentObjects)
return;

rendererConfiguration = rendererConfiguration,
sorting = { flags = SortFlags.CommonTransparent }
};
for (int i = 0; i < passNames.Length; ++i)
{
drawSettings.SetShaderPassName(i, passNames[i]);

}
var filterSettings = new FilterRenderersSettings(true) {renderQueueRange = RenderQueueRange.transparent};
renderContext.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);
if(stateBlock == null)
renderContext.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);
else
renderContext.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, stateBlock.Value);
// RenderDepthPrepass render both opaque and opaque alpha tested based on engine configuration.
// Forward only renderer: We always render everything
// Deferred renderer: We render a depth prepass only if engine request it. We can decide if we render everything or only opaque alpha tested object.
// Forward opaque with deferred renderer (ForwardOnlyOpaqueDepthOnly pass): We always render everything
void RenderDepthPrepass(CullResults cull, Camera camera, ScriptableRenderContext renderContext, CommandBuffer cmd)
{
// Guidelines: To be able to switch from deferred to forward renderer we need to have forward opaque material with both DepthOnly and ForwardOnlyOpaqueDepthOnly pass.

if (addDepthPrepass == false && addForwardOnlyOpaqueDepthPrepass == false)
return;
using (new Utilities.ProfilingSample(addDepthPrepass ? "Depth Prepass" : "Depth Prepass forward opaque ", cmd))
using (new ProfilingSample(cmd, addDepthPrepass ? "Depth Prepass" : "Depth Prepass forward opaque"))
// TODO: We should sort the Material by opaque then alpha masked Must do opaque then alpha masked for performance
Utilities.SetRenderTarget(cmd, m_CameraDepthStencilBufferRT);
// Default depth prepass (forward and deferred) will render all opaque geometry.
RenderQueueRange renderQueueRange = RenderQueueRange.opaque;
// If we want only alpha tested geometry in prepass for deferred we change the RenderQueueRange
if (!m_Asset.renderingSettings.ShouldUseForwardRenderingOnly() && m_Asset.renderingSettings.useDepthPrepassWithDeferredRendering && m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass)
renderQueueRange = new RenderQueueRange { min = (int)RenderQueue.AlphaTest, max = (int)RenderQueue.GeometryLast - 1 };
// We render first the opaque object as opaque alpha tested are more costly to render and could be reject by early-z (but not Hi-z as it is disable with clip instruction)
// This is handeled automatically with the RenderQueue value (OpaqueAlphaTested have a different value and thus are sorted after Opaque)
CoreUtils.SetRenderTarget(cmd, m_CameraDepthStencilBufferRT);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, addDepthPrepass ? HDShaderPassNames.m_DepthOnlyName : HDShaderPassNames.m_ForwardOnlyOpaqueDepthOnlyName);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, addDepthPrepass ? HDShaderPassNames.s_DepthOnlyName : HDShaderPassNames.s_ForwardOnlyOpaqueDepthOnlyName, 0, renderQueueRange);
// RenderGBuffer do the gbuffer pass. This is solely call with deferred. If we use a depth prepass, then the depth prepass will perform the alpha testing for opaque apha tested and we don't need to do it anymore
// during Gbuffer pass. This is handled in the shader and the depth test (equal and no depth write) is done here.
using (new Utilities.ProfilingSample(m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() ? "GBufferDebugDisplay" : "GBuffer", cmd))
using (new ProfilingSample(cmd, m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() ? "GBufferDebugDisplay" : "GBuffer"))
Utilities.SetRenderTarget(cmd, m_gbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT);
// render opaque objects into GBuffer
RenderOpaqueRenderList(cull, camera, renderContext, cmd, m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() ? HDShaderPassNames.m_GBufferDebugDisplayName : HDShaderPassNames.m_GBufferName, Utilities.kRendererConfigurationBakedLighting);
CoreUtils.SetRenderTarget(cmd, m_gbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT);
// Render opaque objects into GBuffer
if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled())
{
// When doing debug display, the shader has the clip instruction regardless of the depth prepass so we can use regular depth test.
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferDebugDisplayName, HDUtils.k_RendererConfigurationBakedLighting, RenderQueueRange.opaque, m_DepthStateOpaque);
}
else
{
if (m_Asset.renderingSettings.useDepthPrepassWithDeferredRendering)
{
RenderQueueRange rangeOpaqueNoAlphaTest = new RenderQueueRange { min = (int)RenderQueue.Geometry, max = (int)RenderQueue.AlphaTest - 1 };
RenderQueueRange rangeOpaqueAlphaTest = new RenderQueueRange { min = (int)RenderQueue.AlphaTest, max = (int)RenderQueue.GeometryLast - 1 };
// When using depth prepass for opaque alpha test only we need to use regular depth test for normal opaque objects.
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, HDUtils.k_RendererConfigurationBakedLighting, rangeOpaqueNoAlphaTest, m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass ? m_DepthStateOpaque : m_DepthStateOpaqueWithPrepass);
// but for opaque alpha tested object we use a depth equal and no depth write. And we rely on the shader pass GbufferWithDepthPrepass
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferWithPrepassName, HDUtils.k_RendererConfigurationBakedLighting, rangeOpaqueAlphaTest, m_DepthStateOpaqueWithPrepass);
}
else
{
// No depth prepass, use regular depth test - Note that we will render opaque then opaque alpha tested (based on the RenderQueue system)
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, HDUtils.k_RendererConfigurationBakedLighting, RenderQueueRange.opaque, m_DepthStateOpaque);
}
}
using (new Utilities.ProfilingSample("DisplayDebug ViewMaterial", cmd))
using (new ProfilingSample(cmd, "DisplayDebug ViewMaterial"))
using (new Utilities.ProfilingSample("DebugViewMaterialGBuffer", cmd))
using (new ProfilingSample(cmd, "DebugViewMaterialGBuffer"))
Utilities.DrawFullScreen(cmd, m_DebugViewMaterialGBuffer, m_CameraColorBufferRT);
CoreUtils.DrawFullScreen(cmd, m_DebugViewMaterialGBuffer, m_CameraColorBufferRT);
Utilities.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, Utilities.kClearAll, Color.black);
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.All, Color.black);
RenderOpaqueRenderList(cull, hdCamera.camera, renderContext, cmd, HDShaderPassNames.m_ForwardDisplayDebugName, Utilities.kRendererConfigurationBakedLighting);
RenderOpaqueRenderList(cull, hdCamera.camera, renderContext, cmd, HDShaderPassNames.s_ForwardDisplayDebugName, HDUtils.k_RendererConfigurationBakedLighting);
RenderTransparentRenderList(cull, hdCamera.camera, renderContext, cmd, HDShaderPassNames.m_ForwardDisplayDebugName, Utilities.kRendererConfigurationBakedLighting);
RenderTransparentRenderList(cull, hdCamera.camera, renderContext, cmd, HDShaderPassNames.s_ForwardDisplayDebugName, HDUtils.k_RendererConfigurationBakedLighting);
using (new Utilities.ProfilingSample("Blit DebugView Material Debug", cmd))
using (new ProfilingSample(cmd, "Blit DebugView Material Debug"))
{
cmd.Blit(m_CameraColorBufferRT, BuiltinRenderTextureType.CameraTarget);
}

if (!m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission || m_Asset.renderingSettings.ShouldUseForwardRenderingOnly())
return;
using (new Utilities.ProfilingSample("Subsurface Scattering", cmd))
using (new ProfilingSample(cmd, "Subsurface Scattering"))
{
if (sssSettings.useDisneySSS)
{

cmd.SetGlobalTexture(HDShaderIDs._IrradianceSource, m_CameraFilteringBufferRT); // Cannot set a RT on a material
// Combine diffuse and specular lighting into 'm_CameraColorBufferRT'.
Utilities.DrawFullScreen(cmd, m_CombineLightingPass, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
CoreUtils.DrawFullScreen(cmd, m_CombineLightingPass, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
}
else
{

m_SssVerticalFilterPass.SetVectorArray(HDShaderIDs._HalfRcpWeightedVariances, sssParameters.halfRcpWeightedVariances);
// Perform the vertical SSS filtering pass which fills 'm_CameraFilteringBufferRT'.
Utilities.DrawFullScreen(cmd, m_SssVerticalFilterPass, m_CameraFilteringBufferRT, m_CameraDepthStencilBufferRT);
CoreUtils.DrawFullScreen(cmd, m_SssVerticalFilterPass, m_CameraFilteringBufferRT, m_CameraDepthStencilBufferRT);
cmd.SetGlobalTexture(HDShaderIDs._IrradianceSource, m_CameraFilteringBufferRT); // Cannot set a RT on a material
m_SssHorizontalFilterAndCombinePass.SetVectorArray(HDShaderIDs._WorldScales, sssParameters.worldScales);

Utilities.DrawFullScreen(cmd, m_SssHorizontalFilterAndCombinePass, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
CoreUtils.DrawFullScreen(cmd, m_SssHorizontalFilterAndCombinePass, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
}
}
}

string profileName;
if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled())
{
passName = addForwardPass ? HDShaderPassNames.m_ForwardDisplayDebugName : HDShaderPassNames.m_ForwardOnlyOpaqueDisplayDebugName;
passName = addForwardPass ? HDShaderPassNames.s_ForwardDisplayDebugName : HDShaderPassNames.s_ForwardOnlyOpaqueDisplayDebugName;
passName = addForwardPass ? HDShaderPassNames.m_ForwardName : HDShaderPassNames.m_ForwardOnlyOpaqueName;
passName = addForwardPass ? HDShaderPassNames.s_ForwardName : HDShaderPassNames.s_ForwardOnlyOpaqueName;
using (new Utilities.ProfilingSample(profileName, cmd))
using (new ProfilingSample(cmd, profileName))
Utilities.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
ShaderPassName[] arrayNames = { passName, HDShaderPassNames.m_SRPDefaultUnlitName};
ShaderPassName[] arrayNames = { passName, HDShaderPassNames.s_SRPDefaultUnlitName};
RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, arrayNames, Utilities.kRendererConfigurationBakedLighting);
// Forward opaque material always have a prepass (whether or not we use deferred) so we pass the right depth state here.
RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, arrayNames, HDUtils.k_RendererConfigurationBakedLighting, null, m_DepthStateOpaqueWithPrepass);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, arrayNames, Utilities.kRendererConfigurationBakedLighting);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, arrayNames, HDUtils.k_RendererConfigurationBakedLighting);
#if UNITY_EDITOR
[Conditional("DEVELOPMENT_BUILD"), Conditional("UNITY_EDITOR")]
using (new Utilities.ProfilingSample("Render Forward Error", cmd))
using (new ProfilingSample(cmd, "Render Forward Error"))
Utilities.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
ShaderPassName[] arrayNames = { HDShaderPassNames.m_AlwaysName, HDShaderPassNames.m_ForwardBaseName, HDShaderPassNames.m_DeferredName, HDShaderPassNames.m_PrepassBaseName, HDShaderPassNames.m_VertexName, HDShaderPassNames.m_VertexLMRGBMName, HDShaderPassNames.m_VertexLMName };
ShaderPassName[] arrayNames = { HDShaderPassNames.s_AlwaysName, HDShaderPassNames.s_ForwardBaseName, HDShaderPassNames.s_DeferredName, HDShaderPassNames.s_PrepassBaseName, HDShaderPassNames.s_VertexName, HDShaderPassNames.s_VertexLMRGBMName, HDShaderPassNames.s_VertexLMName };
RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, arrayNames, 0, m_ErrorMaterial);
RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, arrayNames, 0, null, null, m_ErrorMaterial);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, arrayNames, 0, m_ErrorMaterial);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, arrayNames, 0, null, m_ErrorMaterial);
#endif
using (new Utilities.ProfilingSample("Velocity", cmd))
using (new ProfilingSample(cmd, "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

m_CameraMotionVectorsMaterial.SetVector(HDShaderIDs._CameraPosDiff, hdcam.prevCameraPos - hdcam.cameraPos);
cmd.GetTemporaryRT(m_VelocityBuffer, w, h, 0, FilterMode.Point, Builtin.GetVelocityBufferFormat(), Builtin.GetVelocityBufferReadWrite());
Utilities.DrawFullScreen(cmd, m_CameraMotionVectorsMaterial, m_VelocityBufferRT, null, 0);
CoreUtils.DrawFullScreen(cmd, m_CameraMotionVectorsMaterial, m_VelocityBufferRT, null, 0);
RenderOpaqueRenderList(cullResults, hdcam.camera, renderContext, cmd, HDShaderPassNames.m_MotionVectorsName, RendererConfiguration.PerObjectMotionVectors);
RenderOpaqueRenderList(cullResults, hdcam.camera, renderContext, cmd, HDShaderPassNames.s_MotionVectorsName, RendererConfiguration.PerObjectMotionVectors);
void RenderGaussianPyramidColor(Camera camera, CommandBuffer cmd)
{
if (!m_CurrentDebugDisplaySettings.renderingDebugSettings.enableGaussianPyramid)
return;
using (new ProfilingSample(cmd, "Gaussian Pyramid Color"))
{
int w = camera.pixelWidth;
int h = camera.pixelHeight;
int size = Mathf.ClosestPowerOfTwo(Mathf.Min(w, h));
// The gaussian pyramid compute works in blocks of 8x8 so make sure the last lod has a
// minimum size of 8x8
int lodCount = Mathf.FloorToInt(Mathf.Log(size, 2f) - 3f);
if (lodCount > HDShaderIDs._GaussianPyramidColorMips.Length)
{
Debug.LogWarningFormat("Cannot compute all mipmaps of the color pyramid, max texture size supported: {0}", (2 << HDShaderIDs._GaussianPyramidColorMips.Length).ToString());
lodCount = HDShaderIDs._GaussianPyramidColorMips.Length;
}
cmd.SetGlobalVector(HDShaderIDs._GaussianPyramidColorMipSize, new Vector4(size, size, lodCount, 0));
cmd.Blit(m_CameraColorBufferRT, m_GaussianPyramidColorBuffer);
var last = m_GaussianPyramidColorBuffer;
for (int i = 0; i < lodCount; i++)
{
size >>= 1;
cmd.GetTemporaryRT(HDShaderIDs._GaussianPyramidColorMips[i + 1], size, size, 0, FilterMode.Bilinear, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear, 1, true);
cmd.SetComputeTextureParam(m_GaussianPyramidCS, m_GaussianPyramidKernel, "_Source", last);
cmd.SetComputeTextureParam(m_GaussianPyramidCS, m_GaussianPyramidKernel, "_Result", HDShaderIDs._GaussianPyramidColorMips[i + 1]);
cmd.SetComputeVectorParam(m_GaussianPyramidCS, "_Size", new Vector4(size, size, 1f / size, 1f / size));
cmd.DispatchCompute(m_GaussianPyramidCS, m_GaussianPyramidKernel, size / 8, size / 8, 1);
cmd.CopyTexture(HDShaderIDs._GaussianPyramidColorMips[i + 1], 0, 0, m_GaussianPyramidColorBufferRT, 0, i + 1);
last = HDShaderIDs._GaussianPyramidColorMips[i + 1];
}
cmd.SetGlobalTexture(HDShaderIDs._GaussianPyramidColorTexture, m_GaussianPyramidColorBuffer);
for (int i = 0; i < lodCount; i++)
cmd.ReleaseTemporaryRT(HDShaderIDs._GaussianPyramidColorMips[i + 1]);
}
}
void RenderPyramidDepth(Camera camera, CommandBuffer cmd)
{
if (!m_CurrentDebugDisplaySettings.renderingDebugSettings.enableGaussianPyramid)
return;
using (new ProfilingSample(cmd, "Pyramid Depth"))
{
int w = camera.pixelWidth;
int h = camera.pixelHeight;
int size = Mathf.ClosestPowerOfTwo(Mathf.Min(w, h));
// The gaussian pyramid compute works in blocks of 8x8 so make sure the last lod has a
// minimum size of 8x8
int lodCount = Mathf.FloorToInt(Mathf.Log(size, 2f) - 3f);
if (lodCount > HDShaderIDs._DepthPyramidMips.Length)
{
Debug.LogWarningFormat("Cannot compute all mipmaps of the depth pyramid, max texture size supported: {0}", (2 << HDShaderIDs._DepthPyramidMips.Length).ToString());
lodCount = HDShaderIDs._DepthPyramidMips.Length;
}
cmd.SetGlobalVector(HDShaderIDs._DepthPyramidMipSize, new Vector4(size, size, lodCount, 0));
cmd.GetTemporaryRT(HDShaderIDs._DepthPyramidMips[0], size, size, 0, FilterMode.Bilinear, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear, 1, true);
m_GPUCopy.SampleCopyChannel_xyzw2x(cmd, GetDepthTexture(), HDShaderIDs._DepthPyramidMips[0], new Vector2(size, size));
cmd.CopyTexture(HDShaderIDs._DepthPyramidMips[0], 0, 0, m_DepthPyramidBuffer, 0, 0);
for (int i = 0; i < lodCount; i++)
{
size >>= 1;
cmd.GetTemporaryRT(HDShaderIDs._DepthPyramidMips[i + 1], size, size, 0, FilterMode.Bilinear, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear, 1, true);
cmd.SetComputeTextureParam(m_DepthPyramidCS, m_DepthPyramidKernel, "_Source", HDShaderIDs._DepthPyramidMips[i]);
cmd.SetComputeTextureParam(m_DepthPyramidCS, m_DepthPyramidKernel, "_Result", HDShaderIDs._DepthPyramidMips[i + 1]);
cmd.SetComputeVectorParam(m_DepthPyramidCS, "_Size", new Vector4(size, size, 1f / size, 1f / size));
cmd.DispatchCompute(m_DepthPyramidCS, m_DepthPyramidKernel, size / 8, size / 8, 1);
cmd.CopyTexture(HDShaderIDs._DepthPyramidMips[i + 1], 0, 0, m_DepthPyramidBufferRT, 0, i + 1);
}
cmd.SetGlobalTexture(HDShaderIDs._DepthPyramidTexture, m_DepthPyramidBuffer);
for (int i = 0; i < lodCount + 1; i++)
cmd.ReleaseTemporaryRT(HDShaderIDs._DepthPyramidMips[i]);
}
}
using (new Utilities.ProfilingSample("Distortion", cmd))
using (new ProfilingSample(cmd, "Distortion"))
{
int w = camera.pixelWidth;
int h = camera.pixelHeight;

cmd.ClearRenderTarget(false, true, Color.black); // TODO: can we avoid this clear for performance ?
// Only transparent object can render distortion vectors
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, HDShaderPassNames.m_DistortionVectorsName);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, HDShaderPassNames.s_DistortionVectorsName);
using (new Utilities.ProfilingSample("Post-processing", cmd))
using (new ProfilingSample(cmd, "Post-processing"))
if (Utilities.IsPostProcessingActive(layer))
if (CoreUtils.IsPostProcessingActive(layer))
{
cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, GetDepthTexture());
cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, m_VelocityBufferRT);

if (camera.camera.cameraType == CameraType.Reflection || camera.camera.cameraType == CameraType.Preview)
return;
using (new Utilities.ProfilingSample("Render Debug", cmd))
using (new ProfilingSample(cmd, "Render Debug"))
Utilities.SetRenderTarget(cmd, BuiltinRenderTextureType.CameraTarget, m_CameraDepthStencilBufferRT);
CoreUtils.SetRenderTarget(cmd, BuiltinRenderTextureType.CameraTarget, m_CameraDepthStencilBufferRT);
// First render full screen debug texture
if (m_CurrentDebugDisplaySettings.fullScreenDebugMode != FullScreenDebugMode.None && m_FullScreenDebugPushed)

m_DebugFullScreen.SetFloat(HDShaderIDs._FullScreenDebugMode, (float)m_CurrentDebugDisplaySettings.fullScreenDebugMode);
Utilities.DrawFullScreen(cmd, m_DebugFullScreen, (RenderTargetIdentifier)BuiltinRenderTextureType.CameraTarget);
CoreUtils.DrawFullScreen(cmd, m_DebugFullScreen, (RenderTargetIdentifier)BuiltinRenderTextureType.CameraTarget);
}
// Then overlays

m_SharedPropertyBlock.SetFloat(HDShaderIDs._Mipmap, lightingDebug.skyReflectionMipmap);
cmd.SetViewport(new Rect(x, y, overlaySize, overlaySize));
cmd.DrawProcedural(Matrix4x4.identity, m_DebugDisplayLatlong, 0, MeshTopology.Triangles, 3, 1, m_SharedPropertyBlock);
Utilities.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, camera.camera.pixelWidth);
HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, camera.camera.pixelWidth);
}
m_LightLoop.RenderDebugOverlay(camera.camera, cmd, m_CurrentDebugDisplaySettings, ref x, ref y, overlaySize, camera.camera.pixelWidth);

void InitAndClearBuffer(HDCamera camera, CommandBuffer cmd)
{
using (new Utilities.ProfilingSample("InitAndClearBuffer", cmd))
using (new ProfilingSample(cmd, "InitAndClearBuffer"))
using (new Utilities.ProfilingSample("InitGBuffers and clear Depth/Stencil", cmd))
using (new ProfilingSample(cmd, "InitGBuffers and clear Depth/Stencil"))
{
// 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).

cmd.GetTemporaryRT(m_CameraSssDiffuseLightingBuffer, w, h, 0, FilterMode.Point, RenderTextureFormat.RGB111110Float, RenderTextureReadWrite.Linear, 1, true); // Enable UAV
cmd.GetTemporaryRT(m_CameraFilteringBuffer, w, h, 0, FilterMode.Point, RenderTextureFormat.RGB111110Float, RenderTextureReadWrite.Linear, 1, true); // Enable UAV
// Color and depth pyramids
int s = Mathf.ClosestPowerOfTwo(Mathf.Min(w, h));
m_GaussianPyramidColorBufferDesc.width = s;
m_GaussianPyramidColorBufferDesc.height = s;
cmd.GetTemporaryRT(m_GaussianPyramidColorBuffer, m_GaussianPyramidColorBufferDesc, FilterMode.Trilinear);
m_DepthPyramidBufferDesc.width = s;
m_DepthPyramidBufferDesc.height = s;
cmd.GetTemporaryRT(m_DepthPyramidBuffer, m_DepthPyramidBufferDesc, FilterMode.Trilinear);
// End
Utilities.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.ClearDepth);
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Depth);
using (new Utilities.ProfilingSample("Clear SSS diffuse target", cmd))
using (new ProfilingSample(cmd, "Clear SSS diffuse target"))
Utilities.SetRenderTarget(cmd, m_CameraSssDiffuseLightingBufferRT, ClearFlag.ClearColor, Color.black);
CoreUtils.SetRenderTarget(cmd, m_CameraSssDiffuseLightingBufferRT, ClearFlag.Color, Color.black);
}
// Old SSS Model >>>

using (new Utilities.ProfilingSample("Clear SSS filtering target", cmd))
using (new ProfilingSample(cmd, "Clear SSS filtering target"))
Utilities.SetRenderTarget(cmd, m_CameraFilteringBuffer, ClearFlag.ClearColor, Color.black);
CoreUtils.SetRenderTarget(cmd, m_CameraFilteringBuffer, ClearFlag.Color, Color.black);
}
}
// <<< Old SSS Model

using (new Utilities.ProfilingSample("Clear stencil texture", cmd))
using (new ProfilingSample(cmd, "Clear stencil texture"))
Utilities.SetRenderTarget(cmd, m_CameraStencilBufferCopyRT, ClearFlag.ClearColor, Color.black);
CoreUtils.SetRenderTarget(cmd, m_CameraStencilBufferCopyRT, ClearFlag.Color, Color.black);
using (new Utilities.ProfilingSample("Clear HTile", cmd))
using (new ProfilingSample(cmd, "Clear HTile"))
Utilities.SetRenderTarget(cmd, m_HTileRT, ClearFlag.ClearColor, Color.black);
CoreUtils.SetRenderTarget(cmd, m_HTileRT, ClearFlag.Color, Color.black);
}
}

// TEMP: As we are in development and have not all the setup pass we still clear the color in emissive buffer and gbuffer, but this will be removed later.
// Clear the HDR target
using (new Utilities.ProfilingSample("Clear HDR target", cmd))
using (new ProfilingSample(cmd, "Clear HDR target"))
Utilities.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.ClearColor, Color.black);
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Color, Color.black);
using (new Utilities.ProfilingSample("Clear GBuffer", cmd))
using (new ProfilingSample(cmd, "Clear GBuffer"))
Utilities.SetRenderTarget(cmd, m_gbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT, ClearFlag.ClearColor, Color.black);
CoreUtils.SetRenderTarget(cmd, m_gbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT, ClearFlag.Color, Color.black);
}
}
// END TEMP

7
ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.asset


renderingSettings:
useForwardRenderingOnly: 0
useDepthPrepassWithDeferredRendering: 0
renderAlphaTestOnlyInDeferredPrepass: 0
texturingModeFlags: 1
transmissionFlags: 5460
texturingModeFlags: 0
transmissionFlags: 5462
- {x: 0, y: 12.031147, z: 0, w: 0}
- {x: 0, y: 8.152544, z: 0, w: 0}
- {x: 0, y: 0.2873168, z: 0, w: 0}
- {x: 0, y: 5, z: 0, w: 0}
- {x: 0, y: 12.031147, z: 0, w: 0}

34
ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.cs


using UnityEngine.Rendering;
using System;
using System.Linq;
using UnityEngine.Rendering.PostProcessing;
#if UNITY_EDITOR
using UnityEditor;
#endif
// This HDRenderPipeline assume linear lighting. Don't work with gamma.
// The HDRenderPipeline assumes linear lighting. Doesn't work with gamma.
#if UNITY_EDITOR
[MenuItem("RenderPipeline/HDRenderPipeline/Create Pipeline Asset", false, 16)]
static void CreateHDRenderPipeline()
HDRenderPipelineAsset()
var instance = CreateInstance<HDRenderPipelineAsset>();
AssetDatabase.CreateAsset(instance, Utilities.GetHDRenderPipelinePath() + "HDRenderPipelineAsset.asset");
// If it exist, load renderPipelineResources
instance.renderPipelineResources = AssetDatabase.LoadAssetAtPath<RenderPipelineResources>(RenderPipelineResources.GetRenderPipelineResourcesPath());
#endif
private HDRenderPipelineAsset()
{ }
protected override IRenderPipeline InternalCreatePipeline()
{

[SerializeField]
private RenderPipelineResources m_RenderPipelineResources;
RenderPipelineResources m_RenderPipelineResources;
public RenderPipelineResources renderPipelineResources
{
get { return m_RenderPipelineResources; }

// NOTE: All those properties are public because of how HDRenderPipelineInspector retrieve those properties via serialization/reflection
// Doing it this way allow to change parameters name and still retrieve correct serialized value
// NOTE: All those properties are public because of how HDRenderPipelineInspector retrieves those properties via serialization/reflection
// Doing it this way allows to change parameters name and still retrieve correct serialized values
// Renderer Settings
public RenderingSettings renderingSettings = new RenderingSettings();

[SerializeField]
Shader m_DefaultShader;
public Material DefaultDiffuseMaterial
public Material defaultDiffuseMaterial
public Shader DefaultShader
public Shader defaultShader
{
get { return m_DefaultShader; }
private set { m_DefaultShader = value; }

{
return null;
}
public void OnValidate()
{

390
ScriptableRenderPipeline/HDRenderPipeline/HDStringConstants.cs


namespace UnityEngine.Experimental.Rendering.HDPipeline
{
static class HDShaderPassNames
public static class HDShaderPassNames
internal static readonly ShaderPassName s_EmptyName = new ShaderPassName("");
internal static readonly ShaderPassName m_ForwardName = new ShaderPassName("Forward");
internal static readonly ShaderPassName m_ForwardDisplayDebugName = new ShaderPassName("ForwardDisplayDebug");
internal static readonly ShaderPassName m_DepthOnlyName = new ShaderPassName("DepthOnly");
internal static readonly ShaderPassName m_ForwardOnlyOpaqueDepthOnlyName = new ShaderPassName("ForwardOnlyOpaqueDepthOnly");
internal static readonly ShaderPassName m_ForwardOnlyOpaqueName = new ShaderPassName("ForwardOnlyOpaque");
internal static readonly ShaderPassName m_ForwardOnlyOpaqueDisplayDebugName = new ShaderPassName("ForwardOnlyOpaqueDisplayDebug");
internal static readonly ShaderPassName m_GBufferName = new ShaderPassName("GBuffer");
internal static readonly ShaderPassName m_GBufferDebugDisplayName = new ShaderPassName("GBufferDebugDisplay");
internal static readonly ShaderPassName m_SRPDefaultUnlitName = new ShaderPassName("SRPDefaultUnlit");
internal static readonly ShaderPassName m_MotionVectorsName = new ShaderPassName("MotionVectors");
internal static readonly ShaderPassName m_DistortionVectorsName = new ShaderPassName("DistortionVectors");
public static readonly ShaderPassName s_EmptyName = new ShaderPassName("");
public static readonly ShaderPassName s_ForwardName = new ShaderPassName("Forward");
public static readonly ShaderPassName s_ForwardDisplayDebugName = new ShaderPassName("ForwardDisplayDebug");
public static readonly ShaderPassName s_DepthOnlyName = new ShaderPassName("DepthOnly");
public static readonly ShaderPassName s_ForwardOnlyOpaqueDepthOnlyName = new ShaderPassName("ForwardOnlyOpaqueDepthOnly");
public static readonly ShaderPassName s_ForwardOnlyOpaqueName = new ShaderPassName("ForwardOnlyOpaque");
public static readonly ShaderPassName s_ForwardOnlyOpaqueDisplayDebugName = new ShaderPassName("ForwardOnlyOpaqueDisplayDebug");
public static readonly ShaderPassName s_GBufferName = new ShaderPassName("GBuffer");
public static readonly ShaderPassName s_GBufferWithPrepassName = new ShaderPassName("GBufferWithPrepass");
public static readonly ShaderPassName s_GBufferDebugDisplayName = new ShaderPassName("GBufferDebugDisplay");
public static readonly ShaderPassName s_SRPDefaultUnlitName = new ShaderPassName("SRPDefaultUnlit");
public static readonly ShaderPassName s_MotionVectorsName = new ShaderPassName("MotionVectors");
public static readonly ShaderPassName s_DistortionVectorsName = new ShaderPassName("DistortionVectors");
internal static readonly ShaderPassName m_AlwaysName = new ShaderPassName("Always");
internal static readonly ShaderPassName m_ForwardBaseName = new ShaderPassName("ForwardBase");
internal static readonly ShaderPassName m_DeferredName = new ShaderPassName("Deferred");
internal static readonly ShaderPassName m_PrepassBaseName = new ShaderPassName("PrepassBase");
internal static readonly ShaderPassName m_VertexName = new ShaderPassName("Vertex");
internal static readonly ShaderPassName m_VertexLMRGBMName = new ShaderPassName("VertexLMRGBM");
internal static readonly ShaderPassName m_VertexLMName = new ShaderPassName("VertexLM");
public static readonly ShaderPassName s_AlwaysName = new ShaderPassName("Always");
public static readonly ShaderPassName s_ForwardBaseName = new ShaderPassName("ForwardBase");
public static readonly ShaderPassName s_DeferredName = new ShaderPassName("Deferred");
public static readonly ShaderPassName s_PrepassBaseName = new ShaderPassName("PrepassBase");
public static readonly ShaderPassName s_VertexName = new ShaderPassName("Vertex");
public static readonly ShaderPassName s_VertexLMRGBMName = new ShaderPassName("VertexLMRGBM");
public static readonly ShaderPassName s_VertexLMName = new ShaderPassName("VertexLM");
// fields names as in the shaders for ease of use... Would be nice to clean this up at some
// point.
static class HDShaderIDs
// fields names as in the shaders for ease of use...
// TODO: Would be nice to clean this up at some point
public static class HDShaderIDs
internal static readonly int _ShadowDatasExp = Shader.PropertyToID("_ShadowDatasExp");
internal static readonly int _ShadowPayloads = Shader.PropertyToID("_ShadowPayloads");
internal static readonly int _ShadowmapExp_VSM_0 = Shader.PropertyToID("_ShadowmapExp_VSM_0");
internal static readonly int _ShadowmapExp_VSM_1 = Shader.PropertyToID("_ShadowmapExp_VSM_1");
internal static readonly int _ShadowmapExp_VSM_2 = Shader.PropertyToID("_ShadowmapExp_VSM_2");
internal static readonly int _ShadowmapExp_PCF = Shader.PropertyToID("_ShadowmapExp_PCF");
public static readonly int _ShadowDatasExp = Shader.PropertyToID("_ShadowDatasExp");
public static readonly int _ShadowPayloads = Shader.PropertyToID("_ShadowPayloads");
public static readonly int _ShadowmapExp_VSM_0 = Shader.PropertyToID("_ShadowmapExp_VSM_0");
public static readonly int _ShadowmapExp_VSM_1 = Shader.PropertyToID("_ShadowmapExp_VSM_1");
public static readonly int _ShadowmapExp_VSM_2 = Shader.PropertyToID("_ShadowmapExp_VSM_2");
public static readonly int _ShadowmapExp_PCF = Shader.PropertyToID("_ShadowmapExp_PCF");
internal static readonly int g_LayeredSingleIdxBuffer = Shader.PropertyToID("g_LayeredSingleIdxBuffer");
internal static readonly int _EnvLightIndexShift = Shader.PropertyToID("_EnvLightIndexShift");
internal static readonly int g_isOrthographic = Shader.PropertyToID("g_isOrthographic");
internal static readonly int g_iNrVisibLights = Shader.PropertyToID("g_iNrVisibLights");
internal static readonly int g_mScrProjection = Shader.PropertyToID("g_mScrProjection");
internal static readonly int g_mInvScrProjection = Shader.PropertyToID("g_mInvScrProjection");
internal static readonly int g_iLog2NumClusters = Shader.PropertyToID("g_iLog2NumClusters");
internal static readonly int g_fNearPlane = Shader.PropertyToID("g_fNearPlane");
internal static readonly int g_fFarPlane = Shader.PropertyToID("g_fFarPlane");
internal static readonly int g_fClustScale = Shader.PropertyToID("g_fClustScale");
internal static readonly int g_fClustBase = Shader.PropertyToID("g_fClustBase");
internal static readonly int g_depth_tex = Shader.PropertyToID("g_depth_tex");
internal static readonly int g_vLayeredLightList = Shader.PropertyToID("g_vLayeredLightList");
internal static readonly int g_LayeredOffset = Shader.PropertyToID("g_LayeredOffset");
internal static readonly int g_vBigTileLightList = Shader.PropertyToID("g_vBigTileLightList");
internal static readonly int g_logBaseBuffer = Shader.PropertyToID("g_logBaseBuffer");
internal static readonly int g_vBoundsBuffer = Shader.PropertyToID("g_vBoundsBuffer");
internal static readonly int _LightVolumeData = Shader.PropertyToID("_LightVolumeData");
internal static readonly int g_data = Shader.PropertyToID("g_data");
internal static readonly int g_mProjection = Shader.PropertyToID("g_mProjection");
internal static readonly int g_mInvProjection = Shader.PropertyToID("g_mInvProjection");
internal static readonly int g_viDimensions = Shader.PropertyToID("g_viDimensions");
internal static readonly int g_vLightList = Shader.PropertyToID("g_vLightList");
public static readonly int g_LayeredSingleIdxBuffer = Shader.PropertyToID("g_LayeredSingleIdxBuffer");
public static readonly int _EnvLightIndexShift = Shader.PropertyToID("_EnvLightIndexShift");
public static readonly int g_isOrthographic = Shader.PropertyToID("g_isOrthographic");
public static readonly int g_iNrVisibLights = Shader.PropertyToID("g_iNrVisibLights");
public static readonly int g_mScrProjection = Shader.PropertyToID("g_mScrProjection");
public static readonly int g_mInvScrProjection = Shader.PropertyToID("g_mInvScrProjection");
public static readonly int g_iLog2NumClusters = Shader.PropertyToID("g_iLog2NumClusters");
public static readonly int g_fNearPlane = Shader.PropertyToID("g_fNearPlane");
public static readonly int g_fFarPlane = Shader.PropertyToID("g_fFarPlane");
public static readonly int g_fClustScale = Shader.PropertyToID("g_fClustScale");
public static readonly int g_fClustBase = Shader.PropertyToID("g_fClustBase");
public static readonly int g_depth_tex = Shader.PropertyToID("g_depth_tex");
public static readonly int g_vLayeredLightList = Shader.PropertyToID("g_vLayeredLightList");
public static readonly int g_LayeredOffset = Shader.PropertyToID("g_LayeredOffset");
public static readonly int g_vBigTileLightList = Shader.PropertyToID("g_vBigTileLightList");
public static readonly int g_logBaseBuffer = Shader.PropertyToID("g_logBaseBuffer");
public static readonly int g_vBoundsBuffer = Shader.PropertyToID("g_vBoundsBuffer");
public static readonly int _LightVolumeData = Shader.PropertyToID("_LightVolumeData");
public static readonly int g_data = Shader.PropertyToID("g_data");
public static readonly int g_mProjection = Shader.PropertyToID("g_mProjection");
public static readonly int g_mInvProjection = Shader.PropertyToID("g_mInvProjection");
public static readonly int g_viDimensions = Shader.PropertyToID("g_viDimensions");
public static readonly int g_vLightList = Shader.PropertyToID("g_vLightList");
internal static readonly int g_BaseFeatureFlags = Shader.PropertyToID("g_BaseFeatureFlags");
internal static readonly int g_TileFeatureFlags = Shader.PropertyToID("g_TileFeatureFlags");
public static readonly int g_BaseFeatureFlags = Shader.PropertyToID("g_BaseFeatureFlags");
public static readonly int g_TileFeatureFlags = Shader.PropertyToID("g_TileFeatureFlags");
internal static readonly int _GBufferTexture0 = Shader.PropertyToID("_GBufferTexture0");
internal static readonly int _GBufferTexture1 = Shader.PropertyToID("_GBufferTexture1");
internal static readonly int _GBufferTexture2 = Shader.PropertyToID("_GBufferTexture2");
internal static readonly int _GBufferTexture3 = Shader.PropertyToID("_GBufferTexture3");
public static readonly int _GBufferTexture0 = Shader.PropertyToID("_GBufferTexture0");
public static readonly int _GBufferTexture1 = Shader.PropertyToID("_GBufferTexture1");
public static readonly int _GBufferTexture2 = Shader.PropertyToID("_GBufferTexture2");
public static readonly int _GBufferTexture3 = Shader.PropertyToID("_GBufferTexture3");
internal static readonly int g_DispatchIndirectBuffer = Shader.PropertyToID("g_DispatchIndirectBuffer");
internal static readonly int g_TileList = Shader.PropertyToID("g_TileList");
internal static readonly int g_NumTiles = Shader.PropertyToID("g_NumTiles");
internal static readonly int g_NumTilesX = Shader.PropertyToID("g_NumTilesX");
public static readonly int g_DispatchIndirectBuffer = Shader.PropertyToID("g_DispatchIndirectBuffer");
public static readonly int g_TileList = Shader.PropertyToID("g_TileList");
public static readonly int g_NumTiles = Shader.PropertyToID("g_NumTiles");
public static readonly int g_NumTilesX = Shader.PropertyToID("g_NumTilesX");
internal static readonly int _NumTiles = Shader.PropertyToID("_NumTiles");
public static readonly int _NumTiles = Shader.PropertyToID("_NumTiles");
internal static readonly int _CookieTextures = Shader.PropertyToID("_CookieTextures");
internal static readonly int _CookieCubeTextures = Shader.PropertyToID("_CookieCubeTextures");
internal static readonly int _EnvTextures = Shader.PropertyToID("_EnvTextures");
internal static readonly int _DirectionalLightDatas = Shader.PropertyToID("_DirectionalLightDatas");
internal static readonly int _DirectionalLightCount = Shader.PropertyToID("_DirectionalLightCount");
internal static readonly int _LightDatas = Shader.PropertyToID("_LightDatas");
internal static readonly int _PunctualLightCount = Shader.PropertyToID("_PunctualLightCount");
internal static readonly int _AreaLightCount = Shader.PropertyToID("_AreaLightCount");
internal static readonly int g_vLightListGlobal = Shader.PropertyToID("g_vLightListGlobal");
internal static readonly int _EnvLightDatas = Shader.PropertyToID("_EnvLightDatas");
internal static readonly int _EnvLightCount = Shader.PropertyToID("_EnvLightCount");
internal static readonly int _ShadowDatas = Shader.PropertyToID("_ShadowDatas");
internal static readonly int _DirShadowSplitSpheres = Shader.PropertyToID("_DirShadowSplitSpheres");
internal static readonly int _NumTileFtplX = Shader.PropertyToID("_NumTileFtplX");
internal static readonly int _NumTileFtplY = Shader.PropertyToID("_NumTileFtplY");
internal static readonly int _NumTileClusteredX = Shader.PropertyToID("_NumTileClusteredX");
internal static readonly int _NumTileClusteredY = Shader.PropertyToID("_NumTileClusteredY");
internal static readonly int g_isLogBaseBufferEnabled = Shader.PropertyToID("g_isLogBaseBufferEnabled");
internal static readonly int g_vLayeredOffsetsBuffer = Shader.PropertyToID("g_vLayeredOffsetsBuffer");
public static readonly int _CookieTextures = Shader.PropertyToID("_CookieTextures");
public static readonly int _CookieCubeTextures = Shader.PropertyToID("_CookieCubeTextures");
public static readonly int _EnvTextures = Shader.PropertyToID("_EnvTextures");
public static readonly int _DirectionalLightDatas = Shader.PropertyToID("_DirectionalLightDatas");
public static readonly int _DirectionalLightCount = Shader.PropertyToID("_DirectionalLightCount");
public static readonly int _LightDatas = Shader.PropertyToID("_LightDatas");
public static readonly int _PunctualLightCount = Shader.PropertyToID("_PunctualLightCount");
public static readonly int _AreaLightCount = Shader.PropertyToID("_AreaLightCount");
public static readonly int g_vLightListGlobal = Shader.PropertyToID("g_vLightListGlobal");
public static readonly int _EnvLightDatas = Shader.PropertyToID("_EnvLightDatas");
public static readonly int _EnvLightCount = Shader.PropertyToID("_EnvLightCount");
public static readonly int _ShadowDatas = Shader.PropertyToID("_ShadowDatas");
public static readonly int _DirShadowSplitSpheres = Shader.PropertyToID("_DirShadowSplitSpheres");
public static readonly int _NumTileFtplX = Shader.PropertyToID("_NumTileFtplX");
public static readonly int _NumTileFtplY = Shader.PropertyToID("_NumTileFtplY");
public static readonly int _NumTileClusteredX = Shader.PropertyToID("_NumTileClusteredX");
public static readonly int _NumTileClusteredY = Shader.PropertyToID("_NumTileClusteredY");
internal static readonly int _ViewTilesFlags = Shader.PropertyToID("_ViewTilesFlags");
internal static readonly int _MousePixelCoord = Shader.PropertyToID("_MousePixelCoord");
public static readonly int g_isLogBaseBufferEnabled = Shader.PropertyToID("g_isLogBaseBufferEnabled");
public static readonly int g_vLayeredOffsetsBuffer = Shader.PropertyToID("g_vLayeredOffsetsBuffer");
internal static readonly int _DebugViewMaterial = Shader.PropertyToID("_DebugViewMaterial");
internal static readonly int _DebugLightingMode = Shader.PropertyToID("_DebugLightingMode");
internal static readonly int _DebugLightingAlbedo = Shader.PropertyToID("_DebugLightingAlbedo");
internal static readonly int _DebugLightingSmoothness = Shader.PropertyToID("_DebugLightingSmoothness");
internal static readonly int _AmbientOcclusionTexture = Shader.PropertyToID("_AmbientOcclusionTexture");
public static readonly int _ViewTilesFlags = Shader.PropertyToID("_ViewTilesFlags");
public static readonly int _MousePixelCoord = Shader.PropertyToID("_MousePixelCoord");
internal static readonly int _UseTileLightList = Shader.PropertyToID("_UseTileLightList");
internal static readonly int _Time = Shader.PropertyToID("_Time");
internal static readonly int _SinTime = Shader.PropertyToID("_SinTime");
internal static readonly int _CosTime = Shader.PropertyToID("_CosTime");
internal static readonly int unity_DeltaTime = Shader.PropertyToID("unity_DeltaTime");
internal static readonly int _EnvLightSkyEnabled = Shader.PropertyToID("_EnvLightSkyEnabled");
internal static readonly int _AmbientOcclusionDirectLightStrenght = Shader.PropertyToID("_AmbientOcclusionDirectLightStrenght");
internal static readonly int _SkyTexture = Shader.PropertyToID("_SkyTexture");
public static readonly int _DebugViewMaterial = Shader.PropertyToID("_DebugViewMaterial");
public static readonly int _DebugLightingMode = Shader.PropertyToID("_DebugLightingMode");
public static readonly int _DebugLightingAlbedo = Shader.PropertyToID("_DebugLightingAlbedo");
public static readonly int _DebugLightingSmoothness = Shader.PropertyToID("_DebugLightingSmoothness");
public static readonly int _AmbientOcclusionTexture = Shader.PropertyToID("_AmbientOcclusionTexture");
internal static readonly int _UseDisneySSS = Shader.PropertyToID("_UseDisneySSS");
internal static readonly int _EnableSSSAndTransmission = Shader.PropertyToID("_EnableSSSAndTransmission");
internal static readonly int _TexturingModeFlags = Shader.PropertyToID("_TexturingModeFlags");
internal static readonly int _TransmissionFlags = Shader.PropertyToID("_TransmissionFlags");
internal static readonly int _ThicknessRemaps = Shader.PropertyToID("_ThicknessRemaps");
internal static readonly int _ShapeParams = Shader.PropertyToID("_ShapeParams");
internal static readonly int _HalfRcpVariancesAndWeights = Shader.PropertyToID("_HalfRcpVariancesAndWeights");
internal static readonly int _TransmissionTints = Shader.PropertyToID("_TransmissionTints");
internal static readonly int specularLightingUAV = Shader.PropertyToID("specularLightingUAV");
internal static readonly int diffuseLightingUAV = Shader.PropertyToID("diffuseLightingUAV");
public static readonly int _UseTileLightList = Shader.PropertyToID("_UseTileLightList");
public static readonly int _Time = Shader.PropertyToID("_Time");
public static readonly int _SinTime = Shader.PropertyToID("_SinTime");
public static readonly int _CosTime = Shader.PropertyToID("_CosTime");
public static readonly int unity_DeltaTime = Shader.PropertyToID("unity_DeltaTime");
public static readonly int _EnvLightSkyEnabled = Shader.PropertyToID("_EnvLightSkyEnabled");
public static readonly int _AmbientOcclusionDirectLightStrenght = Shader.PropertyToID("_AmbientOcclusionDirectLightStrenght");
public static readonly int _SkyTexture = Shader.PropertyToID("_SkyTexture");
internal static readonly int g_TileListOffset = Shader.PropertyToID("g_TileListOffset");
public static readonly int _UseDisneySSS = Shader.PropertyToID("_UseDisneySSS");
public static readonly int _EnableSSSAndTransmission = Shader.PropertyToID("_EnableSSSAndTransmission");
public static readonly int _TexturingModeFlags = Shader.PropertyToID("_TexturingModeFlags");
public static readonly int _TransmissionFlags = Shader.PropertyToID("_TransmissionFlags");
public static readonly int _ThicknessRemaps = Shader.PropertyToID("_ThicknessRemaps");
public static readonly int _ShapeParams = Shader.PropertyToID("_ShapeParams");
public static readonly int _HalfRcpVariancesAndWeights = Shader.PropertyToID("_HalfRcpVariancesAndWeights");
public static readonly int _TransmissionTints = Shader.PropertyToID("_TransmissionTints");
public static readonly int specularLightingUAV = Shader.PropertyToID("specularLightingUAV");
public static readonly int diffuseLightingUAV = Shader.PropertyToID("diffuseLightingUAV");
internal static readonly int _LtcData = Shader.PropertyToID("_LtcData");
internal static readonly int _PreIntegratedFGD = Shader.PropertyToID("_PreIntegratedFGD");
internal static readonly int _LtcGGXMatrix = Shader.PropertyToID("_LtcGGXMatrix");
internal static readonly int _LtcDisneyDiffuseMatrix = Shader.PropertyToID("_LtcDisneyDiffuseMatrix");
internal static readonly int _LtcMultiGGXFresnelDisneyDiffuse = Shader.PropertyToID("_LtcMultiGGXFresnelDisneyDiffuse");
public static readonly int g_TileListOffset = Shader.PropertyToID("g_TileListOffset");
internal static readonly int _MainDepthTexture = Shader.PropertyToID("_MainDepthTexture");
public static readonly int _LtcData = Shader.PropertyToID("_LtcData");
public static readonly int _PreIntegratedFGD = Shader.PropertyToID("_PreIntegratedFGD");
public static readonly int _LtcGGXMatrix = Shader.PropertyToID("_LtcGGXMatrix");
public static readonly int _LtcDisneyDiffuseMatrix = Shader.PropertyToID("_LtcDisneyDiffuseMatrix");
public static readonly int _LtcMultiGGXFresnelDisneyDiffuse = Shader.PropertyToID("_LtcMultiGGXFresnelDisneyDiffuse");
internal static readonly int _DeferredShadowTexture = Shader.PropertyToID("_DeferredShadowTexture");
internal static readonly int _DeferredShadowTextureUAV = Shader.PropertyToID("_DeferredShadowTextureUAV");
internal static readonly int _DirectionalShadowIndex = Shader.PropertyToID("_DirectionalShadowIndex");
public static readonly int _MainDepthTexture = Shader.PropertyToID("_MainDepthTexture");
internal static readonly int unity_OrthoParams = Shader.PropertyToID("unity_OrthoParams");
internal static readonly int _ZBufferParams = Shader.PropertyToID("_ZBufferParams");
internal static readonly int _ScreenParams = Shader.PropertyToID("_ScreenParams");
internal static readonly int _ProjectionParams = Shader.PropertyToID("_ProjectionParams");
internal static readonly int _WorldSpaceCameraPos = Shader.PropertyToID("_WorldSpaceCameraPos");
public static readonly int _DeferredShadowTexture = Shader.PropertyToID("_DeferredShadowTexture");
public static readonly int _DeferredShadowTextureUAV = Shader.PropertyToID("_DeferredShadowTextureUAV");
public static readonly int _DirectionalShadowIndex = Shader.PropertyToID("_DirectionalShadowIndex");
public static readonly int unity_OrthoParams = Shader.PropertyToID("unity_OrthoParams");
public static readonly int _ZBufferParams = Shader.PropertyToID("_ZBufferParams");
public static readonly int _ScreenParams = Shader.PropertyToID("_ScreenParams");
public static readonly int _ProjectionParams = Shader.PropertyToID("_ProjectionParams");
public static readonly int _WorldSpaceCameraPos = Shader.PropertyToID("_WorldSpaceCameraPos");
internal static readonly int _StencilRef = Shader.PropertyToID("_StencilRef");
internal static readonly int _StencilCmp = Shader.PropertyToID("_StencilCmp");
public static readonly int _StencilRef = Shader.PropertyToID("_StencilRef");
public static readonly int _StencilCmp = Shader.PropertyToID("_StencilCmp");
internal static readonly int _SrcBlend = Shader.PropertyToID("_SrcBlend");
internal static readonly int _DstBlend = Shader.PropertyToID("_DstBlend");
public static readonly int _SrcBlend = Shader.PropertyToID("_SrcBlend");
public static readonly int _DstBlend = Shader.PropertyToID("_DstBlend");
internal static readonly int _HTile = Shader.PropertyToID("_HTile");
internal static readonly int _StencilTexture = Shader.PropertyToID("_StencilTexture");
public static readonly int _HTile = Shader.PropertyToID("_HTile");
public static readonly int _StencilTexture = Shader.PropertyToID("_StencilTexture");
internal static readonly int _ViewMatrix = Shader.PropertyToID("_ViewMatrix");
internal static readonly int _InvViewMatrix = Shader.PropertyToID("_InvViewMatrix");
internal static readonly int _ProjMatrix = Shader.PropertyToID("_ProjMatrix");
internal static readonly int _InvProjMatrix = Shader.PropertyToID("_InvProjMatrix");
internal static readonly int _NonJitteredViewProjMatrix = Shader.PropertyToID("_NonJitteredViewProjMatrix");
internal static readonly int _ViewProjMatrix = Shader.PropertyToID("_ViewProjMatrix");
internal static readonly int _InvViewProjMatrix = Shader.PropertyToID("_InvViewProjMatrix");
internal static readonly int _InvProjParam = Shader.PropertyToID("_InvProjParam");
internal static readonly int _ScreenSize = Shader.PropertyToID("_ScreenSize");
internal static readonly int _PrevViewProjMatrix = Shader.PropertyToID("_PrevViewProjMatrix");
internal static readonly int _FrustumPlanes = Shader.PropertyToID("_FrustumPlanes");
public static readonly int _ViewMatrix = Shader.PropertyToID("_ViewMatrix");
public static readonly int _InvViewMatrix = Shader.PropertyToID("_InvViewMatrix");
public static readonly int _ProjMatrix = Shader.PropertyToID("_ProjMatrix");
public static readonly int _InvProjMatrix = Shader.PropertyToID("_InvProjMatrix");
public static readonly int _NonJitteredViewProjMatrix = Shader.PropertyToID("_NonJitteredViewProjMatrix");
public static readonly int _ViewProjMatrix = Shader.PropertyToID("_ViewProjMatrix");
public static readonly int _InvViewProjMatrix = Shader.PropertyToID("_InvViewProjMatrix");
public static readonly int _InvProjParam = Shader.PropertyToID("_InvProjParam");
public static readonly int _ScreenSize = Shader.PropertyToID("_ScreenSize");
public static readonly int _PrevViewProjMatrix = Shader.PropertyToID("_PrevViewProjMatrix");
public static readonly int _FrustumPlanes = Shader.PropertyToID("_FrustumPlanes");
internal static readonly int _DepthTexture = Shader.PropertyToID("_DepthTexture");
internal static readonly int _CameraColorTexture = Shader.PropertyToID("_CameraColorTexture");
internal static readonly int _CameraSssDiffuseLightingBuffer = Shader.PropertyToID("_CameraSssDiffuseLightingTexture");
internal static readonly int _CameraFilteringBuffer = Shader.PropertyToID("_CameraFilteringTexture");
internal static readonly int _IrradianceSource = Shader.PropertyToID("_IrradianceSource");
public static readonly int _DepthTexture = Shader.PropertyToID("_DepthTexture");
public static readonly int _CameraColorTexture = Shader.PropertyToID("_CameraColorTexture");
public static readonly int _CameraSssDiffuseLightingBuffer = Shader.PropertyToID("_CameraSssDiffuseLightingTexture");
public static readonly int _CameraFilteringBuffer = Shader.PropertyToID("_CameraFilteringTexture");
public static readonly int _IrradianceSource = Shader.PropertyToID("_IrradianceSource");
internal static readonly int _VelocityTexture = Shader.PropertyToID("_VelocityTexture");
internal static readonly int _DistortionTexture = Shader.PropertyToID("_DistortionTexture");
internal static readonly int _DebugFullScreenTexture = Shader.PropertyToID("_DebugFullScreenTexture");
public static readonly int _VelocityTexture = Shader.PropertyToID("_VelocityTexture");
public static readonly int _DistortionTexture = Shader.PropertyToID("_DistortionTexture");
public static readonly int _GaussianPyramidColorTexture = Shader.PropertyToID("_GaussianPyramidColorTexture");
public static readonly int _DepthPyramidTexture = Shader.PropertyToID("_PyramidDepthTexture");
public static readonly int _GaussianPyramidColorMipSize = Shader.PropertyToID("_GaussianPyramidColorMipSize");
public static readonly int[] _GaussianPyramidColorMips =
{
Shader.PropertyToID("_GaussianColorMip0"),
Shader.PropertyToID("_GaussianColorMip1"),
Shader.PropertyToID("_GaussianColorMip2"),
Shader.PropertyToID("_GaussianColorMip3"),
Shader.PropertyToID("_GaussianColorMip4"),
Shader.PropertyToID("_GaussianColorMip5"),
Shader.PropertyToID("_GaussianColorMip6"),
Shader.PropertyToID("_GaussianColorMip7"),
Shader.PropertyToID("_GaussianColorMip8"),
Shader.PropertyToID("_GaussianColorMip9"),
Shader.PropertyToID("_GaussianColorMip10"),
Shader.PropertyToID("_GaussianColorMip11"),
Shader.PropertyToID("_GaussianColorMip12"),
Shader.PropertyToID("_GaussianColorMip13"),
Shader.PropertyToID("_GaussianColorMip14"),
};
public static readonly int _DepthPyramidMipSize = Shader.PropertyToID("_PyramidDepthMipSize");
public static readonly int[] _DepthPyramidMips =
{
Shader.PropertyToID("_DepthPyramidMip0"),
Shader.PropertyToID("_DepthPyramidMip1"),
Shader.PropertyToID("_DepthPyramidMip2"),
Shader.PropertyToID("_DepthPyramidMip3"),
Shader.PropertyToID("_DepthPyramidMip4"),
Shader.PropertyToID("_DepthPyramidMip5"),
Shader.PropertyToID("_DepthPyramidMip6"),
Shader.PropertyToID("_DepthPyramidMip7"),
Shader.PropertyToID("_DepthPyramidMip8"),
Shader.PropertyToID("_DepthPyramidMip9"),
Shader.PropertyToID("_DepthPyramidMip10"),
Shader.PropertyToID("_DepthPyramidMip11"),
Shader.PropertyToID("_DepthPyramidMip12"),
Shader.PropertyToID("_DepthPyramidMip13"),
Shader.PropertyToID("_DepthPyramidMip14"),
};
public static readonly int _DebugFullScreenTexture = Shader.PropertyToID("_DebugFullScreenTexture");
internal static readonly int _WorldScales = Shader.PropertyToID("_WorldScales");
internal static readonly int _FilterKernels = Shader.PropertyToID("_FilterKernels");
internal static readonly int _FilterKernelsBasic = Shader.PropertyToID("_FilterKernelsBasic");
internal static readonly int _HalfRcpWeightedVariances = Shader.PropertyToID("_HalfRcpWeightedVariances");
public static readonly int _WorldScales = Shader.PropertyToID("_WorldScales");
public static readonly int _FilterKernels = Shader.PropertyToID("_FilterKernels");
public static readonly int _FilterKernelsBasic = Shader.PropertyToID("_FilterKernelsBasic");
public static readonly int _HalfRcpWeightedVariances = Shader.PropertyToID("_HalfRcpWeightedVariances");
internal static readonly int _CameraPosDiff = Shader.PropertyToID("_CameraPosDiff");
public static readonly int _CameraPosDiff = Shader.PropertyToID("_CameraPosDiff");
internal static readonly int _CameraDepthTexture = Shader.PropertyToID("_CameraDepthTexture");
internal static readonly int _CameraMotionVectorsTexture = Shader.PropertyToID("_CameraMotionVectorsTexture");
internal static readonly int _FullScreenDebugMode = Shader.PropertyToID("_FullScreenDebugMode");
public static readonly int _CameraDepthTexture = Shader.PropertyToID("_CameraDepthTexture");
public static readonly int _CameraMotionVectorsTexture = Shader.PropertyToID("_CameraMotionVectorsTexture");
public static readonly int _FullScreenDebugMode = Shader.PropertyToID("_FullScreenDebugMode");
internal static readonly int _InputCubemap = Shader.PropertyToID("_InputCubemap");
internal static readonly int _Mipmap = Shader.PropertyToID("_Mipmap");
public static readonly int _InputCubemap = Shader.PropertyToID("_InputCubemap");
public static readonly int _Mipmap = Shader.PropertyToID("_Mipmap");
public static readonly int _MaxRadius = Shader.PropertyToID("_MaxRadius");
public static readonly int _ShapeParam = Shader.PropertyToID("_ShapeParam");
public static readonly int _StdDev1 = Shader.PropertyToID("_StdDev1");
public static readonly int _StdDev2 = Shader.PropertyToID("_StdDev2");
public static readonly int _LerpWeight = Shader.PropertyToID("_LerpWeight");
public static readonly int _HalfRcpVarianceAndWeight1 = Shader.PropertyToID("_HalfRcpVarianceAndWeight1");
public static readonly int _HalfRcpVarianceAndWeight2 = Shader.PropertyToID("_HalfRcpVarianceAndWeight2");
public static readonly int _TransmissionTint = Shader.PropertyToID("_TransmissionTint");
public static readonly int _ThicknessRemap = Shader.PropertyToID("_ThicknessRemap");
internal static readonly int _MaxRadius = Shader.PropertyToID("_MaxRadius");
internal static readonly int _ShapeParam = Shader.PropertyToID("_ShapeParam");
internal static readonly int _StdDev1 = Shader.PropertyToID("_StdDev1");
internal static readonly int _StdDev2 = Shader.PropertyToID("_StdDev2");
internal static readonly int _LerpWeight = Shader.PropertyToID("_LerpWeight");
internal static readonly int _HalfRcpVarianceAndWeight1 = Shader.PropertyToID("_HalfRcpVarianceAndWeight1");
internal static readonly int _HalfRcpVarianceAndWeight2 = Shader.PropertyToID("_HalfRcpVarianceAndWeight2");
internal static readonly int _TransmissionTint = Shader.PropertyToID("_TransmissionTint");
internal static readonly int _ThicknessRemap = Shader.PropertyToID("_ThicknessRemap");
public static readonly int _Cubemap = Shader.PropertyToID("_Cubemap");
public static readonly int _SkyParam = Shader.PropertyToID("_SkyParam");
public static readonly int _PixelCoordToViewDirWS = Shader.PropertyToID("_PixelCoordToViewDirWS");
internal static readonly int _Cubemap = Shader.PropertyToID("_Cubemap");
internal static readonly int _SkyParam = Shader.PropertyToID("_SkyParam");
internal static readonly int _PixelCoordToViewDirWS = Shader.PropertyToID("_PixelCoordToViewDirWS");
public static readonly int _GlobalFog_Extinction = Shader.PropertyToID("_GlobalFog_Extinction");
public static readonly int _GlobalFog_Asymmetry = Shader.PropertyToID("_GlobalFog_Asymmetry");
public static readonly int _GlobalFog_Scattering = Shader.PropertyToID("_GlobalFog_Scattering");
internal static readonly int _GlobalFog_Extinction = Shader.PropertyToID("_GlobalFog_Extinction");
internal static readonly int _GlobalFog_Asymmetry = Shader.PropertyToID("_GlobalFog_Asymmetry");
internal static readonly int _GlobalFog_Scattering = Shader.PropertyToID("_GlobalFog_Scattering");
public static readonly int _Size = Shader.PropertyToID("_Size");
public static readonly int _Source4 = Shader.PropertyToID("_Source4");
public static readonly int _Result1 = Shader.PropertyToID("_Result1");
}
}

17
ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/ScreenSpaceAmbientOcclusion.cs


return RenderTextureFormat.Default;
}
public ScreenSpaceAmbientOcclusionEffect()
{}
m_Material = Utilities.CreateEngineMaterial(renderPipelineResources.screenSpaceAmbientOcclusionShader);
m_Material = CoreUtils.CreateEngineMaterial(renderPipelineResources.screenSpaceAmbientOcclusionShader);
m_Material.hideFlags = HideFlags.DontSave;
}

m_Material.SetFloat(Uniforms._Downsample, 1.0f / downsize);
m_Material.SetFloat(Uniforms._SampleCount, settings.sampleCount);
using (new Utilities.ProfilingSample("Screenspace ambient occlusion", cmd))
using (new ProfilingSample(cmd, "Screenspace ambient occlusion"))
Utilities.DrawFullScreen(cmd, m_Material, Uniforms._TempTex1, null, 0);
CoreUtils.DrawFullScreen(cmd, m_Material, Uniforms._TempTex1, null, 0);
Utilities.DrawFullScreen(cmd, m_Material, Uniforms._TempTex2, null, 1);
CoreUtils.DrawFullScreen(cmd, m_Material, Uniforms._TempTex2, null, 1);
Utilities.DrawFullScreen(cmd, m_Material, Uniforms._TempTex1, null, 2);
CoreUtils.DrawFullScreen(cmd, m_Material, Uniforms._TempTex1, null, 2);
Utilities.DrawFullScreen(cmd, m_Material, HDShaderIDs._AmbientOcclusionTexture, null, 3);
CoreUtils.DrawFullScreen(cmd, m_Material, HDShaderIDs._AmbientOcclusionTexture, null, 3);
cmd.ReleaseTemporaryRT(Uniforms._TempTex1);
// Setup texture for lighting pass (automatic of unity)

public void Cleanup()
{
Utilities.Destroy(m_Material);
CoreUtils.Destroy(m_Material);
}
}
}

884
ScriptableRenderPipeline/HDRenderPipeline/Lighting/Editor/HDLightEditor.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
using System.Linq;
namespace UnityEngine.Experimental.Rendering.HDPipeline
namespace UnityEditor.Experimental.Rendering.HDPipeline
// TODO: Simplify this editor once we can target 2018.1
[CanEditMultipleObjects]
[CanEditMultipleObjects]
public class HDLightEditor : Editor
sealed partial class HDLightEditor : LightEditor
// Original light editor
SerializedProperty m_Type;
SerializedProperty m_Range;
SerializedProperty m_SpotAngle;
SerializedProperty m_CookieSize;
SerializedProperty m_Color;
SerializedProperty m_Intensity;
SerializedProperty m_BounceIntensity;
SerializedProperty m_ColorTemperature;
SerializedProperty m_UseColorTemperature;
SerializedProperty m_Cookie;
SerializedProperty m_ShadowsType;
SerializedProperty m_ShadowsStrength;
SerializedProperty m_ShadowsResolution;
SerializedProperty m_ShadowsBias;
SerializedProperty m_ShadowsNormalBias;
SerializedProperty m_ShadowsNearPlane;
SerializedProperty m_Flare;
SerializedProperty m_RenderMode;
SerializedProperty m_CullingMask;
SerializedProperty m_Lightmapping;
SerializedProperty m_AreaSizeX;
SerializedProperty m_AreaSizeY;
SerializedProperty m_BakedShadowRadius;
SerializedProperty m_BakedShadowAngle;
sealed class SerializedBaseData
{
public SerializedProperty type;
public SerializedProperty range;
public SerializedProperty spotAngle;
public SerializedProperty cookie;
public SerializedProperty cookieSize;
public SerializedProperty color;
public SerializedProperty intensity;
public SerializedProperty bounceIntensity;
public SerializedProperty colorTemperature;
public SerializedProperty useColorTemperature;
public SerializedProperty shadowsType;
public SerializedProperty shadowsBias;
public SerializedProperty shadowsNormalBias;
public SerializedProperty shadowsNearPlane;
public SerializedProperty lightmapping;
public SerializedProperty areaSizeX;
public SerializedProperty areaSizeY;
public SerializedProperty bakedShadowRadius;
public SerializedProperty bakedShadowAngle;
}
sealed class SerializedLightData
{
public SerializedProperty spotInnerPercent;
public SerializedProperty lightDimmer;
public SerializedProperty fadeDistance;
public SerializedProperty affectDiffuse;
public SerializedProperty affectSpecular;
public SerializedProperty lightTypeExtent;
public SerializedProperty spotLightShape;
public SerializedProperty shapeLength;
public SerializedProperty shapeWidth;
public SerializedProperty shapeRadius;
public SerializedProperty maxSmoothness;
public SerializedProperty applyRangeAttenuation;
// Editor stuff
public SerializedProperty useOldInspector;
public SerializedProperty showFeatures;
public SerializedProperty showAdditionalSettings;
}
// HD Light editor part
SerializedObject additionalDataSerializedObject;
SerializedObject shadowDataSerializedObject;
sealed class SerializedShadowData
{
public SerializedProperty dimmer;
public SerializedProperty fadeDistance;
public SerializedProperty cascadeCount;
public SerializedProperty cascadeRatios;
public SerializedProperty cascadeBorders;
public SerializedProperty resolution;
}
SerializedProperty m_SpotInnerPercent;
SerializedProperty m_LightDimmer;
SerializedProperty m_FadeDistance;
SerializedProperty m_AffectDiffuse;
SerializedProperty m_AffectSpecular;
SerializedProperty m_LightTypeExtent;
SerializedProperty m_SpotLightShape;
SerializedProperty m_ShapeLength;
SerializedProperty m_ShapeWidth;
SerializedProperty m_ShapeRadius;
SerializedProperty m_MaxSmoothness;
SerializedProperty m_ApplyRangeAttenuation;
SerializedObject m_SerializedAdditionalLightData;
SerializedObject m_SerializedAdditionalShadowData;
// Extra data for GUI only
SerializedProperty m_UseOldInspector;
SerializedProperty m_ShowAdditionalSettings;
SerializedBaseData m_BaseData;
SerializedLightData m_AdditionalLightData;
SerializedShadowData m_AdditionalShadowData;
SerializedProperty m_ShadowDimmer;
SerializedProperty m_ShadowFadeDistance;
SerializedProperty m_ShadowCascadeCount;
SerializedProperty m_ShadowCascadeRatios;
SerializedProperty m_ShadowCascadeBorders;
SerializedProperty m_ShadowResolution;
// Copied over from teh original LightEditor class. Will go away once we can target 2018.1
bool m_TypeIsSame { get { return !m_BaseData.type.hasMultipleDifferentValues; } }
bool m_LightmappingTypeIsSame { get { return !m_BaseData.lightmapping.hasMultipleDifferentValues; } }
bool m_IsCompletelyBaked { get { return m_BaseData.lightmapping.intValue == 2; } }
bool m_IsRealtime { get { return m_BaseData.lightmapping.intValue == 4; } }
Light light { get { return serializedObject.targetObject as Light; } }
Texture m_Cookie { get { return m_BaseData.cookie.objectReferenceValue as Texture; } }
bool m_BakingWarningValue { get { return !UnityEditor.Lightmapping.bakedGI && m_LightmappingTypeIsSame && !m_IsRealtime; } }
bool m_BounceWarningValue
{
get
{
return m_TypeIsSame && (light.type == LightType.Point || light.type == LightType.Spot) &&
m_LightmappingTypeIsSame && m_IsRealtime && !m_BaseData.bounceIntensity.hasMultipleDifferentValues
&& m_BaseData.bounceIntensity.floatValue > 0.0f;
}
}
public bool cookieWarningValue
{
get
{
return m_TypeIsSame && light.type == LightType.Spot &&
!m_BaseData.cookie.hasMultipleDifferentValues && m_Cookie && m_Cookie.wrapMode != TextureWrapMode.Clamp;
}
}
// This enum below is LightType enum + LightTypeExtent enum
public enum LightShape
// LightType + LightTypeExtent combined
enum LightShape
//Area, <= offline type of Unity not dispay in our case but reuse for GI of our area light
//Area, <= offline base type not displayed in our case but used for GI of our area light
// Sphere,
// Disc,
//Sphere,
//Disc,
// LightShape is use for displaying UI only. The processing code must use LightTypeExtent and LightType
// Used for UI only; the processing code must use LightTypeExtent and LightType
private Light light { get { return target as Light; } }
// Note: There is no Lightmapping enum, the code C# side must use int
// Light.h file: int m_Lightmapping; ///< enum { Dynamic=4, Stationary=1, Static=2 }
// Lighting.h file:
// enum LightmapBakeType (not accessible in C#)
//{
// kLightRealtime = 1 << 2, // Light is realtime
// kLightBaked = 1 << 1, // light will always be fully baked
// kLightMixed = 1 << 0, // depends on selected LightmapMixedBakeMode
//};
// This mean that m_Lightmapping.enumValueIndex is enum { Mixed=0, Baked=1, Realtime=2 }
enum LightMappingType
void OnEnable()
Mixed,
Baked,
Realtime
}
// Get & automatically add additional HD data if not present
var lightData = GetAdditionalData<HDAdditionalLightData>();
var shadowData = GetAdditionalData<AdditionalShadowData>();
m_SerializedAdditionalLightData = new SerializedObject(lightData);
m_SerializedAdditionalShadowData = new SerializedObject(shadowData);
protected class Styles
{
public static GUIContent CookieSizeX = new GUIContent("CookieSizeX", "");
public static GUIContent CookieSizeY = new GUIContent("CookieSizeY", "");
public static GUIContent ShapeLengthLine = new GUIContent("Length", "Length of the line light");
public static GUIContent ShapeLengthRect = new GUIContent("SizeX", "SizeX of the rectangle light");
public static GUIContent ShapeWidthRect = new GUIContent("SizeY", "SizeY of the rectangle light");
public static GUIContent ShapeLengthPyramid = new GUIContent("SizeX", "");
public static GUIContent ShapeWidthPyramid = new GUIContent("SizeY", "");
public static GUIContent ShapeLengthBox = new GUIContent("SizeX", "");
public static GUIContent ShapeWidthBox = new GUIContent("SizeY", "");
public static GUIContent MaxSmoothness = new GUIContent("MaxSmoothness", "Very low cost way of faking spherical area lighting. This will modify the roughness of the material lit. This is useful when the specular highlight is too small or too sharp.");
public static GUIContent SpotLightShape = new GUIContent("SpotLightShape", "The shape use for the spotlight. Has an impact on the cookie transformation and light angular attenuation.");
public static GUIContent SpotAngle = new GUIContent("Spot Angle", "Controls the angle in degrees at the base of a Spot light's cone.");
public static GUIContent SpotInnerPercent = new GUIContent("Spot Inner Percent", "Controls size of the angular attenuation in percent of the base angle of the Spot light's cone.");
public static GUIContent Color = new GUIContent("Color", "Controls the color being emitted by the light.");
public static GUIContent Intensity = new GUIContent("Intensity", "Controls the brightness of the light. Light color is multiplied by this value.");
public static GUIContent Range = new GUIContent("Range", "Controls how far the light is emitted from the center of the object.");
public static GUIContent LightmappingMode = new GUIContent("Mode", "Specifies the light mode used to determine if and how a light will be baked. Possible modes are Baked, Mixed, and Realtime.");
public static GUIContent BounceIntensity = new GUIContent("Indirect Multiplier", "Controls the intensity of indirect light being contributed to the scene. A value of 0 will cause Realtime lights to be removed from realtime global illumination and Baked and Mixed lights to no longer emit indirect lighting. Has no effect when both Realtime and Baked Global Illumination are disabled.");
public static GUIContent Cookie = new GUIContent("Cookie", "Specifies the Texture projected by the light. Spotlights require 2D texture and pointlights require texture cube.");
public static GUIContent BakedShadowRadius = new GUIContent("Baked Shadow Radius", "Controls the amount of artificial softening applied to the edges of shadows cast by the Point or Spot light.");
public static GUIContent BakedShadowAngle = new GUIContent("Baked Shadow Angle", "Controls the amount of artificial softening applied to the edges of shadows cast by directional lights.");
// Grab all the serialized data we need
m_BaseData = new SerializedBaseData
{
type = serializedObject.FindProperty("m_Type"),
range = serializedObject.FindProperty("m_Range"),
spotAngle = serializedObject.FindProperty("m_SpotAngle"),
cookie = serializedObject.FindProperty("m_Cookie"),
cookieSize = serializedObject.FindProperty("m_CookieSize"),
color = serializedObject.FindProperty("m_Color"),
intensity = serializedObject.FindProperty("m_Intensity"),
bounceIntensity = serializedObject.FindProperty("m_BounceIntensity"),
colorTemperature = serializedObject.FindProperty("m_ColorTemperature"),
useColorTemperature = serializedObject.FindProperty("m_UseColorTemperature"),
shadowsType = serializedObject.FindProperty("m_Shadows.m_Type"),
shadowsBias = serializedObject.FindProperty("m_Shadows.m_Bias"),
shadowsNormalBias = serializedObject.FindProperty("m_Shadows.m_NormalBias"),
shadowsNearPlane = serializedObject.FindProperty("m_Shadows.m_NearPlane"),
lightmapping = serializedObject.FindProperty("m_Lightmapping"),
areaSizeX = serializedObject.FindProperty("m_AreaSize.x"),
areaSizeY = serializedObject.FindProperty("m_AreaSize.y"),
bakedShadowRadius = serializedObject.FindProperty("m_ShadowRadius"),
bakedShadowAngle = serializedObject.FindProperty("m_ShadowAngle")
};
public static GUIContent ShadowResolution = new GUIContent("Resolution", "Controls the rendered resolution of the shadow maps. A higher resolution will increase the fidelity of shadows at the cost of GPU performance and memory usage.");
public static GUIContent ShadowBias = new GUIContent("Bias", "Controls the distance at which the shadows will be pushed away from the light. Useful for avoiding false self-shadowing artifacts.");
public static GUIContent ShadowNormalBias = new GUIContent("Normal Bias", "Controls distance at which the shadow casting surfaces will be shrunk along the surface normal. Useful for avoiding false self-shadowing artifacts.");
public static GUIContent ShadowNearPlane = new GUIContent("Near Plane", "Controls the value for the near clip plane when rendering shadows. Currently clamped to 0.1 units or 1% of the lights range property, whichever is lower.");
using (var o = new PropertyFetcher<HDAdditionalLightData>(m_SerializedAdditionalLightData))
m_AdditionalLightData = new SerializedLightData
{
spotInnerPercent = o.FindProperty(x => x.m_InnerSpotPercent),
lightDimmer = o.FindProperty(x => x.lightDimmer),
fadeDistance = o.FindProperty(x => x.fadeDistance),
affectDiffuse = o.FindProperty(x => x.affectDiffuse),
affectSpecular = o.FindProperty(x => x.affectSpecular),
lightTypeExtent = o.FindProperty(x => x.lightTypeExtent),
spotLightShape = o.FindProperty(x => x.spotLightShape),
shapeLength = o.FindProperty(x => x.shapeLength),
shapeWidth = o.FindProperty(x => x.shapeWidth),
shapeRadius = o.FindProperty(x => x.shapeRadius),
maxSmoothness = o.FindProperty(x => x.maxSmoothness),
applyRangeAttenuation = o.FindProperty(x => x.applyRangeAttenuation),
// Editor stuff
useOldInspector = o.FindProperty(x => x.useOldInspector),
showFeatures = o.FindProperty(x => x.featuresFoldout),
showAdditionalSettings = o.FindProperty(x => x.showAdditionalSettings)
};
public static GUIContent ShadowCascadeCount = new GUIContent("ShadowCascadeCount", "");
public static GUIContent[] ShadowCascadeRatios = new GUIContent[6] { new GUIContent("Cascade 1"), new GUIContent("Cascade 2"), new GUIContent("Cascade 3"), new GUIContent("Cascade 4"), new GUIContent("Cascade 5"), new GUIContent("Cascade 6") };
// TODO: Review this once AdditionalShadowData is refactored
using (var o = new PropertyFetcher<AdditionalShadowData>(m_SerializedAdditionalShadowData))
m_AdditionalShadowData = new SerializedShadowData
{
dimmer = o.FindProperty(x => x.shadowDimmer),
fadeDistance = o.FindProperty(x => x.shadowFadeDistance),
cascadeCount = o.FindProperty("shadowCascadeCount"),
cascadeRatios = o.FindProperty("shadowCascadeRatios"),
cascadeBorders = o.FindProperty("shadowCascadeBorders"),
resolution = o.FindProperty(x => x.shadowResolution)
};
}
public static GUIContent AffectDiffuse = new GUIContent("AffectDiffuse", "This will disable diffuse lighting for this light. Doesn't save performance, diffuse lighting is still computed.");
public static GUIContent AffectSpecular = new GUIContent("AffectSpecular", "This will disable specular lighting for this light. Doesn't save performance, specular lighting is still computed.");
public static GUIContent FadeDistance = new GUIContent("FadeDistance", "The distance at which the light will smoothly fade before being culled to minimize popping.");
public static GUIContent LightDimmer = new GUIContent("LightDimmer", "Aim to be used with script, timeline or animation. It allows dimming one or multiple lights of heterogeneous intensity easily (without needing to know the intensity of each light).");
public static GUIContent ApplyRangeAttenuation = new GUIContent("ApplyRangeAttenuation", "Allows disabling range attenuation. This is useful indoor (like a room) to avoid having to setup a large range for a light to get correct inverse square attenuation that may leak out of the indoor");
public static GUIContent ShadowFadeDistance = new GUIContent("ShadowFadeDistance", "The shadow will fade at distance ShadowFadeDistance before being culled to minimize popping.");
public static GUIContent ShadowDimmer = new GUIContent("ShadowDimmer", "Aim to be use with script, timeline or animation. It allows dimming one or multiple shadows. This can also be used as an optimization to fit in shadow budget manually and minimize popping.");
public override void OnInspectorGUI()
{
m_SerializedAdditionalLightData.Update();
m_SerializedAdditionalShadowData.Update();
public static GUIContent DisabledLightWarning = new GUIContent("Lighting has been disabled in at least one Scene view. Any changes applied to lights in the Scene will not be updated in these views until Lighting has been enabled again.");
public static GUIContent CookieWarning = new GUIContent("Cookie textures for spot lights must be set to clamp. Repeat is not supported.");
public static GUIContent IndirectBounceShadowWarning = new GUIContent("Realtime indirect bounce shadowing is not supported for Spot and Point lights.");
public static GUIContent BakingWarning = new GUIContent("Light mode is currently overridden to Realtime mode. Enable Baked Global Illumination to use Mixed or Baked light modes.");
// Temporary toggle to go back to the old editor & separated additional datas
bool useOldInspector = m_AdditionalLightData.useOldInspector.boolValue;
public static string lightShapeText = "LightShape";
public static readonly string[] lightShapeNames = Enum.GetNames(typeof(LightShape));
if (GUILayout.Button("Toggle default light editor"))
useOldInspector = !useOldInspector;
public static string lightmappingModeText = "Mode";
public static readonly string[] lightmappingModeNames = Enum.GetNames(typeof(LightMappingType));
}
m_AdditionalLightData.useOldInspector.boolValue = useOldInspector;
static Styles s_Styles;
if (useOldInspector)
{
DrawDefaultInspector();
ApplyAdditionalComponentsVisibility(false);
m_SerializedAdditionalShadowData.ApplyModifiedProperties();
m_SerializedAdditionalLightData.ApplyModifiedProperties();
return;
}
// Should match same colors in GizmoDrawers.cpp!
static Color kGizmoLight = new Color(254 / 255f, 253 / 255f, 136 / 255f, 128 / 255f);
static Color kGizmoDisabledLight = new Color(135 / 255f, 116 / 255f, 50 / 255f, 128 / 255f);
// New editor
ApplyAdditionalComponentsVisibility(true);
CheckStyles();
private bool typeIsSame { get { return !m_Type.hasMultipleDifferentValues; } }
private Texture cookie { get { return m_Cookie.objectReferenceValue as Texture; } }
serializedObject.Update();
private bool lightmappingTypeIsSame { get { return !m_Lightmapping.hasMultipleDifferentValues; } }
ResolveLightShape();
private bool isRealtime { get { return m_Lightmapping.enumValueIndex == (int)LightMappingType.Realtime; } }
DrawFoldout(m_AdditionalLightData.showFeatures, "Features", DrawFeatures);
DrawFoldout(m_BaseData.type, "Shape", DrawShape);
DrawFoldout(m_BaseData.intensity, "Light", DrawLightSettings);
private bool isBakedOrMixed { get { return !isRealtime; } }
if (m_BaseData.shadowsType.enumValueIndex != (int)LightShadows.None)
DrawFoldout(m_BaseData.shadowsType, "Shadows", DrawShadows);
private bool bakingWarningValue { get { return !Lightmapping.bakedGI && lightmappingTypeIsSame && isBakedOrMixed; } }
CoreEditorUtils.DrawSplitter();
EditorGUILayout.Space();
private bool cookieWarningValue
{
get
{
return typeIsSame && light.type == LightType.Spot &&
!m_Cookie.hasMultipleDifferentValues && cookie && cookie.wrapMode != TextureWrapMode.Clamp;
}
}
private bool bounceWarningValue
{
get
{
return typeIsSame && (light.type == LightType.Point || light.type == LightType.Spot) &&
lightmappingTypeIsSame && isRealtime && !m_BounceIntensity.hasMultipleDifferentValues && m_BounceIntensity.floatValue > 0.0f && m_ShadowsType.enumValueIndex != (int)LightShadows.None;
}
m_SerializedAdditionalShadowData.ApplyModifiedProperties();
m_SerializedAdditionalLightData.ApplyModifiedProperties();
serializedObject.ApplyModifiedProperties();
private void OnEnable()
void DrawFoldout(SerializedProperty foldoutProperty, string title, Action func)
m_Type = serializedObject.FindProperty("m_Type");
m_Range = serializedObject.FindProperty("m_Range");
m_SpotAngle = serializedObject.FindProperty("m_SpotAngle");
m_CookieSize = serializedObject.FindProperty("m_CookieSize");
m_Color = serializedObject.FindProperty("m_Color");
m_Intensity = serializedObject.FindProperty("m_Intensity");
m_BounceIntensity = serializedObject.FindProperty("m_BounceIntensity");
m_ColorTemperature = serializedObject.FindProperty("m_ColorTemperature");
m_UseColorTemperature = serializedObject.FindProperty("m_UseColorTemperature");
m_Cookie = serializedObject.FindProperty("m_Cookie");
m_ShadowsType = serializedObject.FindProperty("m_Shadows.m_Type");
m_ShadowsStrength = serializedObject.FindProperty("m_Shadows.m_Strength");
m_ShadowsResolution = serializedObject.FindProperty("m_Shadows.m_Resolution");
m_ShadowsBias = serializedObject.FindProperty("m_Shadows.m_Bias");
m_ShadowsNormalBias = serializedObject.FindProperty("m_Shadows.m_NormalBias");
m_ShadowsNearPlane = serializedObject.FindProperty("m_Shadows.m_NearPlane");
m_Flare = serializedObject.FindProperty("m_Flare");
m_RenderMode = serializedObject.FindProperty("m_RenderMode");
m_CullingMask = serializedObject.FindProperty("m_CullingMask");
m_Lightmapping = serializedObject.FindProperty("m_Lightmapping");
m_AreaSizeX = serializedObject.FindProperty("m_AreaSize.x");
m_AreaSizeY = serializedObject.FindProperty("m_AreaSize.y");
m_BakedShadowRadius = serializedObject.FindProperty("m_ShadowRadius");
m_BakedShadowAngle = serializedObject.FindProperty("m_ShadowAngle");
CoreEditorUtils.DrawSplitter();
// Automatically add HD data if not present
// We need to handle multiSelection. To do this we need to get the array of selection and assign it to additionalDataSerializedObject
// additionalDataSerializedObject must be see as an array of selection in all following operation (this is transparent)
var additionalDatas = this.targets.Select(t => (t as Component).GetComponent<HDAdditionalLightData>()).ToArray();
var shadowDatas = this.targets.Select(t => (t as Component).GetComponent<AdditionalShadowData>()).ToArray();
for (int i = 0; i < additionalDatas.Length; ++i)
{
if (additionalDatas[i] == null)
{
additionalDatas[i] = Undo.AddComponent<HDAdditionalLightData>((targets[i] as Component).gameObject);
}
}
bool state = foldoutProperty.isExpanded;
state = CoreEditorUtils.DrawHeaderFoldout(title, state);
for (int i = 0; i < shadowDatas.Length; ++i)
if (state)
if (shadowDatas[i] == null)
{
shadowDatas[i] = Undo.AddComponent<AdditionalShadowData>((targets[i] as Component).gameObject);
}
EditorGUI.indentLevel++;
func();
EditorGUI.indentLevel--;
GUILayout.Space(2f);
additionalDataSerializedObject = new SerializedObject(additionalDatas);
shadowDataSerializedObject = new SerializedObject(shadowDatas);
// Additional data
m_SpotInnerPercent = additionalDataSerializedObject.FindProperty("m_InnerSpotPercent");
m_LightDimmer = additionalDataSerializedObject.FindProperty("lightDimmer");
m_FadeDistance = additionalDataSerializedObject.FindProperty("fadeDistance");
m_AffectDiffuse = additionalDataSerializedObject.FindProperty("affectDiffuse");
m_AffectSpecular = additionalDataSerializedObject.FindProperty("affectSpecular");
m_LightTypeExtent = additionalDataSerializedObject.FindProperty("lightTypeExtent");
m_SpotLightShape = additionalDataSerializedObject.FindProperty("spotLightShape");
m_ShapeLength = additionalDataSerializedObject.FindProperty("shapeLength");
m_ShapeWidth = additionalDataSerializedObject.FindProperty("shapeWidth");
m_ShapeRadius = additionalDataSerializedObject.FindProperty("shapeRadius");
m_MaxSmoothness = additionalDataSerializedObject.FindProperty("maxSmoothness");
m_ApplyRangeAttenuation = additionalDataSerializedObject.FindProperty("applyRangeAttenuation");
// Editor only
m_UseOldInspector = additionalDataSerializedObject.FindProperty("useOldInspector");
m_ShowAdditionalSettings = additionalDataSerializedObject.FindProperty("showAdditionalSettings");
// Shadow data
m_ShadowDimmer = shadowDataSerializedObject.FindProperty("shadowDimmer");
m_ShadowFadeDistance = shadowDataSerializedObject.FindProperty("shadowFadeDistance");
m_ShadowCascadeCount = shadowDataSerializedObject.FindProperty("shadowCascadeCount");
m_ShadowCascadeRatios = shadowDataSerializedObject.FindProperty("shadowCascadeRatios");
m_ShadowCascadeBorders = shadowDataSerializedObject.FindProperty("shadowCascadeBorders");
m_ShadowResolution = shadowDataSerializedObject.FindProperty("shadowResolution");
foldoutProperty.isExpanded = state;
void ResolveLightShape()
void DrawFeatures()
// When we do multiple selection we must not avoid to chose a type, else it may corrupt light
if (m_Type.hasMultipleDifferentValues)
{
m_LightShape = (LightShape)(-1);
EditorGUILayout.PropertyField(m_AdditionalLightData.showAdditionalSettings);
return;
}
bool disabledScope = m_IsCompletelyBaked
|| m_LightShape == LightShape.Line
|| m_LightShape == LightShape.Rectangle;
if (m_LightTypeExtent.enumValueIndex == (int)LightTypeExtent.Punctual)
{
switch ((LightType)m_Type.enumValueIndex)
{
case LightType.Directional:
m_LightShape = LightShape.Directional;
break;
case LightType.Point:
m_LightShape = LightShape.Point;
break;
case LightType.Spot:
m_LightShape = LightShape.Spot;
break;
}
}
else
using (new EditorGUI.DisabledScope(disabledScope))
switch ((LightTypeExtent)m_LightTypeExtent.enumValueIndex)
{
case LightTypeExtent.Rectangle:
m_LightShape = LightShape.Rectangle;
break;
case LightTypeExtent.Line:
m_LightShape = LightShape.Line;
break;
}
bool shadowsEnabled = EditorGUILayout.Toggle(new GUIContent("Enable Shadows"), m_BaseData.shadowsType.enumValueIndex != 0);
m_BaseData.shadowsType.enumValueIndex = shadowsEnabled ? (int)LightShadows.Hard : (int)LightShadows.None;
void LigthShapeGUI()
void DrawShape()
m_LightShape = (LightShape)EditorGUILayout.Popup(Styles.lightShapeText, (int)m_LightShape, Styles.lightShapeNames);
m_LightShape = (LightShape)EditorGUILayout.Popup(s_Styles.shape, (int)m_LightShape, s_Styles.shapeNames);
// LightShape is HD specific, it need to drive LightType from the original LightType when it make sense, so the GI is still in sync with the light shape
// LightShape is HD specific, it need to drive LightType from the original LightType
// when it make sense, so the GI is still in sync with the light shape
m_Type.enumValueIndex = (int)LightType.Directional;
m_LightTypeExtent.enumValueIndex = (int)LightTypeExtent.Punctual;
m_BaseData.type.enumValueIndex = (int)LightType.Directional;
m_AdditionalLightData.lightTypeExtent.enumValueIndex = (int)LightTypeExtent.Punctual;
m_Type.enumValueIndex = (int)LightType.Point;
m_LightTypeExtent.enumValueIndex = (int)LightTypeExtent.Punctual;
EditorGUILayout.PropertyField(m_MaxSmoothness, Styles.MaxSmoothness);
m_BaseData.type.enumValueIndex = (int)LightType.Point;
m_AdditionalLightData.lightTypeExtent.enumValueIndex = (int)LightTypeExtent.Punctual;
EditorGUILayout.PropertyField(m_AdditionalLightData.maxSmoothness, s_Styles.maxSmoothness);
m_Type.enumValueIndex = (int)LightType.Spot;
m_LightTypeExtent.enumValueIndex = (int)LightTypeExtent.Punctual;
EditorGUILayout.PropertyField(m_SpotLightShape, Styles.SpotLightShape);
//Cone Spot
if (m_SpotLightShape.enumValueIndex == (int)SpotLightShape.Cone)
m_BaseData.type.enumValueIndex = (int)LightType.Spot;
m_AdditionalLightData.lightTypeExtent.enumValueIndex = (int)LightTypeExtent.Punctual;
EditorGUILayout.PropertyField(m_AdditionalLightData.spotLightShape, s_Styles.spotLightShape);
var spotLightShape = (SpotLightShape)m_AdditionalLightData.spotLightShape.enumValueIndex;
// Cone Spot
if (spotLightShape == SpotLightShape.Cone)
EditorGUILayout.Slider(m_SpotAngle, 1f, 179f, Styles.SpotAngle);
EditorGUILayout.Slider(m_SpotInnerPercent, 0f, 100f, Styles.SpotInnerPercent);
EditorGUILayout.Slider(m_BaseData.spotAngle, 0f, 179.9f, s_Styles.spotAngle);
EditorGUILayout.Slider(m_AdditionalLightData.spotInnerPercent, 0f, 100f, s_Styles.spotInnerPercent);
if (m_SpotLightShape.enumValueIndex == (int)SpotLightShape.Pyramid)
else if (spotLightShape == SpotLightShape.Pyramid)
EditorGUILayout.Slider(m_ShapeLength, 0.01f, 10, Styles.ShapeLengthPyramid);
EditorGUILayout.Slider(m_ShapeWidth, 0.01f, 10, Styles.ShapeWidthPyramid);
EditorGUILayout.Slider(m_AdditionalLightData.shapeLength, 0.01f, 10f, s_Styles.shapeLengthPyramid);
EditorGUILayout.Slider(m_AdditionalLightData.shapeWidth, 0.01f, 10f, s_Styles.shapeWidthPyramid);
if (m_SpotLightShape.enumValueIndex == (int)SpotLightShape.Box)
else if (spotLightShape == SpotLightShape.Box)
EditorGUILayout.PropertyField(m_ShapeLength, Styles.ShapeLengthBox);
EditorGUILayout.PropertyField(m_ShapeWidth, Styles.ShapeWidthBox);
EditorGUILayout.PropertyField(m_AdditionalLightData.shapeLength, s_Styles.shapeLengthBox);
EditorGUILayout.PropertyField(m_AdditionalLightData.shapeWidth, s_Styles.shapeWidthBox);
EditorGUILayout.PropertyField(m_MaxSmoothness, Styles.MaxSmoothness);
EditorGUILayout.PropertyField(m_AdditionalLightData.maxSmoothness, s_Styles.maxSmoothness);
//m_Type.enumValueIndex = (int)LightType.Area;
m_Type.enumValueIndex = (int)LightType.Point;
m_LightTypeExtent.enumValueIndex = (int)LightTypeExtent.Rectangle;
EditorGUILayout.PropertyField(m_ShapeLength, Styles.ShapeLengthRect);
EditorGUILayout.PropertyField(m_ShapeWidth, Styles.ShapeWidthRect);
m_AreaSizeX.floatValue = m_ShapeLength.floatValue;
m_AreaSizeY.floatValue = m_ShapeWidth.floatValue;
m_ShadowsType.enumValueIndex = (int)LightShadows.None;
//m_BaseData.type.enumValueIndex = (int)LightType.Area;
m_BaseData.type.enumValueIndex = (int)LightType.Point;
m_AdditionalLightData.lightTypeExtent.enumValueIndex = (int)LightTypeExtent.Rectangle;
EditorGUILayout.PropertyField(m_AdditionalLightData.shapeLength, s_Styles.shapeLengthRect);
EditorGUILayout.PropertyField(m_AdditionalLightData.shapeWidth, s_Styles.shapeWidthRect);
m_BaseData.areaSizeX.floatValue = m_AdditionalLightData.shapeLength.floatValue;
m_BaseData.areaSizeY.floatValue = m_AdditionalLightData.shapeWidth.floatValue;
m_BaseData.shadowsType.enumValueIndex = (int)LightShadows.None;
//m_Type.enumValueIndex = (int)LightType.Area;
m_Type.enumValueIndex = (int)LightType.Point;
m_LightTypeExtent.enumValueIndex = (int)LightTypeExtent.Line;
EditorGUILayout.PropertyField(m_ShapeLength, Styles.ShapeLengthLine);
//m_BaseData.type.enumValueIndex = (int)LightType.Area;
m_BaseData.type.enumValueIndex = (int)LightType.Point;
m_AdditionalLightData.lightTypeExtent.enumValueIndex = (int)LightTypeExtent.Line;
EditorGUILayout.PropertyField(m_AdditionalLightData.shapeLength, s_Styles.shapeLengthLine);
m_AreaSizeX.floatValue = m_ShapeLength.floatValue;
m_AreaSizeY.floatValue = 0.01f;
m_ShadowsType.enumValueIndex = (int)LightShadows.None;
m_BaseData.areaSizeX.floatValue = m_AdditionalLightData.shapeLength.floatValue;
m_BaseData.areaSizeY.floatValue = 0.01f;
m_BaseData.shadowsType.enumValueIndex = (int)LightShadows.None;
break;
case (LightShape)(-1):

}
}
void LightGUI()
void DrawLightSettings()
EditorGUILayout.PropertyField(m_Color, Styles.Color);
EditorGUILayout.PropertyField(m_Intensity, Styles.Intensity);
EditorGUILayout.PropertyField(m_BounceIntensity, Styles.BounceIntensity);
// Indirect shadows warning (Should be removed when we support realtime indirect shadows)
if (bounceWarningValue)
if (GraphicsSettings.lightsUseLinearIntensity && GraphicsSettings.lightsUseColorTemperature)
EditorGUILayout.HelpBox(Styles.IndirectBounceShadowWarning.text, MessageType.Info);
EditorGUILayout.PropertyField(m_BaseData.useColorTemperature, s_Styles.useColorTemperature);
if (m_BaseData.useColorTemperature.boolValue)
{
const float kMinKelvin = 1000f;
const float kMaxKelvin = 20000f;
EditorGUILayout.LabelField(s_Styles.color);
EditorGUI.indentLevel += 1;
EditorGUILayout.PropertyField(m_BaseData.color, s_Styles.colorFilter);
EditorGUILayout.Slider(m_BaseData.colorTemperature, kMinKelvin, kMaxKelvin, s_Styles.colorTemperature);
EditorGUI.indentLevel -= 1;
}
else EditorGUILayout.PropertyField(m_BaseData.color, s_Styles.color);
EditorGUILayout.PropertyField(m_Range, Styles.Range);
else EditorGUILayout.PropertyField(m_BaseData.color, s_Styles.color);
// We need to overwrite the name of the default enum that doesn't make any sense
// EditorGUILayout.PropertyField(m_Lightmapping, Styles.LightmappingMode);
m_Lightmapping.enumValueIndex = EditorGUILayout.Popup(Styles.lightmappingModeText, (int)m_Lightmapping.enumValueIndex, Styles.lightmappingModeNames);
EditorGUILayout.PropertyField(m_BaseData.intensity, s_Styles.intensity);
EditorGUILayout.PropertyField(m_BaseData.bounceIntensity, s_Styles.lightBounceIntensity);
// Indirect shadows warning (Should be removed when we support realtime indirect shadows)
if (m_BounceWarningValue)
EditorGUILayout.HelpBox(s_Styles.indirectBounceShadowWarning.text, MessageType.Info);
EditorGUILayout.PropertyField(m_BaseData.range, s_Styles.range);
EditorGUILayout.PropertyField(m_BaseData.lightmapping, s_Styles.lightmappingMode);
if (bakingWarningValue)
{
EditorGUILayout.HelpBox(Styles.BakingWarning.text, MessageType.Info);
}
if (m_BakingWarningValue)
EditorGUILayout.HelpBox(s_Styles.bakingWarning.text, MessageType.Info);
// no cookie with area light (maybe in future textured area light ?)
if (!(m_LightShape == LightShape.Rectangle) && !(m_LightShape == LightShape.Line))
// No cookie with area light (maybe in future textured area light ?)
if (m_LightShape != LightShape.Rectangle && m_LightShape != LightShape.Line)
EditorGUILayout.PropertyField(m_Cookie, Styles.Cookie);
EditorGUILayout.PropertyField(m_BaseData.cookie, s_Styles.cookie);
// When directional light use a cookie, it can control the size
if (m_LightShape == LightShape.Directional)
{
EditorGUILayout.Slider(m_ShapeLength, 0.01f, 10, Styles.CookieSizeX);
EditorGUILayout.Slider(m_ShapeWidth, 0.01f, 10, Styles.CookieSizeY);
}
// Warn on spotlights if the cookie is set to repeat
{
// warn on spotlights if the cookie is set to repeat
EditorGUILayout.HelpBox(Styles.CookieWarning.text, MessageType.Warning);
}
}
}
EditorGUILayout.HelpBox(s_Styles.cookieWarning.text, MessageType.Warning);
void ShadowsGUI()
{
if (m_ShadowsType.enumValueIndex != (int)LightShadows.None)
{
if (m_Lightmapping.enumValueIndex == (int)LightMappingType.Baked)
{
switch ((LightType)m_Type.enumValueIndex)
{
case LightType.Directional:
EditorGUILayout.PropertyField(m_BakedShadowAngle, Styles.BakedShadowAngle);
break;
case LightType.Spot:
case LightType.Point:
EditorGUILayout.PropertyField(m_BakedShadowRadius, Styles.BakedShadowRadius);
break;
}
}
else
// When directional light use a cookie, it can control the size
if (m_Cookie != null && m_LightShape == LightShape.Directional)
EditorGUILayout.PropertyField(m_ShadowResolution, Styles.ShadowResolution);
EditorGUILayout.Slider(m_ShadowsBias, 0.001f, 1, Styles.ShadowBias);
EditorGUILayout.Slider(m_ShadowsNormalBias, 0.001f, 1, Styles.ShadowNormalBias);
EditorGUILayout.Slider(m_ShadowsNearPlane, 0.01f, 10, Styles.ShadowNearPlane);
EditorGUILayout.Slider(m_AdditionalLightData.shapeLength, 0.01f, 10f, s_Styles.cookieSizeX);
EditorGUILayout.Slider(m_AdditionalLightData.shapeWidth, 0.01f, 10f, s_Styles.cookieSizeY);
}
void ShadowsCascadeGUI()
{
UnityEditor.EditorGUI.BeginChangeCheck();
EditorGUILayout.IntSlider(m_ShadowCascadeCount, 1, 4, Styles.ShadowCascadeCount);
if (UnityEditor.EditorGUI.EndChangeCheck())
if (m_AdditionalLightData.showAdditionalSettings.boolValue)
m_ShadowCascadeRatios.arraySize = m_ShadowCascadeCount.intValue - 1;
m_ShadowCascadeBorders.arraySize = m_ShadowCascadeCount.intValue;
}
for (int i = 0; i < m_ShadowCascadeRatios.arraySize; i++)
{
UnityEditor.EditorGUILayout.Slider(m_ShadowCascadeRatios.GetArrayElementAtIndex(i), 0.0f, 1.0f, Styles.ShadowCascadeRatios[i]);
EditorGUILayout.LabelField("Additional Settings", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_AdditionalLightData.affectDiffuse, s_Styles.affectDiffuse);
EditorGUILayout.PropertyField(m_AdditionalLightData.affectSpecular, s_Styles.affectSpecular);
EditorGUILayout.PropertyField(m_AdditionalLightData.fadeDistance, s_Styles.fadeDistance);
EditorGUILayout.PropertyField(m_AdditionalLightData.lightDimmer, s_Styles.lightDimmer);
EditorGUILayout.PropertyField(m_AdditionalLightData.applyRangeAttenuation, s_Styles.applyRangeAttenuation);
EditorGUI.indentLevel--;
void AdditionalSettingsGUI()
void DrawShadows()
// Currently culling mask is not working with HD
// EditorGUILayout.LabelField(new GUIContent("General"), EditorStyles.boldLabel);
// EditorGUILayout.PropertyField(m_CullingMask);
EditorGUILayout.LabelField(new GUIContent("Light"), EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_AffectDiffuse, Styles.AffectDiffuse);
EditorGUILayout.PropertyField(m_AffectSpecular, Styles.AffectSpecular);
EditorGUILayout.PropertyField(m_FadeDistance, Styles.FadeDistance);
EditorGUILayout.PropertyField(m_LightDimmer, Styles.LightDimmer);
EditorGUILayout.PropertyField(m_ApplyRangeAttenuation, Styles.ApplyRangeAttenuation);
if (m_ShadowsType.enumValueIndex != (int)LightShadows.None && m_Lightmapping.enumValueIndex != (int)LightMappingType.Baked)
if (m_IsCompletelyBaked)
EditorGUILayout.LabelField(new GUIContent("Shadows"), EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_ShadowFadeDistance, Styles.ShadowFadeDistance);
EditorGUILayout.PropertyField(m_ShadowDimmer, Styles.ShadowDimmer);
}
}
public override void OnInspectorGUI()
{
serializedObject.Update();
switch ((LightType)m_BaseData.type.enumValueIndex)
{
case LightType.Directional:
EditorGUILayout.Slider(m_BaseData.bakedShadowAngle, 0f, 90f, s_Styles.bakedShadowAngle);
break;
case LightType.Spot:
case LightType.Point:
EditorGUILayout.PropertyField(m_BaseData.bakedShadowRadius, s_Styles.bakedShadowRadius);
break;
}
// Sanity check
if (additionalDataSerializedObject == null || shadowDataSerializedObject == null)
}
additionalDataSerializedObject.Update();
shadowDataSerializedObject.Update();
EditorGUILayout.PropertyField(m_AdditionalShadowData.resolution, s_Styles.shadowResolution);
EditorGUILayout.Slider(m_BaseData.shadowsBias, 0.001f, 1f, s_Styles.shadowBias);
EditorGUILayout.Slider(m_BaseData.shadowsNormalBias, 0.001f, 1f, s_Styles.shadowNormalBias);
EditorGUILayout.Slider(m_BaseData.shadowsNearPlane, 0.01f, 10f, s_Styles.shadowNearPlane);
ResolveLightShape();
if (m_BaseData.type.enumValueIndex != (int)LightType.Directional)
return;
if (GUILayout.Button("Toggle light editor"))
using (var scope = new EditorGUI.ChangeCheckScope())
m_UseOldInspector.boolValue = !m_UseOldInspector.boolValue;
}
EditorGUILayout.Space();
EditorGUILayout.IntSlider(m_AdditionalShadowData.cascadeCount, 1, 4, s_Styles.shadowCascadeCount);
if (m_UseOldInspector.boolValue)
{
base.DrawDefaultInspector();
ApplyAdditionalComponentsVisibility(false);
serializedObject.ApplyModifiedProperties();
// It is required to save m_UseOldInspector value
additionalDataSerializedObject.ApplyModifiedProperties();
shadowDataSerializedObject.ApplyModifiedProperties(); // Should not be needed but if we do some change, could be, so let it here.
return;
if (scope.changed)
{
int len = m_AdditionalShadowData.cascadeCount.intValue;
m_AdditionalShadowData.cascadeRatios.arraySize = len - 1;
m_AdditionalShadowData.cascadeBorders.arraySize = len;
}
ApplyAdditionalComponentsVisibility(true);
// Light features
EditorGUILayout.LabelField(new GUIContent("Light features"), EditorStyles.boldLabel);
// Do not display option for shadow if we are fully bake
if (m_Lightmapping.enumValueIndex != (int)LightMappingType.Baked)
using (var scope = new EditorGUI.ChangeCheckScope())
if (EditorGUILayout.Toggle(new GUIContent("Enable Shadow"), m_ShadowsType.enumValueIndex != 0))
m_ShadowsType.enumValueIndex = (int)LightShadows.Hard;
else
m_ShadowsType.enumValueIndex = (int)LightShadows.None;
}
// Draw each field first...
int arraySize = m_AdditionalShadowData.cascadeRatios.arraySize;
for (int i = 0; i < arraySize; i++)
EditorGUILayout.Slider(m_AdditionalShadowData.cascadeRatios.GetArrayElementAtIndex(i), 0f, 1f, s_Styles.shadowCascadeRatios[i]);
EditorGUI.indentLevel--;
if (scope.changed)
{
// ...then clamp values to avoid out of bounds cascade ratios
for (int i = 0; i < arraySize; i++)
{
var ratios = m_AdditionalShadowData.cascadeRatios;
var ratioProp = ratios.GetArrayElementAtIndex(i);
float val = ratioProp.floatValue;
// Allow to display the arrow for reduce/expand correctly
EditorGUI.indentLevel = 1;
if (i > 0)
{
var prevRatioProp = ratios.GetArrayElementAtIndex(i - 1);
float prevVal = prevRatioProp.floatValue;
val = Mathf.Max(val, prevVal);
}
// LightShape
EditorGUI.indentLevel--;
EditorLightUtilities.DrawSplitter();
m_Type.isExpanded = EditorLightUtilities.DrawHeaderFoldout("Shape", m_Type.isExpanded);
EditorGUI.indentLevel++;
if (i < arraySize - 1)
{
var nextRatioProp = ratios.GetArrayElementAtIndex(i + 1);
float nextVal = nextRatioProp.floatValue;
val = Mathf.Min(val, nextVal);
}
if (m_Type.isExpanded)
{
LigthShapeGUI();
ratioProp.floatValue = val;
}
}
// Light
EditorLightUtilities.DrawSplitter();
m_Intensity.isExpanded = EditorLightUtilities.DrawHeaderFoldout("Light", m_Intensity.isExpanded);
EditorGUI.indentLevel++;
if (m_Intensity.isExpanded)
if (m_AdditionalLightData.showAdditionalSettings.boolValue)
LightGUI();
EditorGUILayout.LabelField("Additional Settings", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_AdditionalShadowData.fadeDistance, s_Styles.shadowFadeDistance);
EditorGUILayout.PropertyField(m_AdditionalShadowData.dimmer, s_Styles.shadowDimmer);
EditorGUI.indentLevel--;
}
// Shadows
if (m_ShadowsType.enumValueIndex != (int)LightShadows.None)
{
EditorGUI.indentLevel--;
EditorLightUtilities.DrawSplitter();
m_ShadowsType.isExpanded = EditorLightUtilities.DrawHeaderFoldout("Shadow", m_ShadowsType.isExpanded);
EditorGUI.indentLevel++;
// Internal utilities
void ApplyAdditionalComponentsVisibility(bool hide)
{
var flags = hide ? HideFlags.HideInInspector : HideFlags.None;
if (m_ShadowsType.isExpanded)
{
ShadowsGUI();
}
foreach (var t in m_SerializedAdditionalLightData.targetObjects)
((HDAdditionalLightData)t).hideFlags = flags;
// shadow cascade
if (m_Type.enumValueIndex == (int)LightType.Directional && m_Lightmapping.enumValueIndex != (int)LightMappingType.Baked)
{
EditorGUI.indentLevel--;
EditorLightUtilities.DrawSplitter();
m_ShadowCascadeCount.isExpanded = EditorLightUtilities.DrawHeaderFoldout("ShadowCascades", m_ShadowCascadeCount.isExpanded);
EditorGUI.indentLevel++;
foreach (var t in m_SerializedAdditionalShadowData.targetObjects)
((AdditionalShadowData)t).hideFlags = flags;
}
if (m_ShadowCascadeCount.isExpanded)
{
ShadowsCascadeGUI();
}
}
}
void ResolveLightShape()
{
var type = m_BaseData.type;
// AdditionalSettings
EditorGUI.indentLevel--;
EditorLightUtilities.DrawSplitter();
m_ShowAdditionalSettings.boolValue = EditorLightUtilities.DrawHeaderFoldout("Additional Settings", m_ShowAdditionalSettings.boolValue);
EditorGUI.indentLevel++;
if (m_ShowAdditionalSettings.boolValue)
// Special case for multi-selection: don't resolve light shape or it'll corrupt lights
if (type.hasMultipleDifferentValues)
AdditionalSettingsGUI();
m_LightShape = (LightShape)(-1);
return;
EditorGUI.indentLevel = 0; // Reset the value that we have init to 1
var lightTypeExtent = (LightTypeExtent)m_AdditionalLightData.lightTypeExtent.enumValueIndex;
if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.m_SceneLighting == false)
if (lightTypeExtent == LightTypeExtent.Punctual)
EditorGUILayout.HelpBox(Styles.DisabledLightWarning.text, MessageType.Warning);
switch ((LightType)type.enumValueIndex)
{
case LightType.Directional:
m_LightShape = LightShape.Directional;
break;
case LightType.Point:
m_LightShape = LightShape.Point;
break;
case LightType.Spot:
m_LightShape = LightShape.Spot;
break;
}
}
else
{
switch (lightTypeExtent)
{
case LightTypeExtent.Rectangle:
m_LightShape = LightShape.Rectangle;
break;
case LightTypeExtent.Line:
m_LightShape = LightShape.Line;
break;
}
serializedObject.ApplyModifiedProperties();
additionalDataSerializedObject.ApplyModifiedProperties();
shadowDataSerializedObject.ApplyModifiedProperties();
void ApplyAdditionalComponentsVisibility(bool hide)
// TODO: Move this to a generic EditorUtilities class
T[] GetAdditionalData<T>()
where T : Component
var additionalData = light.GetComponent<HDAdditionalLightData>();
var shadowData = light.GetComponent<AdditionalShadowData>();
// Handles multi-selection
var data = targets.Cast<Component>()
.Select(t => t.GetComponent<T>())
.ToArray();
for (int i = 0; i < data.Length; i++)
{
if (data[i] == null)
data[i] = Undo.AddComponent<T>(((Component)targets[i]).gameObject);
}
additionalData.hideFlags = hide ? HideFlags.HideInInspector : HideFlags.None;
shadowData.hideFlags = hide ? HideFlags.HideInInspector : HideFlags.None;
return data;
}
}
}

135
ScriptableRenderPipeline/HDRenderPipeline/Lighting/EditorLightUtilities.cs


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

var nearDiscDistance = Mathf.Cos(Mathf.Deg2Rad * spotlight.spotAngle / 2) * spotlight.shadowNearPlane;
var nearDiscRadius = spotlight.shadowNearPlane * Mathf.Sin(spotlight.spotAngle * Mathf.Deg2Rad * 0.5f);
//Draw Range disc
Handles.Disc(spotlight.gameObject.transform.rotation, spotlight.gameObject.transform.position + spotlight.gameObject.transform.forward * rangeDiscDistance, spotlight.gameObject.transform.forward, rangeDiscRadius, false, 1);
//Draw Lines

public static void DrawArealightGizmo(Light arealight)
{
var RectangleSize = new Vector3(arealight.areaSize.x, arealight.areaSize.y, 0);
Gizmos.matrix = arealight.transform.localToWorldMatrix;
Gizmos.DrawWireCube(Vector3.zero, RectangleSize);

Gizmos.DrawLine(m_transform.position, m_transform.position + m_transform.TransformVector(m_transform.root.up * -gizmoSize / m_transform.localScale.y));
Gizmos.DrawLine(m_transform.position, m_transform.position + m_transform.TransformVector(m_transform.root.right * gizmoSize / m_transform.localScale.x));
Gizmos.DrawLine(m_transform.position, m_transform.position + m_transform.TransformVector(m_transform.root.right * -gizmoSize / m_transform.localScale.x));
}
public static bool DrawHeader(string title, bool activeField)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 16f;
labelRect.xMax -= 20f;
var toggleRect = backgroundRect;
toggleRect.y += 2f;
toggleRect.width = 13f;
toggleRect.height = 13f;
var menuIcon = EditorGUIUtility.isProSkin
? (Texture2D)EditorGUIUtility.Load("Builtin Skins/DarkSkin/Images/pane options.png")
: (Texture2D)EditorGUIUtility.Load("Builtin Skins/LightSkin/Images/pane options.png");
var menuRect = new Rect(labelRect.xMax + 4f, labelRect.y + 4f, menuIcon.width, menuIcon.height);
// Background rect should be full-width
backgroundRect.xMin = 0f;
backgroundRect.width += 4f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
using (new EditorGUI.DisabledScope(!activeField))
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
// Active checkbox
activeField = GUI.Toggle(toggleRect, activeField, GUIContent.none, new GUIStyle("ShurikenCheckMark"));
var e = Event.current;
if (e.type == EventType.MouseDown && backgroundRect.Contains(e.mousePosition) && e.button == 0)
{
activeField = !activeField;
e.Use();
}
EditorGUILayout.Space();
return activeField;
}
public static void DrawHeader(string title)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 16f;
labelRect.xMax -= 20f;
var foldoutRect = backgroundRect;
foldoutRect.y += 1f;
foldoutRect.width = 13f;
foldoutRect.height = 13f;
// Background rect should be full-width
backgroundRect.xMin = 0f;
backgroundRect.width += 4f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
EditorGUILayout.Space();
}
public static void DrawSplitter()
{
EditorGUILayout.Space();
var rect = GUILayoutUtility.GetRect(1f, 1f);
// Splitter rect should be full-width
rect.xMin = 0f;
rect.width += 4f;
if (Event.current.type != EventType.Repaint)
return;
EditorGUI.DrawRect(rect, !EditorGUIUtility.isProSkin
? new Color(0.6f, 0.6f, 0.6f, 1.333f)
: new Color(0.12f, 0.12f, 0.12f, 1.333f));
}
public static bool DrawHeaderFoldout(string title, bool state)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 16f;
labelRect.xMax -= 20f;
var foldoutRect = backgroundRect;
foldoutRect.y += 1f;
foldoutRect.width = 13f;
foldoutRect.height = 13f;
// Background rect should be full-width
backgroundRect.xMin = 0f;
backgroundRect.width += 4f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
// Active checkbox
state = GUI.Toggle(foldoutRect, state, GUIContent.none, EditorStyles.foldout);
var e = Event.current;
if (e.type == EventType.MouseDown && backgroundRect.Contains(e.mousePosition) && e.button == 0)
{
state = !state;
e.Use();
}
return state;
}
}
#endif

2
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/Deferred.compute


#pragma kernel Deferred_Indirect_Fptl_Variant23 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant23 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=23
#pragma kernel Deferred_Indirect_Fptl_Variant24 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant24 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=24
#pragma kernel Deferred_Indirect_Fptl_Variant25 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant25 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=25
#pragma kernel Deferred_Indirect_Fptl_Variant26 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant26 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=26
/* Tag: SUPPORT_COMPUTE_CLUSTER_OPAQUE - Uncomment this if you want to do cluster opaque with compute shader (by default we support only fptl on opaque)
#pragma kernel Deferred_Indirect_Clustered_Variant0 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Clustered_Variant0 USE_CLUSTERED_LIGHTLIST USE_INDIRECT VARIANT=0

#pragma kernel Deferred_Indirect_Clustered_Variant23 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Clustered_Variant23 USE_CLUSTERED_LIGHTLIST USE_INDIRECT VARIANT=23
#pragma kernel Deferred_Indirect_Clustered_Variant24 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Clustered_Variant24 USE_CLUSTERED_LIGHTLIST USE_INDIRECT VARIANT=24
#pragma kernel Deferred_Indirect_Clustered_Variant25 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Clustered_Variant25 USE_CLUSTERED_LIGHTLIST USE_INDIRECT VARIANT=25
#pragma kernel Deferred_Indirect_Clustered_Variant26 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Clustered_Variant26 USE_CLUSTERED_LIGHTLIST USE_INDIRECT VARIANT=26
*/
#define LIGHTLOOP_TILE_PASS 1

23
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/ShadowDispatch.hlsl


// and that on the C# side the shadowContext bindDelegate binds the correct resource to the correct texture id.
#define SHADOW_DISPATCH_USE_CUSTOM_DIRECTIONAL // enables hardcoded resources and algorithm for directional lights
#define SHADOW_DISPATCH_USE_CUSTOM_PUNCTUAL // enables hardcoded resources and algorithm for punctual lights
//#define SHADOW_DISPATCH_USE_SEPARATE_PUNC_ALGOS // enables separate resources and algorithms for spot and point lights
#define SHADOW_DISPATCH_USE_CUSTOM_DIRECTIONAL // enables hardcoded resources and algorithm for directional lights
#define SHADOW_DISPATCH_USE_CUSTOM_PUNCTUAL // enables hardcoded resources and algorithm for punctual lights
//#define SHADOW_DISPATCH_USE_SEPARATE_CASCADE_ALGOS // enables separate cascade sampling variants for each cascade
//#define SHADOW_DISPATCH_USE_SEPARATE_PUNC_ALGOS // enables separate resources and algorithms for spot and point lights
#define SHADOW_DISPATCH_DIR_ALG GPUSHADOWALGORITHM_PCF_TENT_5X5
#define SHADOW_DISPATCH_DIR_ALG GPUSHADOWALGORITHM_PCF_TENT_5X5 // all cascades
#define SHADOW_DISPATCH_DIR_ALG_0 GPUSHADOWALGORITHM_PCF_TENT_7X7 // 1st cascade
#define SHADOW_DISPATCH_DIR_ALG_1 GPUSHADOWALGORITHM_PCF_TENT_5X5 // 2nd cascade
#define SHADOW_DISPATCH_DIR_ALG_2 GPUSHADOWALGORITHM_PCF_TENT_3X3 // 3rd cascade
#define SHADOW_DISPATCH_DIR_ALG_3 GPUSHADOWALGORITHM_PCF_1TAP // 4th cascade
// point
#define SHADOW_DISPATCH_POINT_TEX 3
#define SHADOW_DISPATCH_POINT_SMP 0

{
Texture2DArray tex = shadowContext.tex2DArray[SHADOW_DISPATCH_DIR_TEX];
SamplerComparisonState compSamp = shadowContext.compSamplers[SHADOW_DISPATCH_DIR_SMP];
uint algo = SHADOW_DISPATCH_DIR_ALG;
#ifdef SHADOW_DISPATCH_USE_SEPARATE_CASCADE_ALGOS
uint algo[kMaxShadowCascades] = { SHADOW_DISPATCH_DIR_ALG_0, SHADOW_DISPATCH_DIR_ALG_1, SHADOW_DISPATCH_DIR_ALG_2, SHADOW_DISPATCH_DIR_ALG_3 };
#else
uint algo = SHADOW_DISPATCH_DIR_ALG;
#endif
return EvalShadow_CascadedDepth_Blend( shadowContext, algo, tex, compSamp, positionWS, normalWS, shadowDataIndex, L );
}

#undef SHADOW_DISPATCH_DIR_TEX
#undef SHADOW_DISPATCH_DIR_SMP
#undef SHADOW_DISPATCH_DIR_ALG
#undef SHADOW_DISPATCH_DIR_ALG_0
#undef SHADOW_DISPATCH_DIR_ALG_1
#undef SHADOW_DISPATCH_DIR_ALG_2
#undef SHADOW_DISPATCH_DIR_ALG_3
#undef SHADOW_DISPATCH_POINT_TEX
#undef SHADOW_DISPATCH_POINT_SMP
#undef SHADOW_DISPATCH_POINT_ALG

107
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs


Area = 1 << 9,
Directional = 1 << 10,
Env = 1 << 11,
Sky = 1 << 12 // If adding more light be sure to not overflow LightDefinitions.s_LightFeatureMaskFlags
Sky = 1 << 12,
SSL = 1 << 13 // If adding more light be sure to not overflow LightDefinitions.s_LightFeatureMaskFlags
}
[GenerateHLSL]

public static int s_TileSizeClustered = 32;
// feature variants
public static int s_NumFeatureVariants = 26;
public static int s_NumFeatureVariants = 27;
// Following define the maximum number of bits use in each feature category.
public static uint s_LightFeatureMaskFlags = 0xFF00;

s_TileList = null;
s_TileFeatureFlags = null;
m_DeferredAllMaterialSRT = Utilities.CreateEngineMaterial(m_Resources.deferredShader);
m_DeferredAllMaterialSRT = CoreUtils.CreateEngineMaterial(m_Resources.deferredShader);
m_DeferredAllMaterialSRT.EnableKeyword("LIGHTLOOP_TILE_PASS");
m_DeferredAllMaterialSRT.DisableKeyword("OUTPUT_SPLIT_LIGHTING");
m_DeferredAllMaterialSRT.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.RegularLighting);

m_DeferredAllMaterialMRT = Utilities.CreateEngineMaterial(m_Resources.deferredShader);
m_DeferredAllMaterialMRT = CoreUtils.CreateEngineMaterial(m_Resources.deferredShader);
m_DeferredAllMaterialMRT.EnableKeyword("LIGHTLOOP_TILE_PASS");
m_DeferredAllMaterialMRT.EnableKeyword("OUTPUT_SPLIT_LIGHTING");
m_DeferredAllMaterialMRT.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.SplitLighting);

m_SingleDeferredMaterialSRT = Utilities.CreateEngineMaterial(m_Resources.deferredShader);
m_SingleDeferredMaterialSRT = CoreUtils.CreateEngineMaterial(m_Resources.deferredShader);
m_SingleDeferredMaterialSRT.EnableKeyword("LIGHTLOOP_SINGLE_PASS");
m_SingleDeferredMaterialSRT.DisableKeyword("OUTPUT_SPLIT_LIGHTING");
m_SingleDeferredMaterialSRT.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.RegularLighting);

m_SingleDeferredMaterialMRT = Utilities.CreateEngineMaterial(m_Resources.deferredShader);
m_SingleDeferredMaterialMRT = CoreUtils.CreateEngineMaterial(m_Resources.deferredShader);
m_SingleDeferredMaterialMRT.EnableKeyword("LIGHTLOOP_SINGLE_PASS");
m_SingleDeferredMaterialMRT.EnableKeyword("OUTPUT_SPLIT_LIGHTING");
m_SingleDeferredMaterialMRT.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.SplitLighting);

m_DebugViewTilesMaterial = Utilities.CreateEngineMaterial(m_Resources.debugViewTilesShader);
m_DebugViewTilesMaterial = CoreUtils.CreateEngineMaterial(m_Resources.debugViewTilesShader);
m_DefaultTexture2DArray = new Texture2DArray(1, 1, 1, TextureFormat.ARGB32, false);
m_DefaultTexture2DArray.SetPixels32(new Color32[1] { new Color32(128, 128, 128, 128) }, 0);

UnityEditor.SceneView.onSceneGUIDelegate -= OnSceneGUI;
#endif
Utilities.SafeRelease(s_DirectionalLightDatas);
Utilities.SafeRelease(s_LightDatas);
Utilities.SafeRelease(s_EnvLightDatas);
Utilities.SafeRelease(s_shadowDatas);
CoreUtils.SafeRelease(s_DirectionalLightDatas);
CoreUtils.SafeRelease(s_LightDatas);
CoreUtils.SafeRelease(s_EnvLightDatas);
CoreUtils.SafeRelease(s_shadowDatas);
if (m_CubeReflTexArray != null)
{

ReleaseResolutionDependentBuffers();
Utilities.SafeRelease(s_AABBBoundsBuffer);
Utilities.SafeRelease(s_ConvexBoundsBuffer);
Utilities.SafeRelease(s_LightVolumeDataBuffer);
Utilities.SafeRelease(s_DispatchIndirectBuffer);
CoreUtils.SafeRelease(s_AABBBoundsBuffer);
CoreUtils.SafeRelease(s_ConvexBoundsBuffer);
CoreUtils.SafeRelease(s_LightVolumeDataBuffer);
CoreUtils.SafeRelease(s_DispatchIndirectBuffer);
Utilities.SafeRelease(s_GlobalLightListAtomic);
CoreUtils.SafeRelease(s_GlobalLightListAtomic);
Utilities.Destroy(m_DeferredAllMaterialSRT);
Utilities.Destroy(m_DeferredAllMaterialMRT);
CoreUtils.Destroy(m_DeferredAllMaterialSRT);
CoreUtils.Destroy(m_DeferredAllMaterialMRT);
Utilities.Destroy(m_DebugViewTilesMaterial);
CoreUtils.Destroy(m_DebugViewTilesMaterial);
Utilities.Destroy(m_SingleDeferredMaterialSRT);
Utilities.Destroy(m_SingleDeferredMaterialMRT);
CoreUtils.Destroy(m_SingleDeferredMaterialSRT);
CoreUtils.Destroy(m_SingleDeferredMaterialMRT);
}
public void NewFrame()

public void ReleaseResolutionDependentBuffers()
{
Utilities.SafeRelease(s_LightList);
Utilities.SafeRelease(s_TileList);
Utilities.SafeRelease(s_TileFeatureFlags);
CoreUtils.SafeRelease(s_LightList);
CoreUtils.SafeRelease(s_TileList);
CoreUtils.SafeRelease(s_TileFeatureFlags);
Utilities.SafeRelease(s_PerVoxelLightLists);
Utilities.SafeRelease(s_PerVoxelOffset);
Utilities.SafeRelease(s_PerTileLogBaseTweak);
CoreUtils.SafeRelease(s_PerVoxelLightLists);
CoreUtils.SafeRelease(s_PerVoxelOffset);
CoreUtils.SafeRelease(s_PerTileLogBaseTweak);
Utilities.SafeRelease(s_BigTileLightList);
CoreUtils.SafeRelease(s_BigTileLightList);
}
int NumLightIndicesPerClusteredTile()

case LightTypeExtent.Line:
if (areaLightCount >= k_MaxAreaLightsOnScreen)
continue;
continue;
gpuLightType = GPULightType.Line;
lightVolumeType = LightVolumeType.Box;
break;

sortKeys[sortCount++] = (uint)lightCategory << 27 | (uint)gpuLightType << 22 | (uint)lightVolumeType << 17 | shadow << 16 | (uint)lightIndex;
}
Utilities.QuickSort(sortKeys, 0, sortCount - 1); // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory (note the SortCount-1 that is different from original call).
CoreUtils.QuickSort(sortKeys, 0, sortCount - 1); // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory (note the SortCount-1 that is different from original call).
// TODO: Refactor shadow management
// The good way of managing shadow:

}
// Not necessary yet but call it for future modification with sphere influence volume
Utilities.QuickSort(sortKeys, 0, sortCount - 1); // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory (note the SortCount-1 that is different from original call).
CoreUtils.QuickSort(sortKeys, 0, sortCount - 1); // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory (note the SortCount-1 that is different from original call).
for (int sortIndex = 0; sortIndex < sortCount; ++sortIndex)
{

public void PushGlobalParams(Camera camera, CommandBuffer cmd, ComputeShader computeShader, int kernelIndex, bool forceClustered = false)
{
using (new Utilities.ProfilingSample("Push Global Parameters", cmd))
using (new ProfilingSample(cmd, "Push Global Parameters"))
{
// Shadows
m_ShadowMgr.SyncData();

private void SetupDebugDisplayMode(bool debugDisplayEnable)
{
Utilities.SetKeyword(m_DeferredAllMaterialSRT, "DEBUG_DISPLAY", debugDisplayEnable);
Utilities.SetKeyword(m_DeferredAllMaterialMRT, "DEBUG_DISPLAY", debugDisplayEnable);
Utilities.SetKeyword(m_SingleDeferredMaterialSRT, "DEBUG_DISPLAY", debugDisplayEnable);
Utilities.SetKeyword(m_SingleDeferredMaterialMRT, "DEBUG_DISPLAY", debugDisplayEnable);
CoreUtils.SetKeyword(m_DeferredAllMaterialSRT, "DEBUG_DISPLAY", debugDisplayEnable);
CoreUtils.SetKeyword(m_DeferredAllMaterialMRT, "DEBUG_DISPLAY", debugDisplayEnable);
CoreUtils.SetKeyword(m_SingleDeferredMaterialSRT, "DEBUG_DISPLAY", debugDisplayEnable);
CoreUtils.SetKeyword(m_SingleDeferredMaterialMRT, "DEBUG_DISPLAY", debugDisplayEnable);
}
public void RenderLightingDebug(HDCamera hdCamera, CommandBuffer cmd, RenderTargetIdentifier colorBuffer, DebugDisplaySettings debugDisplaySettings)

return;
using (new Utilities.ProfilingSample("Tiled Lighting Debug", cmd))
using (new ProfilingSample(cmd, "Tiled Lighting Debug"))
{
bool bUseClusteredForDeferred = !usingFptl;

m_DebugViewTilesMaterial.EnableKeyword("SHOW_LIGHT_CATEGORIES");
m_DebugViewTilesMaterial.DisableKeyword("SHOW_FEATURE_VARIANTS");
Utilities.DrawFullScreen(cmd, m_DebugViewTilesMaterial, 0, colorBuffer);
CoreUtils.DrawFullScreen(cmd, m_DebugViewTilesMaterial, 0, colorBuffer);
}
SetGlobalPropertyRedirect(null, 0, null);
}

if (m_CurrentSunLight == null)
return;
using (new Utilities.ProfilingSample("Deferred Directional", cmd))
using (new ProfilingSample(cmd, "Deferred Directional"))
{
hdCamera.SetupComputeShader(deferredDirectionalShadowComputeShader, cmd);
m_ShadowMgr.BindResources(cmd, deferredDirectionalShadowComputeShader, s_deferredDirectionalShadowKernel);

string singlePassName = "SinglePass - Deferred Lighting Pass";
string SinglePassMRTName = "SinglePass - Deferred Lighting Pass MRT";
using (new Utilities.ProfilingSample(m_TileSettings.enableTileAndCluster ?
(options.outputSplitLighting ? tilePassMRTName : tilePassName) :
(options.outputSplitLighting ? SinglePassMRTName : singlePassName), cmd))
using (new ProfilingSample(cmd, m_TileSettings.enableTileAndCluster ?
(options.outputSplitLighting ? tilePassMRTName : tilePassName) :
(options.outputSplitLighting ? SinglePassMRTName : singlePassName)))
{
var camera = hdCamera.camera;

// This is a debug brute force renderer to debug tile/cluster which render all the lights
if (options.outputSplitLighting)
{
Utilities.DrawFullScreen(cmd, m_SingleDeferredMaterialMRT, colorBuffers, depthStencilBuffer);
CoreUtils.DrawFullScreen(cmd, m_SingleDeferredMaterialMRT, colorBuffers, depthStencilBuffer);
}
else
{

m_SingleDeferredMaterialSRT.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal);
}
Utilities.DrawFullScreen(cmd, m_SingleDeferredMaterialSRT, colorBuffers[0], depthStencilBuffer);
CoreUtils.DrawFullScreen(cmd, m_SingleDeferredMaterialSRT, colorBuffers[0], depthStencilBuffer);
}
}
else

if (options.outputSplitLighting)
{
Utilities.SelectKeyword(m_DeferredAllMaterialMRT, "USE_CLUSTERED_LIGHTLIST", "USE_FPTL_LIGHTLIST", bUseClusteredForDeferred);
Utilities.DrawFullScreen(cmd, m_DeferredAllMaterialMRT, colorBuffers, depthStencilBuffer);
CoreUtils.SelectKeyword(m_DeferredAllMaterialMRT, "USE_CLUSTERED_LIGHTLIST", "USE_FPTL_LIGHTLIST", bUseClusteredForDeferred);
CoreUtils.DrawFullScreen(cmd, m_DeferredAllMaterialMRT, colorBuffers, depthStencilBuffer);
}
else
{

m_DeferredAllMaterialSRT.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal);
}
Utilities.SelectKeyword(m_DeferredAllMaterialSRT, "USE_CLUSTERED_LIGHTLIST", "USE_FPTL_LIGHTLIST", bUseClusteredForDeferred);
Utilities.DrawFullScreen(cmd, m_DeferredAllMaterialSRT, colorBuffers[0], depthStencilBuffer);
CoreUtils.SelectKeyword(m_DeferredAllMaterialSRT, "USE_CLUSTERED_LIGHTLIST", "USE_FPTL_LIGHTLIST", bUseClusteredForDeferred);
CoreUtils.DrawFullScreen(cmd, m_DeferredAllMaterialSRT, colorBuffers[0], depthStencilBuffer);
}
}
}

// Note: if we use render opaque with deferred tiling we need to render a opaque depth pass for these opaque objects
if (!m_TileSettings.enableTileAndCluster)
{
using (new Utilities.ProfilingSample("Forward pass", cmd))
using (new ProfilingSample(cmd, "Forward pass"))
{
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 Utilities.ProfilingSample(useFptl ? "Forward Tiled pass" : "Forward Clustered pass", cmd))
using (new ProfilingSample(cmd, useFptl ? "Forward Tiled pass" : "Forward Clustered pass"))
{
// 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 Utilities.ProfilingSample("Display Shadows", cmd))
using (new ProfilingSample(cmd, "Display Shadows"))
{
if (lightingDebug.shadowDebugMode == ShadowMapDebugMode.VisualizeShadowMap)
{

for (uint i = 0; i < faceCount; ++i)
{
m_ShadowMgr.DisplayShadow(cmd, index, i, x, y, overlaySize, overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue);
Utilities.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, camera.pixelWidth);
HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, camera.pixelWidth);
}
}
}

Utilities.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, camera.pixelWidth);
HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, camera.pixelWidth);
}
}
}

3
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs.hlsl


#define LIGHTFEATUREFLAGS_DIRECTIONAL (1024)
#define LIGHTFEATUREFLAGS_ENV (2048)
#define LIGHTFEATUREFLAGS_SKY (4096)
#define LIGHTFEATUREFLAGS_SSL (8192)
//
// UnityEngine.Experimental.Rendering.HDPipeline.TilePass.LightDefinitions: static fields

#define USE_LEFT_HAND_CAMERA_SPACE (1)
#define TILE_SIZE_FPTL (16)
#define TILE_SIZE_CLUSTERED (32)
#define NUM_FEATURE_VARIANTS (26)
#define NUM_FEATURE_VARIANTS (27)
#define LIGHT_FEATURE_MASK_FLAGS (65280)
#define MATERIAL_FEATURE_MASK_FLAGS (255)

2
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.hlsl


float3 envDiffuseLighting;
float3 envSpecularLighting;
float envDiffuseLightingWeight;
};
//-----------------------------------------------------------------------------

14
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePassLoop.hlsl


#endif
}
if (featureFlags & LIGHTFEATUREFLAGS_ENV || featureFlags & LIGHTFEATUREFLAGS_SKY)
float totalIblWeight = 0.0; // Max: 1
if (featureFlags & LIGHTFEATUREFLAGS_SSL)
float totalIblWeight = 0.0; // Max: 1
// SSR and rough refraction
float3 localDiffuseLighting, localSpecularLighting;
float2 weight;
EvaluateBSDF_SSL(V, posInput, bsdfData, localDiffuseLighting, localSpecularLighting, weight);
applyWeigthedIblLighting(localDiffuseLighting, localSpecularLighting, weight, accLighting.envDiffuseLighting, accLighting.envSpecularLighting, totalIblWeight);
accLighting.envDiffuseLightingWeight = weight.x;
}
if (featureFlags & LIGHTFEATUREFLAGS_ENV || featureFlags & LIGHTFEATUREFLAGS_SKY)
{
// Reflection probes are sorted by volume (in the increasing order).
if (featureFlags & LIGHTFEATUREFLAGS_ENV)
{

5
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/builddispatchindirect.compute


uint tileY = (dispatchThreadId + 0.5f) / (float)g_NumTilesX; // Integer division is extremely expensive, so we better avoid it
uint tileX = dispatchThreadId - tileY * g_NumTilesX;
// Check if there is no light or no material (mean we are sky/background pixel) / Both test as we can enable/disable light/material classification
if ((featureFlags & LIGHT_FEATURE_MASK_FLAGS) != 0 && (featureFlags & MATERIAL_FEATURE_MASK_FLAGS) != 0)
// Check if there is no material (means it is a sky/background pixel).
// Note that we can have no lights, yet we still need to render geometry with precomputed illumination.
if ((featureFlags & MATERIAL_FEATURE_MASK_FLAGS) != 0)
{
uint variant = FeatureFlagsToTileVariant(featureFlags);
uint offset;

6
ScriptableRenderPipeline/HDRenderPipeline/Lighting/Volumetrics/HomogeneousFog.cs


using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[ExecuteInEditMode]

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


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

void ClearVolumetricLightingBuffers(CommandBuffer cmd, bool isFirstFrame)
{
using (new Utilities.ProfilingSample("Clear volumetric lighting buffers", cmd))
using (new ProfilingSample(cmd, "Clear volumetric lighting buffers"))
Utilities.SetRenderTarget(cmd, m_VolumetricLightingBufferCurrentFrameRT, ClearFlag.ClearColor, Color.black);
CoreUtils.SetRenderTarget(cmd, m_VolumetricLightingBufferCurrentFrameRT, ClearFlag.Color, Color.black);
Utilities.SetRenderTarget(cmd, m_VolumetricLightingBufferAccumulated, ClearFlag.ClearColor, Color.black);
CoreUtils.SetRenderTarget(cmd, m_VolumetricLightingBufferAccumulated, ClearFlag.Color, Color.black);
}
}
}

{
if (!SetGlobalVolumeProperties(m_VolumetricLightingEnabled, cmd, m_VolumetricLightingCS)) { return; }
using (new Utilities.ProfilingSample("VolumetricLighting", cmd))
using (new ProfilingSample(cmd, "VolumetricLighting"))
{
bool enableClustered = m_Asset.tileSettings.enableClustered && m_Asset.tileSettings.enableTileAndCluster;

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs


using UnityEngine;
//-----------------------------------------------------------------------------
// structure definition
//-----------------------------------------------------------------------------

27
ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/Editor/LayeredLitUI.cs


using System;
using UnityEngine;
using UnityEngine.Rendering;
using System.Linq;

private class StylesLayer
{
public readonly Color[] layerColors =
{
Color.white,
Color.red,
Color.green,
Color.blue
};
public readonly GUIContent[] layerLabels =
{
new GUIContent("Main layer"),

public readonly GUIContent useHeightBasedBlendText = new GUIContent("Use Height Based Blend", "Layer will be blended with the underlying layer based on the height.");
public readonly GUIContent useMainLayerInfluenceModeText = new GUIContent("Main Layer Influence", "Switch between regular layers mode and base/layers mode");
public readonly GUIContent opacityAsDensityText = new GUIContent("Use Opacity as Density", "Use Opacity as Density.");
public readonly GUIContent opacityAsDensityText = new GUIContent("Use Opacity map as Density map", "Use opacity map as (alpha channel of base color) as Density map.");
public readonly GUIContent inheritBaseNormalText = new GUIContent("Normal influence", "Inherit the normal from the base layer.");
public readonly GUIContent inheritBaseHeightText = new GUIContent("Heightmap influence", "Inherit the height from the base layer.");
public readonly GUIContent inheritBaseColorText = new GUIContent("BaseColor influence", "Inherit the base color from the base layer.");

public StylesLayer()
{
layerLabelColors[0].normal.textColor = Color.white;
layerLabelColors[1].normal.textColor = Color.red;
layerLabelColors[2].normal.textColor = Color.green;
layerLabelColors[3].normal.textColor = Color.blue;
layerLabelColors[0].normal.textColor = layerColors[0];
layerLabelColors[1].normal.textColor = layerColors[1];
layerLabelColors[2].normal.textColor = layerColors[2];
layerLabelColors[3].normal.textColor = layerColors[3];
}
}

bool layersChanged = false;
Material material = m_MaterialEditor.target as Material;
Color originalContentColor = GUI.contentColor;
GUI.contentColor = styles.layerColors[layerIndex];
SynchronizeLayerProperties(material, m_MaterialLayers, layerIndex, false);
SynchronizeLayerProperties(material, m_MaterialLayers, layerIndex, true);
GUI.contentColor = originalContentColor;
GUILayout.BeginHorizontal();
{

61
ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader


_DistortionVectorMap("DistortionVectorMap", 2D) = "black" {}
// Wind
[ToggleOff] _EnableWind("Enable Wind", Float) = 0.0
_InitialBend("Initial Bend", float) = 1.0
_Stiffness("Stiffness", float) = 1.0
_Drag("Drag", float) = 1.0
_ShiverDrag("Shiver Drag", float) = 0.2
_ShiverDirectionality("Shiver Directionality", Range(0.0, 1.0)) = 0.5
[ToggleOff] _EnableFpsMode("Enable Fps Mode", Float) = 0.0
_FpsModeFov("_FpsModeFov", Float) = 60.0

_PPDMinSamples("Min sample for POM", Range(1.0, 64.0)) = 5
_PPDMaxSamples("Max sample for POM", Range(1.0, 64.0)) = 15
_PPDLodThreshold("Start lod to fade out the POM effect", Range(0.0, 16.0)) = 5
[ToggleOff] _PerPixelDisplacementObjectScale("Per pixel displacement object scale", Float) = 1.0
// Displacement map
[ToggleOff] _EnableVertexDisplacement("Enable vertex displacement", Float) = 0.0
[ToggleOff] _VertexDisplacementObjectScale("Vertex displacement object scale", Float) = 1.0
[ToggleOff] _VertexDisplacementTilingScale("Vertex displacement tiling height scale", Float) = 1.0
// Wind
[ToggleOff] _EnableWind("Enable Wind", Float) = 0.0
_InitialBend("Initial Bend", float) = 1.0
_Stiffness("Stiffness", float) = 1.0
_Drag("Drag", float) = 1.0
_ShiverDrag("Shiver Drag", float) = 0.2
_ShiverDirectionality("Shiver Directionality", Range(0.0, 1.0)) = 0.5
// Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor"
// value that exist to identify if the GI emission need to be enabled.
// In our case we don't use such a mechanism but need to keep the code quiet. We declare the value and always enable it.

#pragma shader_feature _DEPTHOFFSET_ON
#pragma shader_feature _DOUBLESIDED_ON
#pragma shader_feature _PER_PIXEL_DISPLACEMENT
#pragma shader_feature _PER_PIXEL_DISPLACEMENT_OBJECT_SCALE
#pragma shader_feature _VERTEX_DISPLACEMENT
#pragma shader_feature _VERTEX_DISPLACEMENT_OBJECT_SCALE
#pragma shader_feature _VERTEX_DISPLACEMENT_TILING_SCALE
#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _LAYER_TILING_COUPLED_WITH_UNIFORM_OBJECT_SCALE
#pragma shader_feature _ _LAYER_MAPPING_PLANAR_BLENDMASK _LAYER_MAPPING_TRIPLANAR_BLENDMASK

#pragma shader_feature _DENSITY_MODE
#pragma shader_feature _HEIGHT_BASED_BLEND
#pragma shader_feature _ _LAYEREDLIT_3_LAYERS _LAYEREDLIT_4_LAYERS
#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _FPS_MODE
#pragma shader_feature _ _BLENDMODE_LERP _BLENDMODE_ADD _BLENDMODE_SOFT_ADD _BLENDMODE_MULTIPLY _BLENDMODE_PRE_MULTIPLY

#define UNITY_MATERIAL_LIT // Need to be define before including Material.hlsl
// Use surface gradient normal mapping as it handle correctly triplanar normal mapping and multiple UVSet
#define SURFACE_GRADIENT
// This shader support vertex modification
#define HAVE_VERTEX_MODIFICATION
//-------------------------------------------------------------------------------------
// Include

HLSLPROGRAM
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "../Lit/LitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL
}
// This pass is the same as GBuffer only it does not do alpha test (the clip instruction is removed)
// This is due to the fact that on GCN, any shader with a clip instruction cannot benefit from HiZ so when we do a prepass, in order to get the most performance, we need to make a special case in the subsequent GBuffer pass.
Pass
{
Name "GBufferWithPrepass" // Name is not used
Tags { "LightMode" = "GBufferWithPrepass" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
Stencil
{
Ref [_StencilRef]
Comp Always
Pass Replace
}
HLSLPROGRAM
#define SHADERPASS SHADERPASS_GBUFFER
#define _BYPASS_ALPHA_TEST
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"

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


_DistortionVectorMap("DistortionVectorMap", 2D) = "black" {}
// Wind
[ToggleOff] _EnableWind("Enable Wind", Float) = 0.0
_InitialBend("Initial Bend", float) = 1.0
_Stiffness("Stiffness", float) = 1.0
_Drag("Drag", float) = 1.0
_ShiverDrag("Shiver Drag", float) = 0.2
_ShiverDirectionality("Shiver Directionality", Range(0.0, 1.0)) = 0.5
[ToggleOff] _EnableFpsMode("Enable Fps Mode", Float) = 0.0
_FpsModeFov("_FpsModeFov", Float) = 60.0

_PPDMinSamples("Min sample for POM", Range(1.0, 64.0)) = 5
_PPDMaxSamples("Max sample for POM", Range(1.0, 64.0)) = 15
_PPDLodThreshold("Start lod to fade out the POM effect", Range(0.0, 16.0)) = 5
[ToggleOff] _PerPixelDisplacementObjectScale("Per pixel displacement object scale", Float) = 1.0
// Displacement map
[ToggleOff] _EnableVertexDisplacement("Enable vertex displacement", Float) = 0.0
[ToggleOff] _VertexDisplacementObjectScale("Vertex displacement object scale", Float) = 1.0
[ToggleOff] _VertexDisplacementTilingScale("Vertex displacement tiling height scale", Float) = 1.0
// Wind
[ToggleOff] _EnableWind("Enable Wind", Float) = 0.0
_InitialBend("Initial Bend", float) = 1.0
_Stiffness("Stiffness", float) = 1.0
_Drag("Drag", float) = 1.0
_ShiverDrag("Shiver Drag", float) = 0.2
_ShiverDirectionality("Shiver Directionality", Range(0.0, 1.0)) = 0.5
// Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor"
// value that exist to identify if the GI emission need to be enabled.
// In our case we don't use such a mechanism but need to keep the code quiet. We declare the value and always enable it.

[HideInInspector] _UVDetailsMappingMask2("_UVDetailsMappingMask2", Color) = (1, 0, 0, 0)
[HideInInspector] _UVDetailsMappingMask3("_UVDetailsMappingMask3", Color) = (1, 0, 0, 0)
// Tesselation specific
[Enum(Phong, 0, Displacement, 1, DisplacementPhong, 2)] _TessellationMode("Tessellation mode", Float) = 1
[HideInInspector] _ShowMaterialReferences("_ShowMaterialReferences", Float) = 0
[HideInInspector] _ShowLayer0("_ShowLayer0", Float) = 0
[HideInInspector] _ShowLayer1("_ShowLayer1", Float) = 0
[HideInInspector] _ShowLayer2("_ShowLayer2", Float) = 0
[HideInInspector] _ShowLayer3("_ShowLayer3", Float) = 0
// Tessellation specific
[Enum(None, 0, Phong, 1)] _TessellationMode("Tessellation mode", Float) = 0
_TessellationFactor("Tessellation Factor", Range(0.0, 15.0)) = 4.0
_TessellationFactorMinDistance("Tessellation start fading distance", Float) = 20.0
_TessellationFactorMaxDistance("Tessellation end fading distance", Float) = 50.0

[ToggleOff] _TessellationObjectScale("Tessellation object scale", Float) = 0.0
[ToggleOff] _TessellationTilingScale("Tessellation tiling scale", Float) = 1.0
[HideInInspector] _ShowMaterialReferences("_ShowMaterialReferences", Float) = 0
[HideInInspector] _ShowLayer0("_ShowLayer0", Float) = 0
[HideInInspector] _ShowLayer1("_ShowLayer1", Float) = 0
[HideInInspector] _ShowLayer2("_ShowLayer2", Float) = 0
[HideInInspector] _ShowLayer3("_ShowLayer3", Float) = 0
}
HLSLINCLUDE

#pragma shader_feature _DEPTHOFFSET_ON
#pragma shader_feature _DOUBLESIDED_ON
#pragma shader_feature _PER_PIXEL_DISPLACEMENT
// Default is _TESSELLATION_PHONG
#pragma shader_feature _ _TESSELLATION_DISPLACEMENT _TESSELLATION_DISPLACEMENT_PHONG
#pragma shader_feature _TESSELLATION_OBJECT_SCALE
#pragma shader_feature _TESSELLATION_TILING_SCALE
#pragma shader_feature _PER_PIXEL_DISPLACEMENT_OBJECT_SCALE
#pragma shader_feature _VERTEX_DISPLACEMENT
#pragma shader_feature _VERTEX_DISPLACEMENT_OBJECT_SCALE
#pragma shader_feature _VERTEX_DISPLACEMENT_TILING_SCALE
#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _TESSELLATION_PHONG
#pragma shader_feature _LAYER_TILING_COUPLED_WITH_UNIFORM_OBJECT_SCALE
#pragma shader_feature _ _LAYER_MAPPING_PLANAR_BLENDMASK _LAYER_MAPPING_TRIPLANAR_BLENDMASK

#pragma shader_feature _DENSITY_MODE
#pragma shader_feature _HEIGHT_BASED_BLEND
#pragma shader_feature _ _LAYEREDLIT_3_LAYERS _LAYEREDLIT_4_LAYERS
#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _FPS_MODE
#pragma shader_feature _ _BLENDMODE_LERP _BLENDMODE_ADD _BLENDMODE_SOFT_ADD _BLENDMODE_MULTIPLY _BLENDMODE_PRE_MULTIPLY

#define TESSELLATION_ON
// Use surface gradient normal mapping as it handle correctly triplanar normal mapping and multiple UVSet
#define SURFACE_GRADIENT
// This shader support vertex modification
#define HAVE_VERTEX_MODIFICATION
#define HAVE_TESSELLATION_MODIFICATION
//-------------------------------------------------------------------------------------
// Include

#pragma domain Domain
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "../Lit/LitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL
}
// This pass is the same as GBuffer only it does not do alpha test (the clip instruction is removed)
// This is due to the fact that on GCN, any shader with a clip instruction cannot benefit from HiZ so when we do a prepass, in order to get the most performance, we need to make a special case in the subsequent GBuffer pass.
Pass
{
Name "GBufferWithPrepass" // Name is not used
Tags { "LightMode" = "GBufferWithPrepass" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
Stencil
{
Ref [_StencilRef]
Comp Always
Pass Replace
}
HLSLPROGRAM
#pragma hull Hull
#pragma domain Domain
#define SHADERPASS SHADERPASS_GBUFFER
#define _BYPASS_ALPHA_TEST
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"

136
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs


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

public static GUIContent ppdMinSamplesText = new GUIContent("Minimum steps", "Minimum steps (texture sample) to use with per pixel displacement mapping");
public static GUIContent ppdMaxSamplesText = new GUIContent("Maximum steps", "Maximum steps (texture sample) to use with per pixel displacement mapping");
public static GUIContent ppdLodThresholdText = new GUIContent("Fading mip level start", "Starting heightmap mipmap lod number where the parallax occlusion mapping effect start to disappear");
public static GUIContent perPixelDisplacementObjectScaleText = new GUIContent("Lock with object scale", "Per Pixel displacement will take into account the tiling scale - Only work with uniform positive scale");
// Vertex displacement
public static string vertexDisplacementText = "Vertex displacement";
public static GUIContent enableVertexDisplacementText = new GUIContent("Enable vertex displacement", "Use heightmap as a displacement map. Displacement map is use to move vertex position in local space");
public static GUIContent vertexDisplacementObjectScaleText = new GUIContent("Lock with object scale", "Vertex displacement will take into account the object scale - Only work with uniform positive scale");
public static GUIContent vertexDisplacementTilingScaleText = new GUIContent("Lock with heightmap tiling", "Vertex displacement will take into account the tiling scale - Only work with uniform positive scale");
// Tessellation
public static string tessellationModeText = "Tessellation Mode";

public static GUIContent tessellationFactorTriangleSizeText = new GUIContent("Triangle size", "Desired screen space sized of triangle (in pixel). Smaller value mean smaller triangle.");
public static GUIContent tessellationShapeFactorText = new GUIContent("Shape factor", "Strength of Phong tessellation shape (lerp factor)");
public static GUIContent tessellationBackFaceCullEpsilonText = new GUIContent("Triangle culling Epsilon", "If -1.0 back face culling is enabled for tessellation, higher number mean more aggressive culling and better performance");
public static GUIContent tessellationObjectScaleText = new GUIContent("Lock with object scale", "Tessellation displacement will take into account the object scale - Only work with uniform positive scale");
public static GUIContent tessellationTilingScaleText = new GUIContent("Lock with heightmap tiling", "Tessellation displacement will take into account the tiling scale - Only work with uniform positive scale");
// Vertex animation
public static string vertexAnimation = "Vertex animation";
// Wind
public static GUIContent windText = new GUIContent("Enable Wind");

public static GUIContent windShiverDragText = new GUIContent("Shiver Drag");
public static GUIContent windShiverDirectionalityText = new GUIContent("Shiver Directionality");
public static string vertexAnimation = "Vertex Animation";
// FPS Mode
public static GUIContent fpsModeText = new GUIContent("Enable FPS Mode");
public static GUIContent fpsModeFovText = new GUIContent("Fov");
// FPS Mode
public static GUIContent fpsModeText = new GUIContent("Enable FPS Mode");
public static GUIContent fpsModeFovText = new GUIContent("Fov");
public static string fpsMode = "FPS Mode";
}

public enum TessellationMode
{
Phong,
Displacement,
DisplacementPhong,
None,
Phong
}
protected MaterialProperty doubleSidedNormalMode = null;

protected const string kStencilRef = "_StencilRef";
// Per pixel displacement params
protected MaterialProperty enablePerPixelDisplacement = null;
protected const string kEnablePerPixelDisplacement = "_EnablePerPixelDisplacement";
protected MaterialProperty ppdMinSamples = null;
protected const string kPpdMinSamples = "_PPDMinSamples";
protected MaterialProperty ppdMaxSamples = null;
protected const string kPpdMaxSamples = "_PPDMaxSamples";
protected MaterialProperty ppdLodThreshold = null;
protected const string kPpdLodThreshold = "_PPDLodThreshold";
protected MaterialProperty perPixelDisplacementObjectScale = null;
protected const string kPerPixelDisplacementObjectScale = "_PerPixelDisplacementObjectScale";
// Vertex displacement
protected MaterialProperty enableVertexDisplacement = null;
protected const string kEnableVertexDisplacement = "_EnableVertexDisplacement";
protected MaterialProperty vertexDisplacementObjectScale = null;
protected const string kVertexDisplacementObjectScale = "_VertexDisplacementObjectScale";
protected MaterialProperty vertexDisplacementTilingScale = null;
protected const string kVertexDisplacementTilingScale = "_VertexDisplacementTilingScale";
// Wind
protected MaterialProperty windEnable = null;
protected const string kWindEnabled = "_EnableWind";

protected MaterialProperty fpsModeFov = null;
protected const string kFpsModeFov = "_FpsModeFov";
// Per pixel displacement params
protected MaterialProperty enablePerPixelDisplacement = null;
protected const string kEnablePerPixelDisplacement = "_EnablePerPixelDisplacement";
protected MaterialProperty ppdMinSamples = null;
protected const string kPpdMinSamples = "_PPDMinSamples";
protected MaterialProperty ppdMaxSamples = null;
protected const string kPpdMaxSamples = "_PPDMaxSamples";
protected MaterialProperty ppdLodThreshold = null;
protected const string kPpdLodThreshold = "_PPDLodThreshold";
// tessellation params
protected MaterialProperty tessellationMode = null;
protected const string kTessellationMode = "_TessellationMode";

protected const string kTessellationShapeFactor = "_TessellationShapeFactor";
protected MaterialProperty tessellationBackFaceCullEpsilon = null;
protected const string kTessellationBackFaceCullEpsilon = "_TessellationBackFaceCullEpsilon";
protected MaterialProperty tessellationObjectScale = null;
protected const string kTessellationObjectScale = "_TessellationObjectScale";
protected MaterialProperty tessellationTilingScale = null;
protected const string kTessellationTilingScale = "_TessellationTilingScale";
protected override void FindBaseMaterialProperties(MaterialProperty[] props)
{

ppdMinSamples = FindProperty(kPpdMinSamples, props);
ppdMaxSamples = FindProperty(kPpdMaxSamples, props);
ppdLodThreshold = FindProperty(kPpdLodThreshold, props);
perPixelDisplacementObjectScale = FindProperty(kPerPixelDisplacementObjectScale, props);
// vertex displacement
enableVertexDisplacement = FindProperty(kEnableVertexDisplacement, props);
vertexDisplacementObjectScale = FindProperty(kVertexDisplacementObjectScale, props);
vertexDisplacementTilingScale = FindProperty(kVertexDisplacementTilingScale, props);
// tessellation specific, silent if not found
tessellationMode = FindProperty(kTessellationMode, props, false);

tessellationFactorTriangleSize = FindProperty(kTessellationFactorTriangleSize, props, false);
tessellationShapeFactor = FindProperty(kTessellationShapeFactor, props, false);
tessellationBackFaceCullEpsilon = FindProperty(kTessellationBackFaceCullEpsilon, props, false);
tessellationObjectScale = FindProperty(kTessellationObjectScale, props, false);
tessellationTilingScale = FindProperty(kTessellationTilingScale, props, false);
// Wind
windEnable = FindProperty(kWindEnabled, props);

m_MaterialEditor.ShaderProperty(ppdMaxSamples, StylesBaseLit.ppdMaxSamplesText);
ppdMinSamples.floatValue = Mathf.Min(ppdMinSamples.floatValue, ppdMaxSamples.floatValue);
m_MaterialEditor.ShaderProperty(ppdLodThreshold, StylesBaseLit.ppdLodThresholdText);
//m_MaterialEditor.ShaderProperty(perPixelDisplacementObjectScale, StylesBaseLit.perPixelDisplacementObjectScaleText);
m_MaterialEditor.ShaderProperty(depthOffsetEnable, StylesBaseLit.depthOffsetEnableText);
EditorGUI.indentLevel--;
}

// Vertex displacement options
EditorGUILayout.Space();
EditorGUILayout.LabelField(StylesBaseLit.vertexDisplacementText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(enableVertexDisplacement, StylesBaseLit.enableVertexDisplacementText);
if (enableVertexDisplacement.floatValue > 0.0f)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(vertexDisplacementObjectScale, StylesBaseLit.vertexDisplacementObjectScaleText);
m_MaterialEditor.ShaderProperty(vertexDisplacementTilingScale, StylesBaseLit.vertexDisplacementTilingScaleText);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
// Display tessellation option if it exist
if (tessellationMode != null)
{

// clamp min distance to be below max distance
tessellationFactorMinDistance.floatValue = Math.Min(tessellationFactorMaxDistance.floatValue, tessellationFactorMinDistance.floatValue);
m_MaterialEditor.ShaderProperty(tessellationFactorTriangleSize, StylesBaseLit.tessellationFactorTriangleSizeText);
if ((TessellationMode)tessellationMode.floatValue == TessellationMode.Phong ||
(TessellationMode)tessellationMode.floatValue == TessellationMode.DisplacementPhong)
if ((TessellationMode)tessellationMode.floatValue == TessellationMode.Phong)
{
m_MaterialEditor.ShaderProperty(tessellationShapeFactor, StylesBaseLit.tessellationShapeFactorText);
}

}
m_MaterialEditor.ShaderProperty(tessellationObjectScale, StylesBaseLit.tessellationObjectScaleText);
m_MaterialEditor.ShaderProperty(tessellationTilingScale, StylesBaseLit.tessellationTilingScaleText);
EditorGUI.indentLevel--;
}
}

bool enablePerPixelDisplacement = material.GetFloat(kEnablePerPixelDisplacement) > 0.0f;
SetKeyword(material, "_PER_PIXEL_DISPLACEMENT", enablePerPixelDisplacement);
if (material.HasProperty(kTessellationMode))
{
TessellationMode tessMode = (TessellationMode)material.GetFloat(kTessellationMode);
bool perPixelDisplacementObjectScale = material.GetFloat(kPerPixelDisplacementObjectScale) > 0.0;
SetKeyword(material, "_PER_PIXEL_DISPLACEMENT_OBJECT_SCALE", perPixelDisplacementObjectScale && enablePerPixelDisplacement);
if (tessMode == TessellationMode.Phong)
{
material.DisableKeyword("_TESSELLATION_DISPLACEMENT");
material.DisableKeyword("_TESSELLATION_DISPLACEMENT_PHONG");
}
else if (tessMode == TessellationMode.Displacement)
{
material.EnableKeyword("_TESSELLATION_DISPLACEMENT");
material.DisableKeyword("_TESSELLATION_DISPLACEMENT_PHONG");
}
else
{
material.DisableKeyword("_TESSELLATION_DISPLACEMENT");
material.EnableKeyword("_TESSELLATION_DISPLACEMENT_PHONG");
}
bool enableVertexDisplacement = material.GetFloat(kEnableVertexDisplacement) > 0.0f;
SetKeyword(material, "_VERTEX_DISPLACEMENT", enableVertexDisplacement);
bool tessellationObjectScaleEnable = material.GetFloat(kTessellationObjectScale) > 0.0;
SetKeyword(material, "_TESSELLATION_OBJECT_SCALE", tessellationObjectScaleEnable);
bool vertexDisplacementObjectScaleEnable = material.GetFloat(kVertexDisplacementObjectScale) > 0.0;
SetKeyword(material, "_VERTEX_DISPLACEMENT_OBJECT_SCALE", vertexDisplacementObjectScaleEnable && enableVertexDisplacement);
bool tessellationTilingScaleEnable = material.GetFloat(kTessellationTilingScale) > 0.0;
SetKeyword(material, "_TESSELLATION_TILING_SCALE", tessellationTilingScaleEnable);
bool vertexDisplacementTilingScaleEnable = material.GetFloat(kVertexDisplacementTilingScale) > 0.0;
SetKeyword(material, "_VERTEX_DISPLACEMENT_TILING_SCALE", vertexDisplacementTilingScaleEnable && enableVertexDisplacement);
bool windEnabled = material.GetFloat(kWindEnabled) > 0.0f;
SetKeyword(material, "_VERTEX_WIND", windEnabled);
if (material.HasProperty(kTessellationMode))
{
TessellationMode tessMode = (TessellationMode)material.GetFloat(kTessellationMode);
SetKeyword(material, "_TESSELLATION_PHONG", tessMode == TessellationMode.Phong);
bool windEnabled = material.GetFloat(kWindEnabled) > 0.0f;
SetKeyword(material, "_VERTEX_WIND", windEnabled);
bool fpsModeEnabled = material.GetFloat(kFpsModeEnabled) > 0.0f;
bool fpsModeEnabled = material.GetFloat(kFpsModeEnabled) > 0.0f;
SetKeyword(material, "_FPS_MODE", fpsModeEnabled);
}

72
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/LitUI.cs


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

public static GUIContent albedoAffectEmissiveText = new GUIContent("Albedo Affect Emissive", "Specifies whether or not the emissive color is multiplied by the albedo.");
public static GUIContent normalMapSpaceWarning = new GUIContent("Object space normal can't be use with triplanar mapping.");
// Transparency
public static string TransparencyInputsText = "Transparency Inputs";
public static string refractionModeText = "Refraction Mode";
public static GUIContent refractionIORText = new GUIContent("Indice of refraction", "Indice of refraction");
public static GUIContent refractionThicknessText = new GUIContent("Refraction Thickness", "Thickness for rough refraction");
public static GUIContent refractionThicknessMultiplierText = new GUIContent("Refraction Thickness multiplier", "Thickness multiplier");
public static GUIContent refractionThicknessMapText = new GUIContent("Refraction Thickness Map (R)", "Thickness multiplier");
// Transparency absorption
public static GUIContent transmittanceColorText = new GUIContent("Transmittance Color", "Absorption color (RGB)");
public static GUIContent atDistanceText = new GUIContent("Transmittance Absorption Distance", "Absorption distance reference");
}
// Lit shader is not layered but some layered materials inherit from it. In order to share code we need LitUI to account for this.

protected MaterialProperty enableSpecularOcclusion = null;
protected const string kEnableSpecularOcclusion = "_EnableSpecularOcclusion";
// transparency params
protected MaterialProperty ior = null;
protected const string kIOR = "_IOR";
protected MaterialProperty transmittanceColor = null;
protected const string kTransmittanceColor = "_TransmittanceColor";
protected MaterialProperty atDistance = null;
protected const string kATDistance = "_ATDistance";
protected MaterialProperty thicknessMultiplier = null;
protected const string kThicknessMultiplier = "_ThicknessMultiplier";
protected MaterialProperty refractionMode = null;
protected const string kRefractionMode = "_RefractionMode";
protected void FindMaterialLayerProperties(MaterialProperty[] props)
{
for (int i = 0; i < m_LayerCount; ++i)

// clear coat
coatCoverage = FindProperty(kCoatCoverage, props);
coatIOR = FindProperty(kCoatIOR, props);
// Transparency
refractionMode = FindProperty(kRefractionMode, props, false);
transmittanceColor = FindProperty(kTransmittanceColor, props, false);
atDistance = FindProperty(kATDistance, props, false);
thicknessMultiplier = FindProperty(kThicknessMultiplier, props, false);
ior = FindProperty(kIOR, props, false);
// We reuse thickness from SSS
}
protected void ShaderSSSInputGUI(Material material)

m_MaterialEditor.ShaderProperty(detailSmoothnessScale[layerIndex], Styles.detailSmoothnessScaleText);
EditorGUI.indentLevel--;
var surfaceTypeValue = (SurfaceType)surfaceType.floatValue;
if (surfaceTypeValue == SurfaceType.Transparent
&& refractionMode != null)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField(Styles.TransparencyInputsText, EditorStyles.boldLabel);
++EditorGUI.indentLevel;
m_MaterialEditor.ShaderProperty(refractionMode, Styles.refractionModeText);
var mode = (Lit.RefractionMode)refractionMode.floatValue;
if (mode != Lit.RefractionMode.None)
{
m_MaterialEditor.ShaderProperty(ior, Styles.refractionIORText);
if (mode != Lit.RefractionMode.ThinPlane)
{
if (thicknessMap.textureValue == null)
m_MaterialEditor.ShaderProperty(thickness, Styles.refractionThicknessText);
m_MaterialEditor.TexturePropertySingleLine(Styles.refractionThicknessMapText, thicknessMap);
++EditorGUI.indentLevel;
m_MaterialEditor.ShaderProperty(thicknessMultiplier, Styles.refractionThicknessMultiplierText);
--EditorGUI.indentLevel;
}
m_MaterialEditor.ShaderProperty(transmittanceColor, Styles.transmittanceColorText);
++EditorGUI.indentLevel;
m_MaterialEditor.ShaderProperty(atDistance, Styles.atDistanceText);
--EditorGUI.indentLevel;
}
--EditorGUI.indentLevel;
}
}
private void DoEmissiveGUI(Material material)

SetKeyword(material, "_MATID_ANISO", materialId == Lit.MaterialId.LitAniso);
SetKeyword(material, "_MATID_SPECULAR", materialId == Lit.MaterialId.LitSpecular);
SetKeyword(material, "_MATID_CLEARCOAT", materialId == Lit.MaterialId.LitClearCoat);
var refractionModeValue = (Lit.RefractionMode)material.GetFloat(kRefractionMode);
SetKeyword(material, "_REFRACTION_THINPLANE", refractionModeValue == Lit.RefractionMode.ThinPlane);
SetKeyword(material, "_REFRACTION_THICKPLANE", refractionModeValue == Lit.RefractionMode.ThickPlane);
SetKeyword(material, "_REFRACTION_THICKSPHERE", refractionModeValue == Lit.RefractionMode.ThickSphere);
}
}
} // namespace UnityEditor

31
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs


public static float s_SkinSpecularValue = 0.028f;
}
[GenerateHLSL(PackingRules.Exact)]
public enum RefractionMode
{
None = 0,
ThickPlane = 1,
ThickSphere = 2,
ThinPlane = 3
};
//-----------------------------------------------------------------------------
// SurfaceData
//-----------------------------------------------------------------------------

public float coatCoverage;
[SurfaceDataAttributes("Coat IOR")]
public float coatIOR; // Value is [0..1] for artists but the UI will display the value between [1..2]
// Transparency
[SurfaceDataAttributes("Indice of refraction")]
public float ior;
// Reuse thickness from SSS
[SurfaceDataAttributes("Transmittance Color")]
public Vector3 transmittanceColor;
[SurfaceDataAttributes("Transmittance Absorption Distance")]
public float atDistance;
};
//-----------------------------------------------------------------------------

public Vector3 coatNormalWS;
public float coatCoverage;
public float coatIOR; // CoatIOR is in range[1..2] it is surfaceData + 1
// Transparency
public float ior;
// Reuse thickness from SSS
public Vector3 absorptionCoefficient;
};
//-----------------------------------------------------------------------------

public override void Build(RenderPipelineResources renderPipelineResources)
{
m_InitPreFGD = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/PreIntegratedFGD");
m_InitPreFGD = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/PreIntegratedFGD");
// For DisneyDiffuse integration values goes from (0.5 to 1.53125). GGX need 0 to 1. Use float format.
m_PreIntegratedFGD = new RenderTexture(128, 128, 0, RenderTextureFormat.RGB111110Float, RenderTextureReadWrite.Linear);

public override void Cleanup()
{
Utilities.Destroy(m_InitPreFGD);
CoreUtils.Destroy(m_InitPreFGD);
// TODO: how to delete RenderTexture ? or do we need to do it ?
m_isInit = false;

// return;
// Sample Game Change END
using (new Utilities.ProfilingSample("Init PreFGD", cmd))
using (new ProfilingSample(cmd, "Init PreFGD"))
Utilities.DrawFullScreen(cmd, m_InitPreFGD, new RenderTargetIdentifier(m_PreIntegratedFGD));
CoreUtils.DrawFullScreen(cmd, m_InitPreFGD, new RenderTargetIdentifier(m_PreIntegratedFGD));
}
m_isInit = true;
}

33
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs.hlsl


#define SKIN_SPECULAR_VALUE (0.028)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+RefractionMode: static fields
//
#define REFRACTIONMODE_NONE (0)
#define REFRACTIONMODE_THICK_PLANE (1)
#define REFRACTIONMODE_THICK_SPHERE (2)
#define REFRACTIONMODE_THIN_PLANE (3)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+SurfaceData: static fields
//
#define DEBUGVIEW_LIT_SURFACEDATA_BASE_COLOR (1000)

#define DEBUGVIEW_LIT_SURFACEDATA_COAT_NORMAL_WS (1013)
#define DEBUGVIEW_LIT_SURFACEDATA_COAT_COVERAGE (1014)
#define DEBUGVIEW_LIT_SURFACEDATA_COAT_IOR (1015)
#define DEBUGVIEW_LIT_SURFACEDATA_IOR (1016)
#define DEBUGVIEW_LIT_SURFACEDATA_TRANSMITTANCE_COLOR (1017)
#define DEBUGVIEW_LIT_SURFACEDATA_AT_DISTANCE (1018)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+TransmissionType: static fields

#define DEBUGVIEW_LIT_BSDFDATA_COAT_NORMAL_WS (1048)
#define DEBUGVIEW_LIT_BSDFDATA_COAT_COVERAGE (1049)
#define DEBUGVIEW_LIT_BSDFDATA_COAT_IOR (1050)
#define DEBUGVIEW_LIT_BSDFDATA_IOR (1051)
#define DEBUGVIEW_LIT_BSDFDATA_ABSORPTION_COEFFICIENT (1052)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Lit+GBufferMaterial: static fields

float3 coatNormalWS;
float coatCoverage;
float coatIOR;
float ior;
float3 transmittanceColor;
float atDistance;
};
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Lit+BSDFData

float3 coatNormalWS;
float coatCoverage;
float coatIOR;
float ior;
float3 absorptionCoefficient;
};
//

break;
case DEBUGVIEW_LIT_SURFACEDATA_COAT_IOR:
result = surfacedata.coatIOR.xxx;
break;
case DEBUGVIEW_LIT_SURFACEDATA_IOR:
result = surfacedata.ior.xxx;
break;
case DEBUGVIEW_LIT_SURFACEDATA_TRANSMITTANCE_COLOR:
result = surfacedata.transmittanceColor;
break;
case DEBUGVIEW_LIT_SURFACEDATA_AT_DISTANCE:
result = surfacedata.atDistance.xxx;
break;
}
}

break;
case DEBUGVIEW_LIT_BSDFDATA_COAT_IOR:
result = bsdfdata.coatIOR.xxx;
break;
case DEBUGVIEW_LIT_BSDFDATA_IOR:
result = bsdfdata.ior.xxx;
break;
case DEBUGVIEW_LIT_BSDFDATA_ABSORPTION_COEFFICIENT:
result = bsdfdata.absorptionCoefficient;
break;
}
}

227
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl


//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// SurfaceData and BSDFData
//-----------------------------------------------------------------------------

// TODO: Test if this is a win
// #define LIT_USE_BSDF_PRE_LAMBDAV
// Color pyramid (width, height, lodcount, Unused)
float4 _GaussianPyramidColorMipSize;
TEXTURE2D(_GaussianPyramidColorTexture);
SAMPLER2D(sampler_GaussianPyramidColorTexture);
// Depth pyramid (width, height, lodcount, Unused)
float4 _PyramidDepthMipSize;
TEXTURE2D(_PyramidDepthTexture);
SAMPLER2D(sampler_PyramidDepthTexture);
// Area light textures specific constant
SamplerState ltc_linear_clamp_sampler;
// TODO: This one should be set into a constant Buffer at pass frequency (with _Screensize)

// Combination need to be define in increasing "comlexity" order as define by FeatureFlagsToTileVariant
static const uint kFeatureVariantFlags[NUM_FEATURE_VARIANTS] =
{
// Precomputed illumination (no dynamic lights) for all material types (except for the clear coat)
/* 0 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_ENV | (MATERIAL_FEATURE_MASK_FLAGS & (~MATERIALFEATUREFLAGS_LIT_CLEAR_COAT)),
/* 0 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 1 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 2 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 3 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 4 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 1 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 2 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 3 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 4 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 5 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 5 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_SSS,
/* 6 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_LIT_SSS,
/* 7 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_SSS,
/* 8 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_SSS,
/* 9 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_SSS,
/* 6 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_SSS,
/* 7 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_LIT_SSS,
/* 8 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_SSS,
/* 9 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_SSS,
/* 10 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_SSS,
/* 10 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_ANISO,
/* 11 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_LIT_ANISO,
/* 12 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_ANISO,
/* 13 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_ANISO,
/* 14 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_ANISO,
/* 11 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_ANISO,
/* 12 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_LIT_ANISO,
/* 13 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_ANISO,
/* 14 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_ANISO,
/* 15 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_ANISO,
/* 15 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 16 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 17 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 18 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 19 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 16 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 17 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 18 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 19 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 20 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 20 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,
/* 21 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,
/* 22 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,
/* 23 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,
/* 24 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,
/* 21 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,
/* 22 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,
/* 23 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,
/* 24 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,
/* 25 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,
/* 25 */ LIGHT_FEATURE_MASK_FLAGS | MATERIAL_FEATURE_MASK_FLAGS, // Catch all case with MATERIAL_FEATURE_MASK_FLAGS is needed in case we disable material classification
/* 26 */ LIGHT_FEATURE_MASK_FLAGS | MATERIAL_FEATURE_MASK_FLAGS, // Catch all case with MATERIAL_FEATURE_MASK_FLAGS is needed in case we disable material classification
};
uint FeatureFlagsToTileVariant(uint featureFlags)

bsdfData.coatCoverage = coatCoverage;
}
void FillMaterialIdTransparencyData(float ior, float3 transmittanceColor, float atDistance, float thickness, inout BSDFData bsdfData)
{
// Uses thickness from SSS's property set
bsdfData.ior = ior;
// Absorption coefficient from Disney: http://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf
bsdfData.absorptionCoefficient = -log(transmittanceColor + 0.00001) / max(atDistance, 0.000001);
#if defined(_REFRACTION_THINPLANE)
bsdfData.thickness = 0.03;
#else
bsdfData.thickness = max(0.000001, thickness);
#endif
}
// For image based lighting, a part of the BSDF is pre-integrated.
// This is done both for specular and diffuse (in case of DisneyDiffuse)
void GetPreIntegratedFGD(float NdotV, float perceptualRoughness, float3 fresnel0, out float3 specularFGD, out float diffuseFGD)

FillMaterialIdStandardData(surfaceData.baseColor, surfaceData.metallic, bsdfData);
FillMaterialIdClearCoatData(surfaceData.coatNormalWS, surfaceData.coatCoverage, surfaceData.coatIOR, bsdfData);
}
#if defined(_REFRACTION_THINPLANE) || defined(_REFRACTION_THICKPLANE) || defined(_REFRACTION_THICKSPHERE)
// Note: Will override thickness of SSS's property set
FillMaterialIdTransparencyData(surfaceData.ior, surfaceData.transmittanceColor, surfaceData.atDistance, surfaceData.thickness, bsdfData);
#endif
return bsdfData;
}

}
//-----------------------------------------------------------------------------
// EvaluateBSDF_SSL
// ----------------------------------------------------------------------------
void EvaluateBSDF_SSL(float3 V, PositionInputs posInput, BSDFData bsdfData, out float3 diffuseLighting, out float3 specularLighting, out float2 weight)
{
diffuseLighting = float3(0.0, 0.0, 0.0);
specularLighting = float3(0.0, 0.0, 0.0);
weight = float2(0.0, 0.0);
#if defined(_REFRACTION_THINPLANE) || defined(_REFRACTION_THICKPLANE) || defined(_REFRACTION_THICKSPHERE)
// Refraction process:
// 1. Depending on the shape model, we calculate the refracted point in world space and the optical depth
// 2. We calculate the screen space position of the refracted point
// 3. If this point is available (ie: in color GBuffer and point is not in front of the object)
// a. Get the corresponding color depending on the roughness from the gaussian pyramid of the color buffer
// b. Multiply by the transmittance for absorption (depends on the optical depth)
weight.x = 1.0;
float3 refractedBackPointWS = float3(0.0, 0.0, 0.0);
float opticalDepth = 0.0;
// For all refraction approximation, to calculate the refracted point in world space,
// we approximate the scene as a plane (back plane) with normal -V at the depth hit point.
// (We avoid to raymarch the depth texture to get the refracted point.)
#if defined(_REFRACTION_THICKPLANE)
// Thick plane shape model:
// We approximate locally the shape of the object as halfspace defined by the normal {bsdfData.normallWS} at {bsdfData.positionWS}
// Thus, the light is refracted once.
// It approximate cubic filled shapes
//
// However, we can't approximate the optical depth of the object, so we use a constant as parameter ({bsdfData.thickness})
// Refracted ray
float3 R = refract(-V, bsdfData.normalWS, 1.0 / bsdfData.ior);
// Get the depth of the approximated back plane
float pyramidDepth = SAMPLE_TEXTURE2D_LOD(_PyramidDepthTexture, sampler_PyramidDepthTexture, posInput.positionSS, 2.0).r;
float depth = LinearEyeDepth(pyramidDepth, _ZBufferParams);
// Distance from point to the back plane
float distFromP = depth - posInput.depthVS;
float VoR = dot(-V, R);
refractedBackPointWS = posInput.positionWS + R * distFromP / VoR;
opticalDepth = bsdfData.thickness;
#elif defined(_REFRACTION_THICKSPHERE)
// Thick sphere shape model:
// We approximate locally the shape of the object as sphere, that is tangent to the shape.
// The sphere has a diameter of {bsdfData.thickness}
// The center of the sphere is at {bsdfData.positionWS} - {bsdfData.normalWS} * {bsdfData.thickness}
//
// So the light is refracted twice: in and out of the tangent sphere
// Get the depth of the approximated back plane
float pyramidDepth = SAMPLE_TEXTURE2D_LOD(_PyramidDepthTexture, sampler_PyramidDepthTexture, posInput.positionSS, 2.0).r;
float depth = LinearEyeDepth(pyramidDepth, _ZBufferParams);
// Distance from point to the back plane
float depthFromPosition = depth - posInput.depthVS;
// First refraction (tangent sphere in)
// Refracted ray
float3 R1 = refract(-V, bsdfData.normalWS, 1.0 / bsdfData.ior);
// Center of the tangent sphere
float3 C = posInput.positionWS - bsdfData.normalWS * bsdfData.thickness * 0.5;
// Second refraction (tangent sphere out)
float NoR1 = dot(bsdfData.normalWS, R1);
// Optical depth within the sphere
opticalDepth = -NoR1 * bsdfData.thickness;
// Out hit point in the tangent sphere
float3 P1 = posInput.positionWS + R1 * opticalDepth;
// Out normal
float3 N1 = normalize(C - P1);
// Out refracted ray
float3 R2 = refract(R1, N1, bsdfData.ior);
float N1oR2 = dot(N1, R2);
float VoR1 = dot(V, R1);
// Refracted source point
refractedBackPointWS = P1 - R2 * (depthFromPosition - NoR1 * VoR1 * bsdfData.thickness) / N1oR2;
#elif defined(_REFRACTION_THINPLANE)
// Thin plane shape model:
// We approximate locally the shape of the object as a plane with normal {bsdfData.normalWS} at {bsdfData.positionWS}
// with a thickness {bsdfData.thickness}
// Refracted ray
float3 R = refract(-V, bsdfData.normalWS, 1.0 / bsdfData.ior);
// Get the depth of the approximated back plane
float pyramidDepth = SAMPLE_TEXTURE2D_LOD(_PyramidDepthTexture, sampler_PyramidDepthTexture, posInput.positionSS, 2.0).r;
float depth = LinearEyeDepth(pyramidDepth, _ZBufferParams);
// Distance from point to the back plane
float distFromP = depth - posInput.depthVS;
// Optical depth within the thin plane
opticalDepth = bsdfData.thickness / dot(R, -bsdfData.normalWS);
// The refracted ray exiting the thin plane is the same as the incident ray (parallel interfaces and same ior)
float VoR = dot(-V, R);
float VoN = dot(V, bsdfData.normalWS);
refractedBackPointWS = posInput.positionWS + R * opticalDepth - V * (distFromP - VoR * opticalDepth);
#endif
// Calculate screen space coordinates of refracted point in back plane
float4 refractedBackPointCS = mul(_ViewProjMatrix, float4(refractedBackPointWS, 1.0));
float2 refractedBackPointSS = ComputeScreenSpacePosition(refractedBackPointCS);
float refractedBackPointDepth = LinearEyeDepth(SAMPLE_TEXTURE2D_LOD(_PyramidDepthTexture, sampler_PyramidDepthTexture, refractedBackPointSS, 0.0).r, _ZBufferParams);
// Exit if texel is out of color buffer
// Or if the texel is from an object in front of the object
if (refractedBackPointDepth < posInput.depthVS
|| any(refractedBackPointSS < 0.0)
|| any(refractedBackPointSS > 1.0))
{
diffuseLighting = SAMPLE_TEXTURE2D_LOD(_GaussianPyramidColorTexture, sampler_GaussianPyramidColorTexture, posInput.positionSS, 0.0).rgb;
return;
}
// Map the roughness to the correct mip map level of the color pyramid
float mipLevel = PerceptualRoughnessToMipmapLevel(bsdfData.perceptualRoughness);
diffuseLighting = SAMPLE_TEXTURE2D_LOD(_GaussianPyramidColorTexture, sampler_GaussianPyramidColorTexture, refractedBackPointSS.xy, mipLevel).rgb;
// Beer-Lamber law for absorption
float3 transmittance = exp(-bsdfData.absorptionCoefficient * opticalDepth);
diffuseLighting *= transmittance;
#else
// Use perfect flat transparency when we cannot fetch the correct pixel color for the refracted point
diffuseLighting = SAMPLE_TEXTURE2D_LOD(_GaussianPyramidColorTexture, sampler_GaussianPyramidColorTexture, posInput.positionSS, 0.0).rgb;
#endif
}
//-----------------------------------------------------------------------------
// EvaluateBSDF_Env
// ----------------------------------------------------------------------------

// TODO: we could call a function like PostBSDF that will apply albedo and divide by PI once for the loop
// envDiffuseLighting is not used in our case
diffuseLighting = (accLighting.dirDiffuseLighting + accLighting.punctualDiffuseLighting + accLighting.areaDiffuseLighting) * GTAOMultiBounce(lightLoopContext.directAmbientOcclusion, bsdfData.diffuseColor) + bakeDiffuseLighting;
// envDiffuseLighting is used for refraction
diffuseLighting = accLighting.envDiffuseLighting * accLighting.envDiffuseLightingWeight + (1.0 - accLighting.envDiffuseLightingWeight) * ((accLighting.dirDiffuseLighting + accLighting.punctualDiffuseLighting + accLighting.areaDiffuseLighting) * GTAOMultiBounce(lightLoopContext.directAmbientOcclusion, bsdfData.diffuseColor) + bakeDiffuseLighting);
specularLighting = accLighting.dirSpecularLighting + accLighting.punctualSpecularLighting + accLighting.areaSpecularLighting + accLighting.envSpecularLighting;
}

73
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader


_SpecularColor("SpecularColor", Color) = (1, 1, 1, 1)
_SpecularColorMap("SpecularColorMap", 2D) = "white" {}
// Wind
[ToggleOff] _EnableWind("Enable Wind", Float) = 0.0
_InitialBend("Initial Bend", float) = 1.0
_Stiffness("Stiffness", float) = 1.0
_Drag("Drag", float) = 1.0
_ShiverDrag("Shiver Drag", float) = 0.2
_ShiverDirectionality("Shiver Directionality", Range(0.0, 1.0)) = 0.5
[ToggleOff] _EnableFpsMode("Enable Fps Mode", Float) = 0.0
_FpsModeFov("_FpsModeFov", Float) = 60.0
[ToggleOff] _EnableFpsMode("Enable Fps Mode", Float) = 0.0
_FpsModeFov("_FpsModeFov", Float) = 60.0
_DistortionVectorMap("DistortionVectorMap", 2D) = "black" {}

[ToggleOff] _AlphaCutoffEnable("Alpha Cutoff Enable", Float) = 0.0
_AlphaCutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
// Transparency
[Enum(None, 0, ThickPlane, 1, ThickSphere, 2, ThinPlane, 3)]_RefractionMode("Refraction Mode", Int) = 0
_IOR("Indice Of Refraction", Range(1.0, 2.5)) = 1.0
_ThicknessMultiplier("Thickness Multiplier", Float) = 1.0
_TransmittanceColor("Transmittance Color", Color) = (1.0, 1.0, 1.0)
_ATDistance("Transmittance Absorption Distance", Float) = 1.0
// Stencil state
[HideInInspector] _StencilRef("_StencilRef", Int) = 2 // StencilLightingUsage.RegularLighting (fixed at compile time)

_PPDMinSamples("Min sample for POM", Range(1.0, 64.0)) = 5
_PPDMaxSamples("Max sample for POM", Range(1.0, 64.0)) = 15
_PPDLodThreshold("Start lod to fade out the POM effect", Range(0.0, 16.0)) = 5
[ToggleOff] _PerPixelDisplacementObjectScale("Per pixel displacement object scale", Float) = 1.0
// Displacement map
[ToggleOff] _EnableVertexDisplacement("Enable vertex displacement", Float) = 0.0
[ToggleOff] _VertexDisplacementObjectScale("Vertex displacement object scale", Float) = 1.0
[ToggleOff] _VertexDisplacementTilingScale("Vertex displacement tiling height scale", Float) = 1.0
// Wind
[ToggleOff] _EnableWind("Enable Wind", Float) = 0.0
_InitialBend("Initial Bend", float) = 1.0
_Stiffness("Stiffness", float) = 1.0
_Drag("Drag", float) = 1.0
_ShiverDrag("Shiver Drag", float) = 0.2
_ShiverDirectionality("Shiver Directionality", Range(0.0, 1.0)) = 0.5
// Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor"
// value that exist to identify if the GI emission need to be enabled.

#pragma shader_feature _DEPTHOFFSET_ON
#pragma shader_feature _DOUBLESIDED_ON
#pragma shader_feature _PER_PIXEL_DISPLACEMENT
#pragma shader_feature _PER_PIXEL_DISPLACEMENT_OBJECT_SCALE
#pragma shader_feature _VERTEX_DISPLACEMENT
#pragma shader_feature _VERTEX_DISPLACEMENT_OBJECT_SCALE
#pragma shader_feature _VERTEX_DISPLACEMENT_TILING_SCALE
#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _ _REFRACTION_THINPLANE _REFRACTION_THICKPLANE _REFRACTION_THICKSPHERE
#pragma shader_feature _ _MAPPING_PLANAR _MAPPING_TRIPLANAR
#pragma shader_feature _NORMALMAP_TANGENT_SPACE

#pragma shader_feature _SUBSURFACE_RADIUS_MAP
#pragma shader_feature _THICKNESSMAP
#pragma shader_feature _SPECULARCOLORMAP
#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _FPS_MODE
#pragma shader_feature _ _BLENDMODE_LERP _BLENDMODE_ADD _BLENDMODE_SOFT_ADD _BLENDMODE_MULTIPLY _BLENDMODE_PRE_MULTIPLY

#define UNITY_MATERIAL_LIT // Need to be define before including Material.hlsl
// Use surface gradient normal mapping as it handle correctly triplanar normal mapping and multiple UVSet
#define SURFACE_GRADIENT
// This shader support vertex modification
#define HAVE_VERTEX_MODIFICATION
//-------------------------------------------------------------------------------------
// Include

HLSLPROGRAM
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/LitSharePass.hlsl"
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL
}
// This pass is the same as GBuffer only it does not do alpha test (the clip instruction is removed)
// This is due to the fact that on GCN, any shader with a clip instruction cannot benefit from HiZ so when we do a prepass, in order to get the most performance, we need to make a special case in the subsequent GBuffer pass.
Pass
{
Name "GBufferWithPrepass" // Name is not used
Tags { "LightMode" = "GBufferWithPrepass" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
Stencil
{
Ref [_StencilRef]
Comp Always
Pass Replace
}
HLSLPROGRAM
#define SHADERPASS SHADERPASS_GBUFFER
#define _BYPASS_ALPHA_TEST
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/LitSharePass.hlsl"

58
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitData.hlsl


#include "../../../Core/ShaderLibrary/SampleUVMapping.hlsl"
#include "../MaterialUtilities.hlsl"
void DoAlphaTest(float alpha, float alphaCutoff)
{
// For Deferred:
// If we have a prepass, we need to remove the clip from the GBuffer pass (otherwise HiZ does not work on PS4)
// For Forward (Full forward or ForwardOnlyOpaque in deferred):
// Opaque geometry always has a depth pre-pass so we never want to do the clip here. For transparent we perform the clip as usual.
#if ((SHADER_PASS == SHADERPASS_GBUFFER) && !defined(_BYPASS_ALPHA_TEST)) || (SHADER_PASS == SHADERPASS_FORWARD && defined(SURFACE_TYPE_TRANSPARENT))
clip(alpha - alphaCutoff);
#endif
}
// TODO: move this function to commonLighting.hlsl once validated it work correctly
float GetSpecularOcclusionFromBentAO(float3 V, float3 bentNormalWS, SurfaceData surfaceData)
{

{
float maxDisplacement = 0.0;
#if defined(_HEIGHTMAP)
maxDisplacement = _HeightAmplitude;
maxDisplacement = abs(_HeightAmplitude); // _HeightAmplitude can be negative if min and max are inverted, but the max displacement must be positive
#endif
return maxDisplacement;
}

// Note: The TBN is not normalize as it is based on mikkt. We should normalize it, but POM is always use on simple enough surfarce that mean it is not required (save 2 normalize). Tag: SURFACE_GRADIENT
float3 viewDirTS = isPlanar ? float3(uvXZ, V.y) : TransformWorldToTangent(V, worldToTangent);
NdotV = viewDirTS.z;
int numSteps = (int)lerp(_PPDMaxSamples, _PPDMinSamples, viewDirTS.z);

float ComputePerVertexDisplacement(LayerTexCoord layerTexCoord, float4 vertexColor, float lod)
{
float height = (SAMPLE_UVMAPPING_TEXTURE2D_LOD(_HeightMap, sampler_HeightMap, layerTexCoord.base, lod).r - _HeightCenter) * _HeightAmplitude;
#ifdef _TESSELLATION_TILING_SCALE
#ifdef _VERTEX_DISPLACEMENT_TILING_SCALE
// When we change the tiling, we have want to conserve the ratio with the displacement (and this is consistent with per pixel displacement)
// IDEA: precompute the tiling scale? MOV-MUL vs MOV-MOV-MAX-RCP-MUL.
float tilingScale = rcp(max(_BaseColorMap_ST.x, _BaseColorMap_ST.y));

input.positionWS, input.worldToTangent[2].xyz, layerTexCoord);
}
void ApplyTessellationTileScale(inout float height0, inout float height1, inout float height2, inout float height3)
void ApplyDisplacementTileScale(inout float height0, inout float height1, inout float height2, inout float height3)
#ifdef _TESSELLATION_TILING_SCALE
#ifdef _VERTEX_DISPLACEMENT_TILING_SCALE
float tileObjectScale = 1.0;
#ifdef _LAYER_TILING_COUPLED_WITH_UNIFORM_OBJECT_SCALE
// Extract scaling from world transform

{
float maxDisplacement = 0.0;
// _HeightAmplitudeX can be negative if min and max are inverted, but the max displacement must be positive, take abs()
maxDisplacement = _HeightAmplitude0;
maxDisplacement = abs(_HeightAmplitude0);
maxDisplacement = max( _HeightAmplitude1
maxDisplacement = max( abs(_HeightAmplitude1)
+_HeightAmplitude0 * _InheritBaseHeight1
+ abs(_HeightAmplitude0) * _InheritBaseHeight1
#endif
, maxDisplacement);
#endif

maxDisplacement = max( _HeightAmplitude2
maxDisplacement = max( abs(_HeightAmplitude2)
+_HeightAmplitude0 * _InheritBaseHeight2
+ abs(_HeightAmplitude0) * _InheritBaseHeight2
#endif
, maxDisplacement);
#endif

#if defined(_HEIGHTMAP3)
maxDisplacement = max( _HeightAmplitude3
maxDisplacement = max( abs(_HeightAmplitude3)
+_HeightAmplitude0 * _InheritBaseHeight3
+ abs(_HeightAmplitude0) * _InheritBaseHeight3
#endif
, maxDisplacement);
#endif

float verticalDisplacement = maxHeight - height * maxHeight;
// IDEA: precompute the tiling scale? MOV-MUL vs MOV-MOV-MAX-RCP-MUL.
float tilingScale = rcp(max(_BaseColorMap0_ST.x, _BaseColorMap0_ST.y));
return tilingScale * verticalDisplacement / NdotV;
return tilingScale * verticalDisplacement / max(NdotV, 0.001);
}
return 0.0;

float height1 = (SAMPLE_UVMAPPING_TEXTURE2D_LOD(_HeightMap1, SAMPLER_HEIGHTMAP_IDX, layerTexCoord.base1, lod).r - _HeightCenter1) * _HeightAmplitude1;
float height2 = (SAMPLE_UVMAPPING_TEXTURE2D_LOD(_HeightMap2, SAMPLER_HEIGHTMAP_IDX, layerTexCoord.base2, lod).r - _HeightCenter2) * _HeightAmplitude2;
float height3 = (SAMPLE_UVMAPPING_TEXTURE2D_LOD(_HeightMap3, SAMPLER_HEIGHTMAP_IDX, layerTexCoord.base3, lod).r - _HeightCenter3) * _HeightAmplitude3;
ApplyTessellationTileScale(height0, height1, height2, height3); // Only apply with per vertex displacement
ApplyDisplacementTileScale(height0, height1, height2, height3); // Only apply with per vertex displacement
SetEnabledHeightByLayer(height0, height1, height2, height3);
float4 resultBlendMasks = inputBlendMasks;

float influenceFactor = BlendLayeredScalar(0.0, _InheritBaseNormal1, _InheritBaseNormal2, _InheritBaseNormal3, weights) * influenceMask;
// We will add smoothly the contribution of the normal map by lerping between vertex normal ( (0,0,1) in tangent space) and the actual normal from the main layer depending on the influence factor.
// Note: that we don't take details map into account here.
float3 mainNormalTS = lerp(float3(0.0, 0.0, 1.0), normalTS0, influenceFactor);
#ifdef SURFACE_GRADIENT
float3 neutralNormalTS = float3(0.0, 0.0, 0.0);
#else
float3 neutralNormalTS = float3(0.0, 0.0, 1.0);
#endif
float3 mainNormalTS = lerp(neutralNormalTS, normalTS0, influenceFactor);
// Add on our regular normal a bit of Main Layer normal base on influence factor. Note that this affect only the "visible" normal.
#ifdef SURFACE_GRADIENT

// (baseColor - meanColor) + lerp(meanColor, baseColor0, inheritBaseColor) simplify to
// saturate(influenceFactor * (baseColor0 - meanColor) + baseColor);
// There is a special case when baseColor < meanColor to avoid getting negative values.
float3 factor = baseColor > meanColor ? (baseColor0 - meanColor) : (baseColor0 * baseColor / meanColor - baseColor);
float3 factor = baseColor > meanColor ? (baseColor0 - meanColor) : (baseColor0 * baseColor / max(meanColor, 0.001) - baseColor); // max(to avoid divide by 0)
return influenceFactor * factor + baseColor;
}

float alpha = PROP_BLEND_SCALAR(alpha, weights);
#ifdef _ALPHATEST_ON
clip(alpha - _AlphaCutoff);
DoAlphaTest(alpha, _AlphaCutoff);
#endif
float3 normalTS;

surfaceData.coatCoverage = 0.0f;
surfaceData.coatIOR = 0.5;
// Transparency parameters
// Use thickness from SSS
surfaceData.ior = 1.0;
surfaceData.transmittanceColor = float3(1.0, 1.0, 1.0);
surfaceData.atDistance = 1000000.0;
GetNormalWS(input, V, normalTS, surfaceData.normalWS);
// Use bent normal to sample GI if available
// If any layer use a bent normal map, then bentNormalTS contain the interpolated result of bentnormal and normalmap (in case no bent normal are available)

#endif // #ifndef LAYERED_LIT_SHADER
#ifdef TESSELLATION_ON
#endif

29
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitDataInternal.hlsl


void ADD_IDX(ComputeLayerTexCoord)( float2 texCoord0, float2 texCoord1, float2 texCoord2, float2 texCoord3, float4 uvMappingMask, float4 uvMappingMaskDetail,
void ADD_IDX(ComputeLayerTexCoord)( float2 texCoord0, float2 texCoord1, float2 texCoord2, float2 texCoord3, float4 uvMappingMask, float4 uvMappingMaskDetail,
float3 positionWS, int mappingType, float worldScale, inout LayerTexCoord layerTexCoord, float additionalTiling = 1.0)
{
// Handle uv0, uv1, uv2, uv3 based on _UVMappingMask weight (exclusif 0..1)

// Perform alha test very early to save performance (a killed pixel will not sample textures)
#if defined(_ALPHATEST_ON) && !defined(LAYERED_LIT_SHADER)
clip(alpha - _AlphaCutoff);
DoAlphaTest(alpha, _AlphaCutoff);
#endif
float3 detailNormalTS = float3(0.0, 0.0, 0.0);

surfaceData.baseColor = SAMPLE_UVMAPPING_TEXTURE2D(ADD_IDX(_BaseColorMap), ADD_ZERO_IDX(sampler_BaseColorMap), ADD_IDX(layerTexCoord.base)).rgb * ADD_IDX(_BaseColor).rgb;
#ifdef _DETAIL_MAP_IDX
surfaceData.baseColor *= LerpWhiteTo(2.0 * saturate(detailAlbedo * ADD_IDX(_DetailAlbedoScale)), detailMask);
surfaceData.baseColor *= LerpWhiteTo(2.0 * detailAlbedo, detailMask * ADD_IDX(_DetailAlbedoScale));
// we saturate to avoid to have a smoothness value above 1
surfaceData.baseColor = saturate(surfaceData.baseColor);
#endif
surfaceData.specularOcclusion = 1.0; // Will be setup outside of this function

#endif
#ifdef _DETAIL_MAP_IDX
surfaceData.perceptualSmoothness *= LerpWhiteTo(2.0 * saturate(detailSmoothness * ADD_IDX(_DetailSmoothnessScale)), detailMask);
surfaceData.perceptualSmoothness *= LerpWhiteTo(2.0 * detailSmoothness, detailMask * ADD_IDX(_DetailSmoothnessScale));
// we saturate to avoid to have a smoothness value above 1
surfaceData.perceptualSmoothness = saturate(surfaceData.perceptualSmoothness);
#endif
// MaskMap is RGBA: Metallic, Ambient Occlusion (Optional), emissive Mask (Optional), Smoothness

surfaceData.specularColor *= SAMPLE_UVMAPPING_TEXTURE2D(_SpecularColorMap, sampler_SpecularColorMap, layerTexCoord.base).rgb;
#endif
#if defined(_REFRACTION_THINPLANE) || defined(_REFRACTION_THICKPLANE) || defined(_REFRACTION_THICKSPHERE)
surfaceData.ior = _IOR;
surfaceData.transmittanceColor = _TransmittanceColor;
surfaceData.atDistance = _ATDistance;
// Thickness already defined with SSS (from both thickness and thicknessMap)
surfaceData.thickness *= _ThicknessMultiplier;
#else
surfaceData.ior = 1.0;
surfaceData.transmittanceColor = float3(1.0, 1.0, 1.0);
surfaceData.atDistance = 1.0;
#endif
surfaceData.coatNormalWS = input.worldToTangent[2].xyz; // Assign vertex normal
surfaceData.coatCoverage = _CoatCoverage;
surfaceData.coatIOR = _CoatIOR;

surfaceData.coatNormalWS = float3(0.0, 0.0, 0.0);
surfaceData.coatCoverage = 0.0f;
surfaceData.coatIOR = 0.5;
// Transparency
surfaceData.ior = 1.0;
surfaceData.transmittanceColor = float3(1.0, 1.0, 1.0);
surfaceData.atDistance = 1000000.0;
#endif // #if !defined(LAYERED_LIT_SHADER)

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


float _EnableSpecularOcclusion;
// Transparency
float3 _TransmittanceColor;
float _IOR;
float _ATDistance;
float _ThicknessMultiplier;
// Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor"
// value that exist to identify if the GI emission need to be enabled.
// In our case we don't use such a mechanism but need to keep the code quiet. We declare the value and always enable it.

120
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.hlsl


float3 GetVertexDisplacement(float3 positionWS, float3 normalWS, float2 texCoord0, float2 texCoord1, float2 texCoord2, float2 texCoord3, float4 vertexColor, float3 objectScale)
{
// This call will work for both LayeredLit and Lit shader
LayerTexCoord layerTexCoord;
ZERO_INITIALIZE(LayerTexCoord, layerTexCoord);
GetLayerTexCoord(texCoord0, texCoord1, texCoord2, texCoord3, positionWS, normalWS, layerTexCoord);
// TODO: do this algorithm for lod fetching as lod not available in vertex/domain shader
// http://www.sebastiansylvan.com/post/the-problem-with-tessellation-in-directx-11/
float lod = 0.0;
float height = ComputePerVertexDisplacement(layerTexCoord, vertexColor, lod);
float3 displ = height * normalWS;
// Applying scaling of the object if requested
displ *= objectScale;
return displ;
}
void ApplyVertexModification(AttributesMesh input, float3 normalWS, float3 objectScale, inout float3 positionWS)
{
// If tessellation is enabled we apply displacement map after tessellation
#if defined(_VERTEX_DISPLACEMENT) && !defined(TESSELLATION_ON)
positionWS += GetVertexDisplacement(positionWS, normalWS,
#ifdef ATTRIBUTES_NEED_TEXCOORD0
input.uv0,
#else
float2(0.0, 0.0),
#endif
#ifdef ATTRIBUTES_NEED_TEXCOORD1
input.uv1,
#else
float2(0.0, 0.0),
#endif
#ifdef ATTRIBUTES_NEED_TEXCOORD2
input.uv2,
#else
float2(0.0, 0.0),
#endif
#ifdef ATTRIBUTES_NEED_TEXCOORD3
input.uv3,
#else
float2(0.0, 0.0),
#endif
#ifdef ATTRIBUTES_NEED_COLOR
input.color,
#else
float4(0.0, 0.0, 0.0, 0.0),
#endif
objectScale);
#endif
#ifdef _VERTEX_WIND
float3 rootWP = mul(GetObjectToWorldMatrix(), float4(0, 0, 0, 1)).xyz;
ApplyWindDisplacement(positionWS, normalWS, rootWP, _Stiffness, _Drag, _ShiverDrag, _ShiverDirectionality, _InitialBend, input.color.a, _Time);
#endif
}
#ifdef TESSELLATION_ON
float4 GetTessellationFactors(float3 p0, float3 p1, float3 p2, float3 n0, float3 n1, float3 n2)
{
float maxDisplacement = GetMaxDisplacement();

// y - 2->0 edge
// z - 0->1 edge
// w - inside tessellation factor
float3 GetTessellationDisplacement(VaryingsMeshToDS input)
void ApplyTessellationModification(VaryingsMeshToDS input, float3 normalWS, float3 objectScale, inout float3 positionWS)
// This call will work for both LayeredLit and Lit shader
LayerTexCoord layerTexCoord;
ZERO_INITIALIZE(LayerTexCoord, layerTexCoord);
GetLayerTexCoord(
#ifdef VARYINGS_DS_NEED_TEXCOORD0
#if defined(_VERTEX_DISPLACEMENT)
positionWS += GetVertexDisplacement(positionWS, normalWS,
#ifdef VARYINGS_DS_NEED_TEXCOORD0
#else
#else
#endif
#ifdef VARYINGS_DS_NEED_TEXCOORD1
#endif
#ifdef VARYINGS_DS_NEED_TEXCOORD1
#else
#else
#endif
#ifdef VARYINGS_DS_NEED_TEXCOORD2
#endif
#ifdef VARYINGS_DS_NEED_TEXCOORD2
#else
#else
#endif
#ifdef VARYINGS_DS_NEED_TEXCOORD3
#endif
#ifdef VARYINGS_DS_NEED_TEXCOORD3
#else
#else
#endif
input.positionWS,
input.normalWS,
layerTexCoord);
// http://www.sebastiansylvan.com/post/the-problem-with-tessellation-in-directx-11/
float lod = 0.0;
float4 vertexColor = float4(0.0, 0.0, 0.0, 0.0);
#ifdef VARYINGS_DS_NEED_COLOR
vertexColor = input.color;
#endif
float height = ComputePerVertexDisplacement(layerTexCoord, vertexColor, lod);
float3 displ = height * input.normalWS;
// Applying scaling of the object if requested
#ifdef _TESSELLATION_OBJECT_SCALE
displ *= input.objectScale;
#endif
#endif
#ifdef VARYINGS_DS_NEED_COLOR
input.color,
#else
float4(0.0, 0.0, 0.0, 0.0),
#endif
objectScale);
#endif // _VERTEX_DISPLACEMENT
}
return displ;
}
#endif // #ifdef TESSELLATION_ON

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


_SpecularColor("SpecularColor", Color) = (1, 1, 1, 1)
_SpecularColorMap("SpecularColorMap", 2D) = "white" {}
// Wind
[ToggleOff] _EnableWind("Enable Wind", Float) = 0.0
_InitialBend("Initial Bend", float) = 1.0
_Stiffness("Stiffness", float) = 1.0
_Drag("Drag", float) = 1.0
_ShiverDrag("Shiver Drag", float) = 0.2
_ShiverDirectionality("Shiver Directionality", Range(0.0, 1.0)) = 0.5
[ToggleOff] _EnableFpsMode("Enable Fps Mode", Float) = 0.0
[ToggleOff] _EnableFpsMode("Enable Fps Mode", Float) = 0.0
_FpsModeFov("_FpsModeFov", Float) = 60.0
_DistortionVectorMap("DistortionVectorMap", 2D) = "black" {}

[ToggleOff] _AlphaCutoffEnable("Alpha Cutoff Enable", Float) = 0.0
_AlphaCutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
// Transparency
[Enum(None, 0, ThickPlane, 1, ThickSphere, 2, ThinPlane, 3)]_RefractionMode("Refraction Mode", Int) = 0
_IOR("Indice Of Refraction", Range(1.0, 2.5)) = 1.0
_ThicknessMultiplier("Thickness Multiplier", Float) = 1.0
_TransmittanceColor("Transmittance Color", Color) = (1.0, 1.0, 1.0)
_ATDistance("Transmittance Absorption Distance", Float) = 1.0
// Stencil state
[HideInInspector] _StencilRef("_StencilRef", Int) = 2 // StencilLightingUsage.RegularLighting (fixed at compile time)

_PPDMinSamples("Min sample for POM", Range(1.0, 64.0)) = 5
_PPDMaxSamples("Max sample for POM", Range(1.0, 64.0)) = 15
_PPDLodThreshold("Start lod to fade out the POM effect", Range(0.0, 16.0)) = 5
[ToggleOff] _PerPixelDisplacementObjectScale("Per pixel displacement object scale", Float) = 1.0
// Displacement map
[ToggleOff] _EnableVertexDisplacement("Enable vertex displacement", Float) = 0.0
[ToggleOff] _VertexDisplacementObjectScale("Vertex displacement object scale", Float) = 1.0
[ToggleOff] _VertexDisplacementTilingScale("Vertex displacement tiling height scale", Float) = 1.0
// Wind
[ToggleOff] _EnableWind("Enable Wind", Float) = 0.0
_InitialBend("Initial Bend", float) = 1.0
_Stiffness("Stiffness", float) = 1.0
_Drag("Drag", float) = 1.0
_ShiverDrag("Shiver Drag", float) = 0.2
_ShiverDirectionality("Shiver Directionality", Range(0.0, 1.0)) = 0.5
// Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor"
// value that exist to identify if the GI emission need to be enabled.
// In our case we don't use such a mechanism but need to keep the code quiet. We declare the value and always enable it.

// Tessellation specific
[Enum(Phong, 0, Displacement, 1, DisplacementPhong, 2)] _TessellationMode("Tessellation mode", Float) = 0
[Enum(None, 0, Phong, 1)] _TessellationMode("Tessellation mode", Float) = 0
_TessellationFactor("Tessellation Factor", Range(0.0, 15.0)) = 4.0
_TessellationFactorMinDistance("Tessellation start fading distance", Float) = 20.0
_TessellationFactorMaxDistance("Tessellation end fading distance", Float) = 50.0

[ToggleOff] _TessellationObjectScale("Tessellation object scale", Float) = 0.0
[ToggleOff] _TessellationTilingScale("Tessellation tiling height scale", Float) = 1.0
// TODO: Handle culling mode for backface culling
}

#pragma shader_feature _DEPTHOFFSET_ON
#pragma shader_feature _DOUBLESIDED_ON
#pragma shader_feature _PER_PIXEL_DISPLACEMENT
// Default is _TESSELLATION_PHONG
#pragma shader_feature _ _TESSELLATION_DISPLACEMENT _TESSELLATION_DISPLACEMENT_PHONG
#pragma shader_feature _TESSELLATION_OBJECT_SCALE
#pragma shader_feature _TESSELLATION_TILING_SCALE
#pragma shader_feature _PER_PIXEL_DISPLACEMENT_OBJECT_SCALE
#pragma shader_feature _VERTEX_DISPLACEMENT
#pragma shader_feature _VERTEX_DISPLACEMENT_OBJECT_SCALE
#pragma shader_feature _VERTEX_DISPLACEMENT_TILING_SCALE
#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _TESSELLATION_PHONG
#pragma shader_feature _ _MAPPING_PLANAR _MAPPING_TRIPLANAR
#pragma shader_feature _NORMALMAP_TANGENT_SPACE

#pragma shader_feature _THICKNESSMAP
#pragma shader_feature _SPECULARCOLORMAP
#pragma shader_feature _VERTEX_WIND
#pragma shader_feature _FPS_MODE
#pragma shader_feature _ _BLENDMODE_LERP _BLENDMODE_ADD _BLENDMODE_SOFT_ADD _BLENDMODE_MULTIPLY _BLENDMODE_PRE_MULTIPLY

#define TESSELLATION_ON
// Use surface gradient normal mapping as it handle correctly triplanar normal mapping and multiple UVSet
#define SURFACE_GRADIENT
// This shader support vertex modification
#define HAVE_VERTEX_MODIFICATION
#define HAVE_TESSELLATION_MODIFICATION
//-------------------------------------------------------------------------------------
// Include

#pragma domain Domain
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/LitSharePass.hlsl"
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL
}
// This pass is the same as GBuffer only it does not do alpha test (the clip instruction is removed)
// This is due to the fact that on GCN, any shader with a clip instruction cannot benefit from HiZ so when we do a prepass, in order to get the most performance, we need to make a special case in the subsequent GBuffer pass.
Pass
{
Name "GBufferWithPrepass" // Name is not used
Tags { "LightMode" = "GBufferWithPrepass" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
Stencil
{
Ref [_StencilRef]
Comp Always
Pass Replace
}
HLSLPROGRAM
#pragma hull Hull
#pragma domain Domain
#define SHADERPASS SHADERPASS_GBUFFER
#define _BYPASS_ALPHA_TEST
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/LitSharePass.hlsl"

1
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.DisneyDiffuse.cs


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

1
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.GGX.cs


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

15
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitDepthPass.hlsl


#endif
// Attributes
#define REQUIRE_UV_FOR_TESSELATION (defined(TESSELLATION_ON) && (defined(_TESSELLATION_DISPLACEMENT) || defined(_TESSELLATION_DISPLACEMENT_PHONG)))
#define REQUIRE_VERTEX_COLOR_FOR_TESSELATION REQUIRE_UV_FOR_TESSELATION
#define REQUIRE_NORMAL defined(TESSELLATION_ON) || REQUIRE_TANGENT_TO_WORLD || defined(_VERTEX_WIND) || defined(_VERTEX_DISPLACEMENT)
#define REQUIRE_VERTEX_COLOR (defined(_VERTEX_DISPLACEMENT) && defined(LAYERED_LIT_SHADER) && (defined(_LAYER_MASK_VERTEX_COLOR_MUL) || defined(_LAYER_MASK_VERTEX_COLOR_ADD))) || defined(_VERTEX_WIND)
#if defined(TESSELLATION_ON) || REQUIRE_TANGENT_TO_WORLD || defined(_VERTEX_WIND)
#if REQUIRE_NORMAL
#ifdef _VERTEX_WIND
#if REQUIRE_VERTEX_COLOR
#define ATTRIBUTES_NEED_COLOR
#endif

// When UVX is present, we assume that UVX - 1 ... UV0 is present
#if REQUIRE_UV_FOR_TESSELATION || REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON)
#if defined(_VERTEX_DISPLACEMENT) || REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON)
#define ATTRIBUTES_NEED_TEXCOORD0
#ifdef LAYERED_LIT_SHADER
#define ATTRIBUTES_NEED_TEXCOORD1

#define ATTRIBUTES_NEED_TEXCOORD3
#endif
#endif
#endif
#if REQUIRE_VERTEX_COLOR_FOR_TESSELATION
#define ATTRIBUTES_NEED_COLOR
#endif
// Varying - Use for pixel shader

8
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitMetaPass.hlsl


#ifndef SHADERPASS
#ifndef SHADERPASS
#error Undefine_SHADERPASS
#endif

#define ATTRIBUTES_NEED_NORMAL
#endif
#if defined(LAYERED_LIT_SHADER) && (defined(_LAYER_MASK_VERTEX_COLOR_MUL) || defined(_LAYER_MASK_VERTEX_COLOR_ADD))
#define REQUIRE_VERTEX_COLOR defined(LAYERED_LIT_SHADER) && (defined(_LAYER_MASK_VERTEX_COLOR_MUL) || defined(_LAYER_MASK_VERTEX_COLOR_ADD))
#if REQUIRE_VERTEX_COLOR
#define ATTRIBUTES_NEED_COLOR
#endif

#if defined(LAYERED_LIT_SHADER) && (defined(_LAYER_MASK_VERTEX_COLOR_MUL) || defined(_LAYER_MASK_VERTEX_COLOR_ADD))
#if REQUIRE_VERTEX_COLOR
#define VARYINGS_NEED_COLOR
#endif

21
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitVelocityPass.hlsl


// conflict with the normal in the semantic. This need to be fix! Also no per pixel displacement is possible either.
// Attributes
#define REQUIRE_UV_FOR_TESSELATION (defined(TESSELLATION_ON) && (defined(_TESSELLATION_DISPLACEMENT) || defined(_TESSELLATION_DISPLACEMENT_PHONG)))
#define REQUIRE_VERTEX_COLOR_FOR_TESSELATION REQUIRE_UV_FOR_TESSELATION
#define REQUIRE_TANGENT_TO_WORLD 0 /* (defined(_HEIGHTMAP) && defined(_PER_PIXEL_DISPLACEMENT)) */
#define REQUIRE_TANGENT_TO_WORLD 0 /* (defined(_HEIGHTMAP) && defined(_PER_PIXEL_DISPLACEMENT)) */
#define REQUIRE_NORMAL 0 /* defined(TESSELLATION_ON) || REQUIRE_TANGENT_TO_WORLD || defined(_VERTEX_WIND) || defined(_VERTEX_DISPLACEMENT) */
#define REQUIRE_VERTEX_COLOR (defined(_VERTEX_DISPLACEMENT) && defined(LAYERED_LIT_SHADER) && (defined(_LAYER_MASK_VERTEX_COLOR_MUL) || defined(_LAYER_MASK_VERTEX_COLOR_ADD))) || defined(_VERTEX_WIND)
#if defined(TESSELLATION_ON) || REQUIRE_TANGENT_TO_WORLD || defined(_VERTEX_WIND)
// #define ATTRIBUTES_NEED_NORMAL - When reenable, think to also enable code in VertMesh.hlsl
#if REQUIRE_NORMAL
#define ATTRIBUTES_NEED_NORMAL
#ifdef _VERTEX_WIND
#if REQUIRE_VERTEX_COLOR
#define ATTRIBUTES_NEED_COLOR
#endif

// When UVX is present, we assume that UVX - 1 ... UV0 is present
#if defined(_ALPHATEST_ON)
#if defined(_VERTEX_DISPLACEMENT) || REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON)
#define ATTRIBUTES_NEED_TEXCOORD0
#ifdef LAYERED_LIT_SHADER
#define ATTRIBUTES_NEED_TEXCOORD1

#endif
#endif
#if REQUIRE_VERTEX_COLOR_FOR_TESSELATION
#define ATTRIBUTES_NEED_COLOR
#endif
// Varying - Use for pixel shader
// This second set of define allow to say which varyings will be output in the vertex (no more tesselation)

#define VARYINGS_NEED_POSITION_WS // Required to get view vector
#define VARYINGS_NEED_TANGENT_TO_WORLD
#endif

259
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringProfile.cs


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

BuildKernel();
}
public void Validate()
{
thicknessRemap.y = Mathf.Max(thicknessRemap.y, 0f);
thicknessRemap.x = Mathf.Clamp(thicknessRemap.x, 0f, thicknessRemap.y);
worldScale = Mathf.Max(worldScale, 0.001f);
// Old SSS Model >>>
var c = new Color();
c.r = Mathf.Max(0.05f, scatterDistance1.r);
c.g = Mathf.Max(0.05f, scatterDistance1.g);
c.b = Mathf.Max(0.05f, scatterDistance1.b);
c.a = 0.0f;
scatterDistance1 = c;
c.r = Mathf.Max(0.05f, scatterDistance2.r);
c.g = Mathf.Max(0.05f, scatterDistance2.g);
c.b = Mathf.Max(0.05f, scatterDistance2.b);
c.a = 0.0f;
scatterDistance2 = c;
// <<< Old SSS Model
BuildKernel();
}
// Ref: Approximate Reflectance Profiles for Efficient Subsurface Scattering by Pixar.
public void BuildKernel()
{

}
// Clamp to avoid artifacts.
m_ShapeParam = new Vector3();
m_ShapeParam.x = 1.0f / Mathf.Max(0.001f, scatteringDistance.r);
m_ShapeParam.y = 1.0f / Mathf.Max(0.001f, scatteringDistance.g);
m_ShapeParam.z = 1.0f / Mathf.Max(0.001f, scatteringDistance.b);

}
}
for (int i = 0; i < numProfiles; i++)
foreach (var profile in profiles)
// Skip unassigned profiles.
if (profiles[i] == null) continue;
profiles[i].thicknessRemap.y = Mathf.Max(profiles[i].thicknessRemap.y, 0);
profiles[i].thicknessRemap.x = Mathf.Clamp(profiles[i].thicknessRemap.x, 0, profiles[i].thicknessRemap.y);
profiles[i].worldScale = Mathf.Max(profiles[i].worldScale, 0.001f);
// Old SSS Model >>>
Color c = new Color();
c.r = Mathf.Max(0.05f, profiles[i].scatterDistance1.r);
c.g = Mathf.Max(0.05f, profiles[i].scatterDistance1.g);
c.b = Mathf.Max(0.05f, profiles[i].scatterDistance1.b);
c.a = 0.0f;
profiles[i].scatterDistance1 = c;
c.r = Mathf.Max(0.05f, profiles[i].scatterDistance2.r);
c.g = Mathf.Max(0.05f, profiles[i].scatterDistance2.g);
c.b = Mathf.Max(0.05f, profiles[i].scatterDistance2.b);
c.a = 0.0f;
profiles[i].scatterDistance2 = c;
// <<< Old SSS Model
profiles[i].BuildKernel();
if (profile != null)
profile.Validate();
}
UpdateCache();

// UpdateCache();
}
}
#if UNITY_EDITOR
[CustomEditor(typeof(SubsurfaceScatteringProfile))]
public class SubsurfaceScatteringProfileEditor : Editor
{
private class Styles
{
public readonly GUIContent sssProfilePreview0 = new GUIContent("Profile Preview");
public readonly GUIContent sssProfilePreview1 = new GUIContent("Shows the fraction of light scattered from the source (center).");
public readonly GUIContent sssProfilePreview2 = new GUIContent("The distance to the boundary of the image corresponds to the Max Radius.");
public readonly GUIContent sssProfilePreview3 = new GUIContent("Note that the intensity of pixels around the center may be clipped.");
public readonly GUIContent sssTransmittancePreview0 = new GUIContent("Transmittance Preview");
public readonly GUIContent sssTransmittancePreview1 = new GUIContent("Shows the fraction of light passing through the object for thickness values from the remap.");
public readonly GUIContent sssTransmittancePreview2 = new GUIContent("Can be viewed as a cross section of a slab of material illuminated by white light from the left.");
public readonly GUIContent sssProfileScatteringDistance = new GUIContent("Scattering Distance", "Determines the shape of the profile, and the blur radius of the filter per color channel. Alpha is ignored.");
public readonly GUIContent sssProfileTransmissionTint = new GUIContent("Transmission tint", "Color which tints transmitted light. Alpha is ignored.");
public readonly GUIContent sssProfileMaxRadius = new GUIContent("Max Radius", "Effective radius of the filter (in millimeters). The blur is energy-preserving, so a wide filter results in a large area with small contributions of individual samples. Reducing the distance increases the sharpness of the result.");
public readonly GUIContent sssTexturingMode = new GUIContent("Texturing Mode", "Specifies when the diffuse texture should be applied.");
public readonly GUIContent[] sssTexturingModeOptions = new GUIContent[2]
{
new GUIContent("Pre- and post-scatter", "Texturing is performed during both the lighting and the SSS passes. Slightly blurs the diffuse texture. Choose this mode if your diffuse texture contains little to no SSS lighting."),
new GUIContent("Post-scatter", "Texturing is performed only during the SSS pass. Effectively preserves the sharpness of the diffuse texture. Choose this mode if your diffuse texture already contains SSS lighting (e.g. a photo of skin).")
};
public readonly GUIContent sssProfileTransmissionMode = new GUIContent("Transmission Mode", "Configures the simulation of light passing through thin objects. Depends on the thickness value (which is applied in the normal direction).");
public readonly GUIContent[] sssTransmissionModeOptions = new GUIContent[3]
{
new GUIContent("None", "Disables transmission. Choose this mode for completely opaque, or very thick translucent objects."),
new GUIContent("Thin Object", "Choose this mode for thin objects, such as paper or leaves. Transmitted light reuses the shadowing state of the surface."),
new GUIContent("Regular", "Choose this mode for moderately thick objects. For performance reasons, transmitted light ignores occlusion (shadows).")
};
public readonly GUIContent sssProfileMinMaxThickness = new GUIContent("Min-Max Thickness", "Shows the values of the thickness remap below (in millimeters).");
public readonly GUIContent sssProfileThicknessRemap = new GUIContent("Thickness Remap", "Remaps the thickness parameter from [0, 1] to the desired range (in millimeters).");
public readonly GUIContent sssProfileWorldScale = new GUIContent("World Scale", "Size of the world unit in meters.");
// Old SSS Model >>>
public readonly GUIContent sssProfileScatterDistance1 = new GUIContent("Scattering Distance #1", "The radius (in centimeters) of the 1st Gaussian filter, one per color channel. Alpha is ignored. The blur is energy-preserving, so a wide filter results in a large area with small contributions of individual samples. Smaller values increase the sharpness.");
public readonly GUIContent sssProfileScatterDistance2 = new GUIContent("Scattering Distance #2", "The radius (in centimeters) of the 2nd Gaussian filter, one per color channel. Alpha is ignored. The blur is energy-preserving, so a wide filter results in a large area with small contributions of individual samples. Smaller values increase the sharpness.");
public readonly GUIContent sssProfileLerpWeight = new GUIContent("Filter Interpolation", "Controls linear interpolation between the two Gaussian filters.");
// <<< Old SSS Model
public readonly GUIStyle centeredMiniBoldLabel = new GUIStyle(GUI.skin.label);
public Styles()
{
centeredMiniBoldLabel.alignment = TextAnchor.MiddleCenter;
centeredMiniBoldLabel.fontSize = 10;
centeredMiniBoldLabel.fontStyle = FontStyle.Bold;
}
}
private static Styles styles
{
get
{
if (s_Styles == null)
{
s_Styles = new Styles();
}
return s_Styles;
}
}
private static Styles s_Styles = null;
private RenderTexture m_ProfileImage, m_TransmittanceImage;
private Material m_ProfileMaterial, m_TransmittanceMaterial;
private SerializedProperty m_ScatteringDistance, m_MaxRadius, m_ShapeParam, m_TransmissionTint,
m_TexturingMode, m_TransmissionMode, m_ThicknessRemap, m_WorldScale;
// Old SSS Model >>>
private SerializedProperty m_ScatterDistance1, m_ScatterDistance2, m_LerpWeight;
// <<< Old SSS Model
void OnEnable()
{
m_ScatteringDistance = serializedObject.FindProperty("scatteringDistance");
m_MaxRadius = serializedObject.FindProperty("m_MaxRadius");
m_ShapeParam = serializedObject.FindProperty("m_ShapeParam");
m_TransmissionTint = serializedObject.FindProperty("transmissionTint");
m_TexturingMode = serializedObject.FindProperty("texturingMode");
m_TransmissionMode = serializedObject.FindProperty("transmissionMode");
m_ThicknessRemap = serializedObject.FindProperty("thicknessRemap");
m_WorldScale = serializedObject.FindProperty("worldScale");
// Old SSS Model >>>
m_ScatterDistance1 = serializedObject.FindProperty("scatterDistance1");
m_ScatterDistance2 = serializedObject.FindProperty("scatterDistance2");
m_LerpWeight = serializedObject.FindProperty("lerpWeight");
// <<< Old SSS Model
// These shaders don't need to be reference by RenderPipelineResource as they are not use at runtime
m_ProfileMaterial = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/DrawSssProfile");
m_TransmittanceMaterial = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/DrawTransmittanceGraph");
m_ProfileImage = new RenderTexture(256, 256, 0, RenderTextureFormat.DefaultHDR);
m_TransmittanceImage = new RenderTexture( 16, 256, 0, RenderTextureFormat.DefaultHDR);
}
public override void OnInspectorGUI()
{
serializedObject.Update();
// Old SSS Model >>>
bool useDisneySSS;
{
HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
useDisneySSS = hdPipeline.sssSettings.useDisneySSS;
}
// <<< Old SSS Model
EditorGUI.BeginChangeCheck();
{
if (useDisneySSS)
{
EditorGUILayout.PropertyField(m_ScatteringDistance, styles.sssProfileScatteringDistance);
GUI.enabled = false;
EditorGUILayout.PropertyField(m_MaxRadius, styles.sssProfileMaxRadius);
GUI.enabled = true;
}
else
{
EditorGUILayout.PropertyField(m_ScatterDistance1, styles.sssProfileScatterDistance1);
EditorGUILayout.PropertyField(m_ScatterDistance2, styles.sssProfileScatterDistance2);
EditorGUILayout.PropertyField(m_LerpWeight, styles.sssProfileLerpWeight);
}
m_TexturingMode.intValue = EditorGUILayout.Popup(styles.sssTexturingMode, m_TexturingMode.intValue, styles.sssTexturingModeOptions);
m_TransmissionMode.intValue = EditorGUILayout.Popup(styles.sssProfileTransmissionMode, m_TransmissionMode.intValue, styles.sssTransmissionModeOptions);
EditorGUILayout.PropertyField(m_TransmissionTint, styles.sssProfileTransmissionTint);
EditorGUILayout.PropertyField(m_ThicknessRemap, styles.sssProfileMinMaxThickness);
Vector2 thicknessRemap = m_ThicknessRemap.vector2Value;
EditorGUILayout.MinMaxSlider(styles.sssProfileThicknessRemap, ref thicknessRemap.x, ref thicknessRemap.y, 0.0f, 50.0f);
m_ThicknessRemap.vector2Value = thicknessRemap;
EditorGUILayout.PropertyField(m_WorldScale, styles.sssProfileWorldScale);
EditorGUILayout.Space();
EditorGUILayout.LabelField(styles.sssProfilePreview0, styles.centeredMiniBoldLabel);
EditorGUILayout.LabelField(styles.sssProfilePreview1, EditorStyles.centeredGreyMiniLabel);
EditorGUILayout.LabelField(styles.sssProfilePreview2, EditorStyles.centeredGreyMiniLabel);
EditorGUILayout.LabelField(styles.sssProfilePreview3, EditorStyles.centeredGreyMiniLabel);
EditorGUILayout.Space();
}
float r = m_MaxRadius.floatValue;
Vector3 S = m_ShapeParam.vector3Value;
Vector4 T = m_TransmissionTint.colorValue;
Vector2 R = m_ThicknessRemap.vector2Value;
bool transmissionEnabled = m_TransmissionMode.intValue != (int)SubsurfaceScatteringProfile.TransmissionMode.None;
m_ProfileMaterial.SetFloat(HDShaderIDs._MaxRadius, r);
m_ProfileMaterial.SetVector(HDShaderIDs._ShapeParam, S);
// Old SSS Model >>>
Utilities.SelectKeyword(m_ProfileMaterial, "SSS_MODEL_DISNEY", "SSS_MODEL_BASIC", useDisneySSS);
// Apply the three-sigma rule, and rescale.
float s = (1.0f / 3.0f) * SssConstants.SSS_BASIC_DISTANCE_SCALE;
float rMax = Mathf.Max(m_ScatterDistance1.colorValue.r, m_ScatterDistance1.colorValue.g, m_ScatterDistance1.colorValue.b,
m_ScatterDistance2.colorValue.r, m_ScatterDistance2.colorValue.g, m_ScatterDistance2.colorValue.b);
Vector4 stdDev1 = s * m_ScatterDistance1.colorValue;
Vector4 stdDev2 = s * m_ScatterDistance2.colorValue;
m_ProfileMaterial.SetVector(HDShaderIDs._StdDev1, stdDev1);
m_ProfileMaterial.SetVector(HDShaderIDs._StdDev2, stdDev2);
m_ProfileMaterial.SetFloat(HDShaderIDs._LerpWeight, m_LerpWeight.floatValue);
m_ProfileMaterial.SetFloat(HDShaderIDs._MaxRadius, rMax);
// <<< Old SSS Model
// Draw the profile.
EditorGUI.DrawPreviewTexture(GUILayoutUtility.GetRect(256, 256), m_ProfileImage, m_ProfileMaterial, ScaleMode.ScaleToFit, 1.0f);
EditorGUILayout.Space();
EditorGUILayout.LabelField(styles.sssTransmittancePreview0, styles.centeredMiniBoldLabel);
EditorGUILayout.LabelField(styles.sssTransmittancePreview1, EditorStyles.centeredGreyMiniLabel);
EditorGUILayout.LabelField(styles.sssTransmittancePreview2, EditorStyles.centeredGreyMiniLabel);
EditorGUILayout.Space();
// Old SSS Model >>>
// Multiply by 0.1 to convert from millimeters to centimeters. Apply the distance scale.
float a = 0.1f * SssConstants.SSS_BASIC_DISTANCE_SCALE;
Vector4 halfRcpVarianceAndWeight1 = new Vector4(a * a * 0.5f / (stdDev1.x * stdDev1.x), a * a * 0.5f / (stdDev1.y * stdDev1.y), a * a * 0.5f / (stdDev1.z * stdDev1.z), 4 * (1.0f - m_LerpWeight.floatValue));
Vector4 halfRcpVarianceAndWeight2 = new Vector4(a * a * 0.5f / (stdDev2.x * stdDev2.x), a * a * 0.5f / (stdDev2.y * stdDev2.y), a * a * 0.5f / (stdDev2.z * stdDev2.z), 4 * m_LerpWeight.floatValue);
m_TransmittanceMaterial.SetVector(HDShaderIDs._HalfRcpVarianceAndWeight1, halfRcpVarianceAndWeight1);
m_TransmittanceMaterial.SetVector(HDShaderIDs._HalfRcpVarianceAndWeight2, halfRcpVarianceAndWeight2);
// <<< Old SSS Model
m_TransmittanceMaterial.SetVector(HDShaderIDs._ShapeParam, S);
m_TransmittanceMaterial.SetVector(HDShaderIDs._TransmissionTint, transmissionEnabled ? T : Vector4.zero);
m_TransmittanceMaterial.SetVector(HDShaderIDs._ThicknessRemap, R);
// Draw the transmittance graph.
EditorGUI.DrawPreviewTexture(GUILayoutUtility.GetRect(16, 16), m_TransmittanceImage, m_TransmittanceMaterial, ScaleMode.ScaleToFit, 16.0f);
serializedObject.ApplyModifiedProperties();
if (EditorGUI.EndChangeCheck())
{
HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
// Validate each individual asset and update caches.
hdPipeline.sssSettings.OnValidate();
}
}
}
#endif
}

1
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/BaseUnlitUI.cs


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

1
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/UnlitUI.cs


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

1
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
using System;
//-----------------------------------------------------------------------------

3
ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/HDRenderPipelineResources.asset


type: 3}
volumetricLightingCS: {fileID: 7200000, guid: 799166e2ee6a4b041bba9e74f6942097,
type: 3}
gaussianPyramidCS: {fileID: 7200000, guid: 6dba4103d23a7904fbc49099355aff3e, type: 3}
depthPyramidCS: {fileID: 7200000, guid: 64a553bb564274041906f78ffba955e4, type: 3}
copyChannelCS: {fileID: 7200000, guid: a68d8aaeb0956234d94e389f196381ee, type: 3}
clearDispatchIndirectShader: {fileID: 7200000, guid: fc1f553acb80a6446a32d33e403d0656,
type: 3}
buildDispatchIndirectShader: {fileID: 7200000, guid: 4eb1b418be7044c40bb5200496c50f14,

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


fileFormatVersion: 2
guid: 42086e81f4f0c724f96f7f09cc995354
timeCreated: 1505146899
timeCreated: 1507124092
licenseType: Pro
NativeFormatImporter:
externalObjects: {}

60
ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/RenderPipelineResources.cs


{
public class RenderPipelineResources : ScriptableObject
{
#if UNITY_EDITOR
public static string GetRenderPipelineResourcesPath()
{
return Utilities.GetHDRenderPipelinePath() + "RenderPipelineResources/HDRenderPipelineResources.asset";
}
// TODO skybox/cubemap
[UnityEditor.MenuItem("RenderPipeline/HDRenderPipeline/Create Resources Asset", false, 15)]
static void CreateRenderPipelineResources()
{
var instance = CreateInstance<RenderPipelineResources>();
string HDRenderPipelinePath = Utilities.GetHDRenderPipelinePath();
instance.debugDisplayLatlongShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Debug/DebugDisplayLatlong.Shader");
instance.debugViewMaterialGBufferShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Debug/DebugViewMaterialGBuffer.Shader");
instance.debugViewTilesShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Debug/DebugViewTiles.Shader");
instance.debugFullScreenShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Debug/DebugFullScreen.Shader");
instance.deferredShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Lighting/Deferred.Shader");
instance.screenSpaceAmbientOcclusionShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Lighting/AmbientOcclusion/ScreenSpaceAmbientOcclusion.Shader");
instance.subsurfaceScatteringCS = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Material/Lit/Resources/SubsurfaceScattering.compute");
instance.volumetricLightingCS = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/Volumetrics/Resources/VolumetricLighting.compute");
instance.clearDispatchIndirectShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/cleardispatchindirect.compute");
instance.buildDispatchIndirectShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/builddispatchindirect.compute");
instance.buildScreenAABBShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/scrbound.compute");
instance.buildPerTileLightListShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/lightlistbuild.compute");
instance.buildPerBigTileLightListShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/lightlistbuild-bigtile.compute");
instance.buildPerVoxelLightListShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/lightlistbuild-clustered.compute");
instance.buildMaterialFlagsShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/materialflags.compute");
instance.deferredComputeShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/Deferred.compute");
instance.deferredDirectionalShadowComputeShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/DeferredDirectionalShadow.compute");
// SceneSettings
// These shaders don't need to be reference by RenderPipelineResource as they are not use at runtime (only to draw in editor)
// instance.drawSssProfile = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "SceneSettings/DrawSssProfile.shader");
// instance.drawTransmittanceGraphShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "SceneSettings/DrawTransmittanceGraph.shader");
instance.cameraMotionVectors = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "RenderPipelineResources/CameraMotionVectors.shader");
// Sky
instance.blitCubemap = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Sky/BlitCubemap.shader");
instance.buildProbabilityTables = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Sky/BuildProbabilityTables.compute");
instance.computeGgxIblSampleData = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Sky/ComputeGgxIblSampleData.compute");
instance.GGXConvolve = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Sky/GGXConvolve.shader");
// Skybox/Cubemap is a builtin shader, must use Sahder.Find to access it. It is fine because we are in the editor
instance.skyboxCubemap = Shader.Find("Skybox/Cubemap");
UnityEditor.AssetDatabase.CreateAsset(instance, GetRenderPipelineResourcesPath());
UnityEditor.AssetDatabase.SaveAssets();
UnityEditor.AssetDatabase.Refresh();
}
#endif
// Debug
public Shader debugDisplayLatlongShader;
public Shader debugViewMaterialGBufferShader;

public Shader screenSpaceAmbientOcclusionShader;
public ComputeShader subsurfaceScatteringCS;
public ComputeShader volumetricLightingCS;
public ComputeShader gaussianPyramidCS;
public ComputeShader depthPyramidCS;
public ComputeShader copyChannelCS;
// Lighting tile pass resources
public ComputeShader clearDispatchIndirectShader;

4
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Editor/CommonSettingsEditor.cs


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

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


Pass
{
Cull Off
ZTest Off
ZTest Always
ZWrite Off
Blend Off

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


Pass
{
Cull Off
ZTest Off
ZTest Always
ZWrite Off
Blend Off

2
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/SceneSettings.cs


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

1
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/SceneSettingsManager.cs


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

1
ScriptableRenderPipeline/HDRenderPipeline/ShaderConfig.cs


using UnityEngine;
using UnityEngine.Rendering;
using System;
//-----------------------------------------------------------------------------
// Configuration

1
ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPass.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
using System;
//-----------------------------------------------------------------------------

13
ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/TessellationShare.hlsl


VaryingsToDS varying = InterpolateWithBaryCoordsToDS(varying0, varying1, varying2, baryCoords);
// We have Phong tessellation in all case where we don't have displacement only
#ifndef _TESSELLATION_DISPLACEMENT
#ifdef _TESSELLATION_PHONG
float3 p0 = varying0.vmesh.positionWS;
float3 p1 = varying1.vmesh.positionWS;

baryCoords, _TessellationShapeFactor);
#endif
#if defined(_TESSELLATION_DISPLACEMENT) || defined(_TESSELLATION_DISPLACEMENT_PHONG)
varying.vmesh.positionWS += GetTessellationDisplacement(varying.vmesh);
#ifdef HAVE_TESSELLATION_MODIFICATION
// TODO: This should be an uniform for the object, this code should be remove (and is specific to Lit.shader) once we have it. - Workaround for now
// Extract scaling from world transform
#ifdef _VERTEX_DISPLACEMENT_OBJECT_SCALE
float3 objectScale = varying.vmesh.objectScale;
#else
float3 objectScale = float3(1.0, 1.0, 1.0);
#endif
ApplyTessellationModification(varying.vmesh, varying.vmesh.normalWS, objectScale, varying.vmesh.positionWS);
#endif
return VertTesselation(varying);

10
ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/VaryingMesh.hlsl


#ifdef VARYINGS_DS_NEED_COLOR
float4 color;
#endif
#ifdef _TESSELLATION_OBJECT_SCALE
#ifdef _VERTEX_DISPLACEMENT_OBJECT_SCALE
float3 objectScale;
#endif
};

float4 interpolators5 : TEXCOORD2;
#endif
#ifdef _TESSELLATION_OBJECT_SCALE
#ifdef _VERTEX_DISPLACEMENT_OBJECT_SCALE
float3 interpolators6 : TEXCOORD3;
#endif
};

#ifdef VARYINGS_DS_NEED_COLOR
output.interpolators5 = input.color;
#endif
#ifdef _TESSELLATION_OBJECT_SCALE
#ifdef _VERTEX_DISPLACEMENT_OBJECT_SCALE
output.interpolators6 = input.objectScale;
#endif

#ifdef VARYINGS_DS_NEED_COLOR
output.color = input.interpolators5;
#endif
#ifdef _TESSELLATION_OBJECT_SCALE
#ifdef _VERTEX_DISPLACEMENT_OBJECT_SCALE
output.objectScale = input.interpolators6;
#endif
return output;

TESSELLATION_INTERPOLATE_BARY(color, baryCoords);
#endif
#ifdef _TESSELLATION_OBJECT_SCALE
#ifdef _VERTEX_DISPLACEMENT_OBJECT_SCALE
// objectScale doesn't change for the whole object.
ouput.objectScale = input0.objectScale;
#endif

43
ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/VertMesh.hlsl


VaryingsMeshType output;
float3 positionWS = TransformObjectToWorld(input.positionOS);
#if defined(ATTRIBUTES_NEED_NORMAL)
#ifdef ATTRIBUTES_NEED_NORMAL
#else
float3 normalWS = float3(0.0, 0.0, 0.0); // We need this case to be able to compile ApplyVertexModification that doesn't use normal.
float4 tangentWS = float4(0.0, 0.0, 0.0, 0.0);
float4 vertexColor = float4(0.0, 0.0, 0.0, 0.0);
#if defined(VARYINGS_NEED_TANGENT_TO_WORLD) || defined(VARYINGS_DS_NEED_TANGENT)
tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
#ifdef ATTRIBUTES_NEED_TANGENT
float4 tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
#if defined(VARYINGS_NEED_COLOR) || defined(VARYINGS_DS_NEED_COLOR)
vertexColor = input.color;
// TODO: This should be an uniform for the object, this code should be remove (and is specific to Lit.shader) once we have it. - Workaround for now
// Extract scaling from world transform
#ifdef _VERTEX_DISPLACEMENT_OBJECT_SCALE
float3 objectScale;
float4x4 worldTransform = GetObjectToWorldMatrix();
objectScale.x = length(float3(worldTransform._m00, worldTransform._m01, worldTransform._m02));
objectScale.y = length(float3(worldTransform._m10, worldTransform._m11, worldTransform._m12));
objectScale.z = length(float3(worldTransform._m20, worldTransform._m21, worldTransform._m22));
#else
float3 objectScale = float3(1.0, 1.0, 1.0);
// TODO: deal with camera center rendering and instancing (This is the reason why we always perform two steps transform to clip space + instancing matrix)
#if defined(_VERTEX_WIND) && (SHADERPASS != SHADERPASS_VELOCITY)
float3 rootWP = mul(GetObjectToWorldMatrix(), float4(0, 0, 0, 1)).xyz;
ApplyWind(positionWS, normalWS, rootWP, _Stiffness, _Drag, _ShiverDrag, _ShiverDirectionality, _InitialBend, input.color.a, _Time);
#if defined(HAVE_VERTEX_MODIFICATION) && (SHADERPASS != SHADERPASS_VELOCITY)
ApplyVertexModification(input, normalWS, objectScale, positionWS);
#endif
#if _FPS_MODE

#ifdef TESSELLATION_ON
output.positionWS = positionWS;
#ifdef _TESSELLATION_OBJECT_SCALE
// Extract scaling from world transform
float4x4 worldTransform = GetObjectToWorldMatrix();
output.objectScale.x = length(float3(worldTransform._m00, worldTransform._m01, worldTransform._m02));
output.objectScale.y = length(float3(worldTransform._m10, worldTransform._m11, worldTransform._m12));
output.objectScale.z = length(float3(worldTransform._m20, worldTransform._m21, worldTransform._m22));
#ifdef _VERTEX_DISPLACEMENT_OBJECT_SCALE
// TODO: This should be an uniform for the object, this code should be remove (and is specific to Lit.shader) once we have it. - Workaround for now
output.objectScale = objectScale;
// TODO: deal with camera center rendering and instancing (This is the reason why we always perform tow steps transform to clip space + instancing matrix)
// TODO: TEMP: Velocity has a flow as it doens't have normal. This need to be fix. In the mean time, generate fix normal so compiler doesn't complain - When fix, think to also enable ATTRIBUTES_NEED_NORMAL in LitVelocityPass.hlsl
#if SHADERPASS == SHADERPASS_VELOCITY
output.normalWS = float3(0.0, 0.0, 1.0);

output.tangentWS = tangentWS;
#endif
#else
// TODO deal with camera center rendering and instancing (This is the reason why we always perform tow steps transform to clip space + instancing matrix)
#ifdef VARYINGS_NEED_POSITION_WS
output.positionWS = positionWS;
#endif

output.texCoord3 = input.uv3;
#endif
#if defined(VARYINGS_NEED_COLOR) || defined(VARYINGS_DS_NEED_COLOR)
output.color = vertexColor;
output.color = input.color;
#endif
return output;

8
ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesFunctions.hlsl


// Otherwise, depth comparisons become meaningless!
float4x4 trViewMat = transpose(GetWorldToViewMatrix());
float3 rotCamPos = trViewMat[3].xyz;
float3 viewPositionWS = mul((float3x3)trViewMat, -rotCamPos);
// When USE_LEGACY_UNITY_MATRIX_VARIABLES is define GetWorldToViewMatrix is absolute (because it use legacy unity matrix), but if not define it use our own variable that is camera relative.
#ifdef USE_LEGACY_UNITY_MATRIX_VARIABLES
return GetCameraRelativePositionWS(viewPositionWS);
#else
return viewPositionWS;
#endif
return mul((float3x3)trViewMat, -rotCamPos);
#endif
}

6
ScriptableRenderPipeline/HDRenderPipeline/Sky/GGXConvolve.shader


{
Pass
{
Cull Off
ZTest Always
ZTest Always
Blend One Zero
Cull Off
Blend Off
HLSLPROGRAM
#pragma target 4.5

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Editor/HDRISkyEditor.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

12
ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/HDRISkyRenderer.cs


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

public override void Build()
{
m_SkyHDRIMaterial = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/Sky/SkyHDRI");
m_SkyHDRIMaterial = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/Sky/SkyHDRI");
Utilities.Destroy(m_SkyHDRIMaterial);
CoreUtils.Destroy(m_SkyHDRIMaterial);
}
public override void SetRenderTargets(BuiltinSkyParameters builtinParams)

Utilities.SetRenderTarget(builtinParams.commandBuffer, builtinParams.colorBuffer);
CoreUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.colorBuffer);
Utilities.SetRenderTarget(builtinParams.commandBuffer, builtinParams.colorBuffer, builtinParams.depthBuffer);
CoreUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.colorBuffer, builtinParams.depthBuffer);
}
}

MaterialPropertyBlock properties = new MaterialPropertyBlock();
properties.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, builtinParams.pixelCoordToViewDirMatrix);
Utilities.DrawFullScreen(builtinParams.commandBuffer, m_SkyHDRIMaterial, properties, renderForCubemap ? 0 : 1);
CoreUtils.DrawFullScreen(builtinParams.commandBuffer, m_SkyHDRIMaterial, properties, renderForCubemap ? 0 : 1);
}
public override bool IsSkyValid()

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


{
ZWrite Off
ZTest Always
Blend One Zero
Blend Off
Cull Off
HLSLPROGRAM

{
ZWrite Off
ZTest LEqual
Blend One Zero
Blend Off
Cull Off
HLSLPROGRAM

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/Editor/ProceduralSkyEditor.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

10
ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkyRenderer.cs


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

public override void Build()
{
m_ProceduralSkyMaterial = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/Sky/SkyProcedural");
m_ProceduralSkyMaterial = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/Sky/SkyProcedural");
Utilities.Destroy(m_ProceduralSkyMaterial);
CoreUtils.Destroy(m_ProceduralSkyMaterial);
}
public override bool IsSkyValid()

{
// We do not bind the depth buffer as a depth-stencil target since it is
// bound as a color texture which is then sampled from within the shader.
Utilities.SetRenderTarget(builtinParams.commandBuffer, builtinParams.colorBuffer);
CoreUtils.SetRenderTarget(builtinParams.commandBuffer, builtinParams.colorBuffer);
}
void SetKeywords(BuiltinSkyParameters builtinParams, ProceduralSkySettings param, bool renderForCubemap)

// Set shader constants.
SetUniforms(builtinParams, m_ProceduralSkySettings, renderForCubemap, ref properties);
Utilities.DrawFullScreen(builtinParams.commandBuffer, m_ProceduralSkyMaterial, properties);
CoreUtils.DrawFullScreen(builtinParams.commandBuffer, m_ProceduralSkyMaterial, properties);
}
}
}

17
ScriptableRenderPipeline/HDRenderPipeline/Sky/RuntimeFilterIBL.cs


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

if (!m_GgxConvolveMaterial)
{
m_GgxConvolveMaterial = Utilities.CreateEngineMaterial(m_RenderPipelinesResources.GGXConvolve);
m_GgxConvolveMaterial = CoreUtils.CreateEngineMaterial(m_RenderPipelinesResources.GGXConvolve);
}
if (!m_GgxIblSampleData)

m_ComputeGgxIblSampleDataCS.SetTexture(m_ComputeGgxIblSampleDataKernel, "output", m_GgxIblSampleData);
using (new Utilities.ProfilingSample("Compute GGX IBL Sample Data", cmd))
using (new ProfilingSample(cmd, "Compute GGX IBL Sample Data"))
cmd.DispatchCompute(m_ComputeGgxIblSampleDataCS, m_ComputeGgxIblSampleDataKernel, 1, 1, 1);
cmd.DispatchCompute(m_ComputeGgxIblSampleDataCS, m_ComputeGgxIblSampleDataKernel, 1, 1, 1);
}
}
}

props.SetFloat("_Level", mip);
props.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, transform);
Utilities.SetRenderTarget(cmd, target, ClearFlag.ClearNone, mip, (CubemapFace)face);
Utilities.DrawFullScreen(cmd, m_GgxConvolveMaterial, props);
CoreUtils.SetRenderTarget(cmd, target, ClearFlag.None, mip, (CubemapFace)face);
CoreUtils.DrawFullScreen(cmd, m_GgxConvolveMaterial, props);
}
cmd.EndSample(sampleName);
}

int numRows = conditionalCdf.height;
using (new Utilities.ProfilingSample("Build Probability Tables", cmd))
using (new ProfilingSample(cmd, "Build Probability Tables"))
cmd.DispatchCompute(m_BuildProbabilityTablesCS, m_ConditionalDensitiesKernel, numRows, 1, 1);
cmd.DispatchCompute(m_BuildProbabilityTablesCS, m_MarginalRowDensitiesKernel, 1, 1, 1);
cmd.DispatchCompute(m_BuildProbabilityTablesCS, m_ConditionalDensitiesKernel, numRows, 1, 1);
cmd.DispatchCompute(m_BuildProbabilityTablesCS, m_MarginalRowDensitiesKernel, 1, 1, 1);
}
m_GgxConvolveMaterial.EnableKeyword("USE_MIS");

46
ScriptableRenderPipeline/HDRenderPipeline/Sky/SkyManager.cs


if ((m_SkyboxCubemapRT != null) && (m_SkyboxCubemapRT.width != resolution))
{
Utilities.Destroy(m_SkyboxCubemapRT);
Utilities.Destroy(m_SkyboxGGXCubemapRT);
Utilities.Destroy(m_SkyboxMarginalRowCdfRT);
Utilities.Destroy(m_SkyboxConditionalCdfRT);
CoreUtils.Destroy(m_SkyboxCubemapRT);
CoreUtils.Destroy(m_SkyboxGGXCubemapRT);
CoreUtils.Destroy(m_SkyboxMarginalRowCdfRT);
CoreUtils.Destroy(m_SkyboxConditionalCdfRT);
m_SkyboxCubemapRT = null;
m_SkyboxGGXCubemapRT = null;

m_faceWorldToViewMatrixMatrices[i] = worldToView;
m_facePixelCoordToViewDirMatrices[i] = ComputePixelCoordToWorldSpaceViewDirectionMatrix(0.5f * Mathf.PI, screenSize, worldToView, true);
m_faceCameraInvViewProjectionMatrix[i] = Utilities.GetViewProjectionMatrix(lookAt, cubeProj).inverse;
m_faceCameraInvViewProjectionMatrix[i] = HDUtils.GetViewProjectionMatrix(lookAt, cubeProj).inverse;
}
}

m_iblFilterGgx = new IBLFilterGGX(renderPipelinesResources);
// TODO: We need to have an API to send our sky information to Enlighten. For now use a workaround through skybox/cubemap material...
m_StandardSkyboxMaterial = Utilities.CreateEngineMaterial(renderPipelinesResources.skyboxCubemap);
m_StandardSkyboxMaterial = CoreUtils.CreateEngineMaterial(renderPipelinesResources.skyboxCubemap);
m_BlitCubemapMaterial = Utilities.CreateEngineMaterial(renderPipelinesResources.blitCubemap);
m_BlitCubemapMaterial = CoreUtils.CreateEngineMaterial(renderPipelinesResources.blitCubemap);
m_CurrentUpdateTime = 0.0f;
}

Utilities.Destroy(m_StandardSkyboxMaterial);
Utilities.Destroy(m_SkyboxCubemapRT);
Utilities.Destroy(m_SkyboxGGXCubemapRT);
Utilities.Destroy(m_SkyboxMarginalRowCdfRT);
Utilities.Destroy(m_SkyboxConditionalCdfRT);
CoreUtils.Destroy(m_StandardSkyboxMaterial);
CoreUtils.Destroy(m_SkyboxCubemapRT);
CoreUtils.Destroy(m_SkyboxGGXCubemapRT);
CoreUtils.Destroy(m_SkyboxMarginalRowCdfRT);
CoreUtils.Destroy(m_SkyboxConditionalCdfRT);
if (m_Renderer != null)
m_Renderer.Cleanup();

builtinParams.colorBuffer = target;
builtinParams.depthBuffer = BuiltinSkyParameters.nullRT;
Utilities.SetRenderTarget(builtinParams.commandBuffer, target, ClearFlag.ClearNone, 0, (CubemapFace)i);
CoreUtils.SetRenderTarget(builtinParams.commandBuffer, target, ClearFlag.None, 0, (CubemapFace)i);
m_Renderer.RenderSky(builtinParams, skySettings, true);
}

for (int i = 0; i < 6; ++i)
{
Utilities.SetRenderTarget(cmd, dest, ClearFlag.ClearNone, 0, (CubemapFace)i);
CoreUtils.SetRenderTarget(cmd, dest, ClearFlag.None, 0, (CubemapFace)i);
propertyBlock.SetTexture("_MainTex", source);
propertyBlock.SetFloat("_faceIndex", (float)i);
cmd.DrawProcedural(Matrix4x4.identity, m_BlitCubemapMaterial, 0, MeshTopology.Triangles, 3, 1, propertyBlock);

private void RenderCubemapGGXConvolution(CommandBuffer cmd, BuiltinSkyParameters builtinParams, SkySettings skyParams, Texture input, RenderTexture target)
{
using (new Utilities.ProfilingSample("Update Env: GGX Convolution", cmd))
using (new ProfilingSample(cmd, "Update Env: GGX Convolution"))
{
int mipCount = 1 + (int)Mathf.Log(input.width, 2.0f);
if (mipCount < ((int)EnvConstants.SpecCubeLodStep + 1))

}
// Copy the first mip
using (new Utilities.ProfilingSample("Copy Original Mip", cmd))
using (new ProfilingSample(cmd, "Copy Original Mip"))
{
for (int f = 0; f < 6; f++)
{

using (new Utilities.ProfilingSample("GGX Convolution", cmd))
using (new ProfilingSample(cmd, "GGX Convolution"))
{
if (m_useMIS && m_iblFilterGgx.SupportMIS)
{

// We need one frame delay for this update to work since DynamicGI.UpdateEnvironment is executed directly but the renderloop is not (so we need to wait for the sky texture to be rendered first)
if (m_NeedLowLevelUpdateEnvironment)
{
using (new Utilities.ProfilingSample("DynamicGI.UpdateEnvironment", cmd))
using (new ProfilingSample(cmd, "DynamicGI.UpdateEnvironment"))
{
// TODO: Properly send the cubemap to Enlighten. Currently workaround is to set the cubemap in a Skybox/cubemap material
m_StandardSkyboxMaterial.SetTexture("_Tex", m_SkyboxCubemapRT);

(skySettings.updateMode == EnvironementUpdateMode.Realtime && m_CurrentUpdateTime > skySettings.updatePeriod)
)
{
using (new Utilities.ProfilingSample("Sky Environment Pass", cmd))
using (new ProfilingSample(cmd, "Sky Environment Pass"))
using (new Utilities.ProfilingSample("Update Env: Generate Lighting Cubemap", cmd))
using (new ProfilingSample(cmd, "Update Env: Generate Lighting Cubemap"))
{
// Render sky into a cubemap - doesn't happen every frame, can be controlled
// Note that m_SkyboxCubemapRT is created with auto-generate mipmap, it mean that here we have also our mipmap correctly box filtered for importance sampling.

{
if (m_SkyParametersHash != 0)
{
using (new Utilities.ProfilingSample("Reset Sky Environment", cmd))
using (new ProfilingSample(cmd, "Reset Sky Environment"))
Utilities.ClearCubemap(cmd, m_SkyboxCubemapRT, Color.black);
CoreUtils.ClearCubemap(cmd, m_SkyboxCubemapRT, Color.black);
RenderCubemapGGXConvolution(cmd, m_BuiltinParameters, skySettings, m_SkyboxCubemapRT, m_SkyboxGGXCubemapRT);
m_SkyParametersHash = 0;

public void RenderSky(HDCamera camera, Light sunLight, RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthBuffer, CommandBuffer cmd)
{
using (new Utilities.ProfilingSample("Sky Pass", cmd))
using (new ProfilingSample(cmd, "Sky Pass"))
{
if (IsSkyValid())
{

2
ScriptableRenderPipeline/HDRenderPipeline/Wind/ShaderWindSettings.cs


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

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

正在加载...
取消
保存