浏览代码

Merge branch 'Unity-2017.3' into LightweightPipeline

/Add-support-for-light-specular-color-tint
Felipe Lira 7 年前
当前提交
5f970d63
共有 236 个文件被更改,包括 3026 次插入2455 次删除
  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. 19
      ScriptableRenderPipeline/Core/CommandBufferPool.cs
  7. 7
      ScriptableRenderPipeline/Core/Debugging/DebugActionManager.cs
  8. 6
      ScriptableRenderPipeline/Core/Debugging/DebugItemHandler.cs
  9. 4
      ScriptableRenderPipeline/Core/Debugging/DebugItemUI.cs
  10. 1
      ScriptableRenderPipeline/Core/Debugging/DebugMenuManager.cs
  11. 3
      ScriptableRenderPipeline/Core/Debugging/DebugMenuState.cs
  12. 3
      ScriptableRenderPipeline/Core/Debugging/DebugMenuUI.cs
  13. 4
      ScriptableRenderPipeline/Core/Debugging/DebugMenuUpdater.cs
  14. 12
      ScriptableRenderPipeline/Core/Debugging/DebugPanel.cs
  15. 10
      ScriptableRenderPipeline/Core/Debugging/DebugPanelUI.cs
  16. 1
      ScriptableRenderPipeline/Core/Debugging/Debugging.cs
  17. 4
      ScriptableRenderPipeline/Core/Debugging/Editor/DebugMenuEditor.cs
  18. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateBool.cs
  19. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateColor.cs
  20. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateFloat.cs
  21. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateInt.cs
  22. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateUInt.cs
  23. 3
      ScriptableRenderPipeline/Core/Inputs/InputRegistering.cs
  24. 6
      ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/Shadow.hlsl
  25. 309
      ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/ShadowAlgorithms.hlsl
  26. 4
      ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/ShadowSampling.hlsl
  27. 32
      ScriptableRenderPipeline/Core/ShaderLibrary/Wind.hlsl
  28. 4
      ScriptableRenderPipeline/Core/Shadow/Shadow.cs
  29. 2
      ScriptableRenderPipeline/Core/Singleton.cs
  30. 88
      ScriptableRenderPipeline/Core/TextureCache.cs
  31. 7
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs
  32. 5
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs.hlsl
  33. 8
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.hlsl
  34. 4
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayLatlong.shader
  35. 4
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugFullScreen.shader
  36. 4
      ScriptableRenderPipeline/HDRenderPipeline/Debug/LightingDebugPanel.cs
  37. 92
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineInspector.cs
  38. 85
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs
  39. 713
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
  40. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.asset
  41. 34
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.cs
  42. 409
      ScriptableRenderPipeline/HDRenderPipeline/HDStringConstants.cs
  43. 17
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/ScreenSpaceAmbientOcclusion.cs
  44. 884
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Editor/HDLightEditor.cs
  45. 135
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/EditorLightUtilities.cs
  46. 2
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/Deferred.compute
  47. 23
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/ShadowDispatch.hlsl
  48. 111
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs
  49. 3
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs.hlsl
  50. 2
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.hlsl
  51. 14
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePassLoop.hlsl
  52. 5
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/builddispatchindirect.compute
  53. 6
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Volumetrics/HomogeneousFog.cs
  54. 12
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Volumetrics/VolumetricLighting.cs
  55. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs
  56. 36
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/Editor/LayeredLitUI.cs
  57. 67
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader
  58. 94
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader
  59. 150
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs
  60. 72
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/LitUI.cs
  61. 31
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs
  62. 33
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs.hlsl
  63. 227
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl
  64. 73
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader
  65. 123
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitData.hlsl
  66. 78
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitDataInternal.hlsl
  67. 18
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitProperties.hlsl
  68. 120
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.hlsl
  69. 85
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader
  70. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.DisneyDiffuse.cs
  71. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.GGX.cs
  72. 15
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitDepthPass.hlsl
  73. 6
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitDistortionPass.hlsl
  74. 8
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitMetaPass.hlsl
  75. 21
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitVelocityPass.hlsl
  76. 259
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringProfile.cs
  77. 108
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/BaseUnlitUI.cs
  78. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/UnlitUI.cs
  79. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.cs
  80. 7
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.shader
  81. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/UnlitData.hlsl
  82. 3
      ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/HDRenderPipelineResources.asset
  83. 2
      ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/HDRenderPipelineResources.asset.meta
  84. 60
      ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/RenderPipelineResources.cs
  85. 4
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Editor/CommonSettingsEditor.cs
  86. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawSssProfile.shader
  87. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader
  88. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/SceneSettings.cs
  89. 1
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/SceneSettingsManager.cs
  90. 1
      ScriptableRenderPipeline/HDRenderPipeline/ShaderConfig.cs
  91. 1
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPass.cs
  92. 13
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/TessellationShare.hlsl
  93. 10
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/VaryingMesh.hlsl
  94. 45
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/VertMesh.hlsl
  95. 8
      ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesFunctions.hlsl
  96. 6
      ScriptableRenderPipeline/HDRenderPipeline/Sky/GGXConvolve.shader
  97. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Editor/HDRISkyEditor.cs
  98. 19
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/HDRISkyRenderer.cs
  99. 16
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/HDRISkySettings.cs
  100. 4
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Resources/SkyHDRI.shader

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;

19
ScriptableRenderPipeline/Core/CommandBufferPool.cs


namespace UnityEngine.Experimental.Rendering
{
internal class ObjectPool<T> where T : new()
class ObjectPool<T> where T : new()
private readonly Stack<T> m_Stack = new Stack<T>();
private readonly UnityAction<T> m_ActionOnGet;
private readonly UnityAction<T> m_ActionOnRelease;
readonly Stack<T> m_Stack = new Stack<T>();
readonly UnityAction<T> m_ActionOnGet;
readonly UnityAction<T> m_ActionOnRelease;
public int countAll { get; private set; }
public int countActive { get { return countAll - countInactive; } }

m_Stack.Push(element);
}
}
private static ObjectPool<CommandBuffer> m_BufferPool = new ObjectPool<CommandBuffer>(null, x => x.Clear());
static ObjectPool<CommandBuffer> s_BufferPool = new ObjectPool<CommandBuffer>(null, x => x.Clear());
var cmd = m_BufferPool.Get();
var cmd = s_BufferPool.Get();
var cmd = m_BufferPool.Get();
var cmd = s_BufferPool.Get();
cmd.name = name;
return cmd;
}

m_BufferPool.Release(buffer);
s_BufferPool.Release(buffer);
}
}
}

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 = HDUtils.GetRenderPipelineMaterialList();
// TODO: Share this code to retrieve deferred material with HDRenderPipeline
// Find first material that have non 0 Gbuffer count and assign it as deferredMaterial

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

713
ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
文件差异内容过多而无法显示
查看文件

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()
{

409
ScriptableRenderPipeline/HDRenderPipeline/HDStringConstants.cs


namespace UnityEngine.Experimental.Rendering.HDPipeline
{
static class HDShaderPassNames
public static class HDShaderPassNames
// ShaderPass string - use to have consistent name through the code
public static readonly string s_EmptyStr = "";
public static readonly string s_ForwardStr = "Forward";
public static readonly string s_ForwardDebugDisplayStr = "ForwardDebugDisplay";
public static readonly string s_DepthOnlyStr = "DepthOnly";
public static readonly string s_ForwardOnlyOpaqueDepthOnlyStr = "ForwardOnlyOpaqueDepthOnly";
public static readonly string s_ForwardOnlyOpaqueStr = "ForwardOnlyOpaque";
public static readonly string s_ForwardOnlyOpaqueDebugDisplayStr = "ForwardOnlyOpaqueDebugDisplay";
public static readonly string s_GBufferStr = "GBuffer";
public static readonly string s_GBufferWithPrepassStr = "GBufferWithPrepass";
public static readonly string s_GBufferDebugDisplayStr = "GBufferDebugDisplay";
public static readonly string s_SRPDefaultUnlitStr = "SRPDefaultUnlit";
public static readonly string s_MotionVectorsStr = "MotionVectors";
public static readonly string s_DistortionVectorsStr = "DistortionVectors";
public static readonly string s_TransparentDepthPrepassStr = "TransparentDepthPrepass";
public static readonly string s_MetaStr = "Meta";
public static readonly string s_ShadowCasterStr = "ShadowCaster";
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(s_EmptyStr);
public static readonly ShaderPassName s_ForwardName = new ShaderPassName(s_ForwardStr);
public static readonly ShaderPassName s_ForwardDebugDisplayName = new ShaderPassName(s_ForwardDebugDisplayStr);
public static readonly ShaderPassName s_DepthOnlyName = new ShaderPassName(s_DepthOnlyStr);
public static readonly ShaderPassName s_ForwardOnlyOpaqueDepthOnlyName = new ShaderPassName(s_ForwardOnlyOpaqueDepthOnlyStr);
public static readonly ShaderPassName s_ForwardOnlyOpaqueName = new ShaderPassName(s_ForwardOnlyOpaqueStr);
public static readonly ShaderPassName s_ForwardOnlyOpaqueDebugDisplayName = new ShaderPassName(s_ForwardOnlyOpaqueDebugDisplayStr);
public static readonly ShaderPassName s_GBufferName = new ShaderPassName(s_GBufferStr);
public static readonly ShaderPassName s_GBufferWithPrepassName = new ShaderPassName(s_GBufferWithPrepassStr);
public static readonly ShaderPassName s_GBufferDebugDisplayName = new ShaderPassName(s_GBufferDebugDisplayStr);
public static readonly ShaderPassName s_SRPDefaultUnlitName = new ShaderPassName(s_SRPDefaultUnlitStr);
public static readonly ShaderPassName s_MotionVectorsName = new ShaderPassName(s_MotionVectorsStr);
public static readonly ShaderPassName s_DistortionVectorsName = new ShaderPassName(s_DistortionVectorsStr);
public static readonly ShaderPassName s_TransparentDepthPrepassName = new ShaderPassName(s_TransparentDepthPrepassStr);
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");
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 g_isLogBaseBufferEnabled = Shader.PropertyToID("g_isLogBaseBufferEnabled");
internal static readonly int g_vLayeredOffsetsBuffer = Shader.PropertyToID("g_vLayeredOffsetsBuffer");
public static readonly int g_isLogBaseBufferEnabled = Shader.PropertyToID("g_isLogBaseBufferEnabled");
public static readonly int g_vLayeredOffsetsBuffer = Shader.PropertyToID("g_vLayeredOffsetsBuffer");
internal static readonly int _ViewTilesFlags = Shader.PropertyToID("_ViewTilesFlags");
internal static readonly int _MousePixelCoord = Shader.PropertyToID("_MousePixelCoord");
public static readonly int _ViewTilesFlags = Shader.PropertyToID("_ViewTilesFlags");
public static readonly int _MousePixelCoord = Shader.PropertyToID("_MousePixelCoord");
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 _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 _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 _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 _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 _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 g_TileListOffset = Shader.PropertyToID("g_TileListOffset");
public static readonly int g_TileListOffset = Shader.PropertyToID("g_TileListOffset");
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 _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 _MainDepthTexture = Shader.PropertyToID("_MainDepthTexture");
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

111
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()

// Debug.Assert(additionalData == null, "Missing HDAdditionalData on a light - Should have been create by HDLightEditor");
if (additionalData == null)
return;
return;
LightCategory lightCategory = LightCategory.Count;
GPULightType gpuLightType = GPULightType.Point;

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)
{

var invProjscr = projscr.inverse;
bool isOrthographic = camera.orthographic;
cmd.SetRenderTarget(new RenderTargetIdentifier((Texture)null));
cmd.SetRenderTarget(BuiltinRenderTextureType.None);
// generate screen-space AABBs (used for both fptl and clustered).
if (m_lightCount != 0)

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
//-----------------------------------------------------------------------------

36
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 layerInfluenceMapMaskText = new GUIContent("Layer Influence Mask", "Layer mask");
public readonly GUIContent vertexColorModeText = new GUIContent("Vertex Color Mode", "Mode multiply: vertex color is multiply with the mask. Mode additive: vertex color values are remapped between -1 and 1 and added to the mask (neutral at 0.5 vertex color).");
public readonly GUIContent layerCountText = new GUIContent("Layer Count", "Number of layers.");
public readonly GUIContent layerTilingBlendMaskText = new GUIContent("Tiling", "Tiling for the blend mask.");
public readonly GUIContent objectScaleAffectTileText = new GUIContent("Lock layers 0123 tiling with object Scale", "Tiling of each layers will be affected by the object scale.");
public readonly GUIContent objectScaleAffectTileText2 = new GUIContent("Lock layers 123 tiling with object Scale", "Tiling of each influenced layers (all except main layer) will be affected by the object scale.");

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

const string kUVBlendMask = "_UVBlendMask";
MaterialProperty UVMappingMaskBlendMask = null;
const string kUVMappingMaskBlendMask = "_UVMappingMaskBlendMask";
MaterialProperty layerTilingBlendMask = null;
const string kLayerTilingBlendMask = "_LayerTilingBlendMask";
MaterialProperty texWorldScaleBlendMask = null;
const string kTexWorldScaleBlendMask = "_TexWorldScaleBlendMask";
MaterialProperty useMainLayerInfluence = null;

objectScaleAffectTile = FindProperty(kObjectScaleAffectTile, props);
UVBlendMask = FindProperty(kUVBlendMask, props);
UVMappingMaskBlendMask = FindProperty(kUVMappingMaskBlendMask, props);
layerTilingBlendMask = FindProperty(kLayerTilingBlendMask, props);
texWorldScaleBlendMask = FindProperty(kTexWorldScaleBlendMask, props);
useMainLayerInfluence = FindProperty(kkUseMainLayerInfluence, props);

{
m_MaterialEditor.ShaderProperty(texWorldScaleBlendMask, styles.layerTexWorldScaleText);
}
else
{
m_MaterialEditor.ShaderProperty(layerTilingBlendMask, styles.layerTilingBlendMaskText);
}
m_MaterialEditor.TextureScaleOffsetProperty(layerMaskMap);
EditorGUI.indentLevel--;
m_MaterialEditor.ShaderProperty(vertexColorMode, styles.vertexColorModeText);

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();
{

67
ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader


[ToggleOff] _OpacityAsDensity2("_OpacityAsDensity2", Float) = 0.0
[ToggleOff] _OpacityAsDensity3("_OpacityAsDensity3", Float) = 0.0
_LayerTilingBlendMask("_LayerTilingBlendMask", Float) = 1
[HideInInspector] _LayerCount("_LayerCount", Float) = 2.0
[Enum(None, 0, Multiply, 1, Add, 2)] _VertexColorMode("Vertex color mode", Float) = 0

// Following are builtin properties
_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] _EnableSpecularOcclusion("Enable specular occlusion", Float) = 0.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 enable_d3d11_debug_symbols
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _DISTORTION_ON
#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 _ _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

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"
#include "../Lit/LitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "GBufferDebugDisplay" // Name is not used

Pass
{
Name "ForwardDisplayDebug" // Name is not used
Tags{ "LightMode" = "ForwardDisplayDebug" } // This will be only for transparent object based on the RenderQueue index
Name "ForwardDebugDisplay" // Name is not used
Tags{ "LightMode" = "ForwardDebugDisplay" } // This will be only for transparent object based on the RenderQueue index
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]

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


[ToggleOff] _OpacityAsDensity2("_OpacityAsDensity2", Float) = 0.0
[ToggleOff] _OpacityAsDensity3("_OpacityAsDensity3", Float) = 0.0
_LayerTilingBlendMask("_LayerTilingBlendMask", Float) = 1
[HideInInspector] _LayerCount("_LayerCount", Float) = 2.0
[Enum(None, 0, Multiply, 1, Add, 2)] _VertexColorMode("Vertex color mode", Float) = 0

// Following are builtin properties
_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] _EnableSpecularOcclusion("Enable specular occlusion", Float) = 0.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 enable_d3d11_debug_symbols
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _DISTORTION_ON
// 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 _ _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"

Pass
{
Name "ForwardDisplayDebug" // Name is not used
Tags{ "LightMode" = "ForwardDisplayDebug" } // This will be only for transparent object based on the RenderQueue index
Name "ForwardDebugDisplay" // Name is not used
Tags{ "LightMode" = "ForwardDebugDisplay" } // This will be only for transparent object based on the RenderQueue index
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]

150
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";
}
public enum DoubleSidedNormalMode

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 windShiverDirectionality = null;
protected const string kWindShiverDirectionality = "_ShiverDirectionality";
// 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);
if (material.HasProperty(kTessellationMode))
{
TessellationMode tessMode = (TessellationMode)material.GetFloat(kTessellationMode);
SetKeyword(material, "_TESSELLATION_PHONG", tessMode == TessellationMode.Phong);
}
bool distortionEnable = material.GetFloat(kDistortionEnable) > 0.0f;
bool distortionOnly = material.GetFloat(kDistortionOnly) > 0.0f;
if (distortionEnable && distortionOnly)
{
// Disable all passes except distortion (setup in BaseUnlitUI.cs) and debug passes (to visualize distortion)
material.SetShaderPassEnabled("GBuffer", false);
material.SetShaderPassEnabled("GBufferDisplayDebug", true);
material.SetShaderPassEnabled("Meta", false);
material.SetShaderPassEnabled("ShadowCaster", false);
material.SetShaderPassEnabled("DepthOnly", false);
material.SetShaderPassEnabled("MotionVectors", false);
material.SetShaderPassEnabled("Forward", false);
material.SetShaderPassEnabled("ForwardDisplayDebug", true);
}
else
{
// Enable all passes except distortion (setup in BaseUnlitUI.cs)
material.SetShaderPassEnabled("GBuffer", true);
material.SetShaderPassEnabled("GBufferDisplayDebug", true);
material.SetShaderPassEnabled("Meta", true);
material.SetShaderPassEnabled("ShadowCaster", true);
material.SetShaderPassEnabled("DepthOnly", true);
material.SetShaderPassEnabled("MotionVectors", true);
material.SetShaderPassEnabled("Forward", true);
material.SetShaderPassEnabled("ForwardDisplayDebug", true);
}
SetupBaseUnlitMaterialPass(material);
}
}
} // namespace UnityEditor

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;

if (m_isInit)
return;
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
_DistortionVectorMap("DistortionVectorMap", 2D) = "black" {}
// Following options are for the GUI inspector and different from the input parameters above

[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.

//-------------------------------------------------------------------------------------
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _DISTORTION_ON
#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 _ _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"

Pass
{
Name "ForwardDisplayDebug" // Name is not used
Tags{ "LightMode" = "ForwardDisplayDebug" } // This will be only for transparent object based on the RenderQueue index
Name "ForwardDebugDisplay" // Name is not used
Tags{ "LightMode" = "ForwardDebugDisplay" } // This will be only for transparent object based on the RenderQueue index
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]

123
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)
{

builtinData.velocity = float2(0.0, 0.0);
#ifdef _DISTORTION_ON
#if (SHADERPASS == SHADERPASS_DISTORTION)
float3 distortion = SAMPLE_TEXTURE2D(_DistortionVectorMap, sampler_DistortionVectorMap, input.texCoord0).rgb;
builtinData.distortion = distortion.rg;
builtinData.distortionBlur = distortion.b;

// Be sure that the compiler is aware that we don't use UV1 to UV3 for main layer so it can optimize code
ComputeLayerTexCoord( texCoord0, texCoord1, texCoord2, texCoord3, float4(1.0, 0.0, 0.0, 0.0), _UVDetailsMappingMask,
positionWS, mappingType, _TexWorldScale, layerTexCoord);
_BaseColorMap_ST.xy, _BaseColorMap_ST.zw, _DetailMap_ST.xy, _DetailMap_ST.zw, 1.0,
positionWS, _TexWorldScale,
mappingType, layerTexCoord);
}
// This is call only in this file

{
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));

// Note: Blend mask have its dedicated mapping and tiling.
// To share code, we simply call the regular code from the main layer for it then save the result, then do regular call for all layers.
ComputeLayerTexCoord0( texCoord0, texCoord1, texCoord2, texCoord3, _UVMappingMaskBlendMask, _UVMappingMaskBlendMask,
positionWS, mappingType, _TexWorldScaleBlendMask, layerTexCoord, _LayerTilingBlendMask);
_LayerMaskMap_ST.xy, _LayerMaskMap_ST.zw, float2(0.0, 0.0), float2(0.0, 0.0), 1.0,
positionWS, _TexWorldScaleBlendMask,
mappingType, layerTexCoord);
layerTexCoord.blendMask = layerTexCoord.base0;

#endif
ComputeLayerTexCoord0( texCoord0, texCoord1, texCoord2, texCoord3, _UVMappingMask0, _UVDetailsMappingMask0,
positionWS, mappingType, _TexWorldScale0, layerTexCoord, 1.0
_BaseColorMap0_ST.xy, _BaseColorMap0_ST.zw, _DetailMap0_ST.xy, _DetailMap0_ST.zw, 1.0
);
, positionWS, _TexWorldScale0,
mappingType, layerTexCoord);
mappingType = UV_MAPPING_UVSET;
#if defined(_LAYER_MAPPING_PLANAR1)

#endif
ComputeLayerTexCoord1( texCoord0, texCoord1, texCoord2, texCoord3, _UVMappingMask1, _UVDetailsMappingMask1,
positionWS, mappingType, _TexWorldScale1, layerTexCoord, tileObjectScale);
_BaseColorMap1_ST.xy, _BaseColorMap1_ST.zw, _DetailMap1_ST.xy, _DetailMap1_ST.zw, tileObjectScale,
positionWS, _TexWorldScale1,
mappingType, layerTexCoord);
mappingType = UV_MAPPING_UVSET;
#if defined(_LAYER_MAPPING_PLANAR2)

#endif
ComputeLayerTexCoord2( texCoord0, texCoord1, texCoord2, texCoord3, _UVMappingMask2, _UVDetailsMappingMask2,
positionWS, mappingType, _TexWorldScale2, layerTexCoord, tileObjectScale);
_BaseColorMap2_ST.xy, _BaseColorMap2_ST.zw, _DetailMap2_ST.xy, _DetailMap2_ST.zw, tileObjectScale,
positionWS, _TexWorldScale2,
mappingType, layerTexCoord);
mappingType = UV_MAPPING_UVSET;
#if defined(_LAYER_MAPPING_PLANAR3)

#endif
ComputeLayerTexCoord3( texCoord0, texCoord1, texCoord2, texCoord3, _UVMappingMask3, _UVDetailsMappingMask3,
positionWS, mappingType, _TexWorldScale3, layerTexCoord, tileObjectScale);
_BaseColorMap3_ST.xy, _BaseColorMap3_ST.zw, _DetailMap3_ST.xy, _DetailMap3_ST.zw, tileObjectScale,
positionWS, _TexWorldScale3,
mappingType, layerTexCoord);
}
// This is call only in this file

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;

// Calculate displacement for per vertex displacement mapping
float ComputePerVertexDisplacement(LayerTexCoord layerTexCoord, float4 vertexColor, float lod)
{
float4 inputBlendMasks = GetBlendMask(layerTexCoord, vertexColor, true, lod);
float weights[_MAX_LAYER];
ApplyTessellationTileScale(height0, height1, height2, height3); // Only apply with per vertex displacement
SetEnabledHeightByLayer(height0, height1, height2, height3);
ApplyDisplacementTileScale(height0, height1, height2, height3); // Only apply with per vertex displacement
float4 resultBlendMasks = inputBlendMasks;
#if defined(_HEIGHT_BASED_BLEND)
resultBlendMasks = ApplyHeightBlend(float4(height0, height1, height2, height3), inputBlendMasks);
#endif
float4 blendMask = GetBlendMask(layerTexCoord, vertexColor, true, lod);
#if defined(_MAIN_LAYER_INFLUENCE_MODE)
// Add main layer influence if any (simply add main layer add on other layer)
// We multiply by the input mask for the first layer (blendMask.a) because if the mask here is black it means that the layer
// is not actually underneath any visible layer so we don't want to inherit its height.
float influenceMask = blendMask.a * GetInfluenceMask(layerTexCoord, true, lod);
height1 += height0 * _InheritBaseHeight1 * influenceMask;
height2 += height0 * _InheritBaseHeight2 * influenceMask;
height3 += height0 * _InheritBaseHeight3 * influenceMask;
#endif
ComputeMaskWeights(resultBlendMasks, weights);
float heightResult = BlendLayeredScalar(height0, height1, height2, height3, weights);
SetEnabledHeightByLayer(height0, height1, height2, height3);
#if defined(_MAIN_LAYER_INFLUENCE_MODE)
// Think that inheritbasedheight will be 0 if height0 is fully visible in weights. So there is no double contribution of height0
float influenceMask = GetInfluenceMask(layerTexCoord, true, lod);
float inheritBaseHeight = BlendLayeredScalar(0.0, _InheritBaseHeight1, _InheritBaseHeight2, _InheritBaseHeight3, weights);
return heightResult + height0 * inheritBaseHeight * inputBlendMasks.a * influenceMask; // We multiply by the input mask for the first layer because if the mask here is black it means that the layer is not actually underneath any visible layer so we don't want to inherit its height.
#endif
#if defined(_HEIGHT_BASED_BLEND)
blendMask = ApplyHeightBlend(float4(height0, height1, height2, height3), blendMask);
#endif
float weights[_MAX_LAYER];
ComputeMaskWeights(blendMask, weights);
return BlendLayeredScalar(height0, height1, height2, height3, weights);
float heightResult = 0.0;
return 0.0;
return heightResult;
}
// Calculate weights to apply to each layer

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

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


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)
void ADD_IDX(ComputeLayerTexCoord)( // Uv related parameters
float2 texCoord0, float2 texCoord1, float2 texCoord2, float2 texCoord3, float4 uvMappingMask, float4 uvMappingMaskDetails,
// scale and bias for base and detail + global tiling factor (for layered lit only)
float2 texScale, float2 texBias, float2 texScaleDetails, float2 texBiasDetails, float additionalTiling,
// parameter for planar/triplanar
float3 positionWS, float worldScale,
// mapping type and output
int mappingType, inout LayerTexCoord layerTexCoord)
{
// Handle uv0, uv1, uv2, uv3 based on _UVMappingMask weight (exclusif 0..1)
float2 uvBase = uvMappingMask.x * texCoord0 +

uvBase *= additionalTiling.xx;
float2 uvDetails = uvMappingMaskDetail.x * texCoord0 +
uvMappingMaskDetail.y * texCoord1 +
uvMappingMaskDetail.z * texCoord2 +
uvMappingMaskDetail.w * texCoord3;
float2 uvDetails = uvMappingMaskDetails.x * texCoord0 +
uvMappingMaskDetails.y * texCoord1 +
uvMappingMaskDetails.z * texCoord2 +
uvMappingMaskDetails.w * texCoord3;
uvDetails *= additionalTiling.xx;

}
// Apply tiling options
ADD_IDX(layerTexCoord.base).uv = TRANSFORM_TEX(uvBase, ADD_IDX(_BaseColorMap));
ADD_IDX(layerTexCoord.details).uv = TRANSFORM_TEX(uvDetails, ADD_IDX(_DetailMap));
ADD_IDX(layerTexCoord.base).uv = uvBase * texScale + texBias;
// Detail map tiling option inherit from the tiling of the base
ADD_IDX(layerTexCoord.details).uv = (uvDetails * texScaleDetails + texBiasDetails) * texScale + texBias;
ADD_IDX(layerTexCoord.base).uvXZ = TRANSFORM_TEX(uvXZ, ADD_IDX(_BaseColorMap));
ADD_IDX(layerTexCoord.base).uvXY = TRANSFORM_TEX(uvXY, ADD_IDX(_BaseColorMap));
ADD_IDX(layerTexCoord.base).uvZY = TRANSFORM_TEX(uvZY, ADD_IDX(_BaseColorMap));
ADD_IDX(layerTexCoord.base).uvXZ = uvXZ * texScale + texBias;
ADD_IDX(layerTexCoord.base).uvXY = uvXY * texScale + texBias;
ADD_IDX(layerTexCoord.base).uvZY = uvZY * texScale + texBias;
ADD_IDX(layerTexCoord.details).uvXZ = TRANSFORM_TEX(uvXZ, ADD_IDX(_DetailMap));
ADD_IDX(layerTexCoord.details).uvXY = TRANSFORM_TEX(uvXY, ADD_IDX(_DetailMap));
ADD_IDX(layerTexCoord.details).uvZY = TRANSFORM_TEX(uvZY, ADD_IDX(_DetailMap));
ADD_IDX(layerTexCoord.details).uvXZ = (uvXZ * texScaleDetails + texBiasDetails) * texScale + texBias;
ADD_IDX(layerTexCoord.details).uvXY = (uvXY * texScaleDetails + texBiasDetails) * texScale + texBias;
ADD_IDX(layerTexCoord.details).uvZY = (uvZY * texScaleDetails + texBiasDetails) * texScale + texBias;
#ifdef SURFACE_GRADIENT
// This part is only relevant for normal mapping with UV_MAPPING_UVSET

uvMappingMask.z * layerTexCoord.vertexBitangentWS2 +
uvMappingMask.w * layerTexCoord.vertexBitangentWS3;
ADD_IDX(layerTexCoord.details).tangentWS = uvMappingMaskDetail.x * layerTexCoord.vertexTangentWS0 +
uvMappingMaskDetail.y * layerTexCoord.vertexTangentWS1 +
uvMappingMaskDetail.z * layerTexCoord.vertexTangentWS2 +
uvMappingMaskDetail.w * layerTexCoord.vertexTangentWS3;
ADD_IDX(layerTexCoord.details).tangentWS = uvMappingMaskDetails.x * layerTexCoord.vertexTangentWS0 +
uvMappingMaskDetails.y * layerTexCoord.vertexTangentWS1 +
uvMappingMaskDetails.z * layerTexCoord.vertexTangentWS2 +
uvMappingMaskDetails.w * layerTexCoord.vertexTangentWS3;
ADD_IDX(layerTexCoord.details).bitangentWS = uvMappingMaskDetail.x * layerTexCoord.vertexBitangentWS0 +
uvMappingMaskDetail.y * layerTexCoord.vertexBitangentWS1 +
uvMappingMaskDetail.z * layerTexCoord.vertexBitangentWS2 +
uvMappingMaskDetail.w * layerTexCoord.vertexBitangentWS3;
ADD_IDX(layerTexCoord.details).bitangentWS = uvMappingMaskDetails.x * layerTexCoord.vertexBitangentWS0 +
uvMappingMaskDetails.y * layerTexCoord.vertexBitangentWS1 +
uvMappingMaskDetails.z * layerTexCoord.vertexBitangentWS2 +
uvMappingMaskDetails.w * layerTexCoord.vertexBitangentWS3;
#endif
}

// 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)

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


// Otherwise those parameters are not bound correctly at runtime.
// ===========================================================================
#ifndef LAYERED_LIT_SHADER
TEXTURE2D(_DiffuseLightingMap);
SAMPLER2D(sampler_DiffuseLightingMap);
TEXTURE2D(_DistortionVectorMap);
SAMPLER2D(sampler_DistortionVectorMap);

#ifndef LAYERED_LIT_SHADER
TEXTURE2D(_DiffuseLightingMap);
SAMPLER2D(sampler_DiffuseLightingMap);
TEXTURE2D(_BaseColorMap);
SAMPLER2D(sampler_BaseColorMap);

float _AlbedoAffectEmissive;
float _EnableSpecularOcclusion;
// Transparency
float3 _TransmittanceColor;
float _IOR;
float _ATDistance;
float _ThicknessMultiplier;
// Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor"
// value that exist to identify if the GI emission need to be enabled.

float _InheritBaseColor1;
float _InheritBaseColor2;
float _InheritBaseColor3;
float _LayerTilingBlendMask;
float4 _LayerMaskMap_ST;
float _TexWorldScaleBlendMask;
PROP_DECL(float, _TexWorldScale);
float4 _UVMappingMaskBlendMask;

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

85
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
_DistortionVectorMap("DistortionVectorMap", 2D) = "black" {}
// Following options are for the GUI inspector and different from the input parameters above

[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 _ALPHATEST_ON
#pragma shader_feature _DISTORTION_ON
// 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 _SUBSURFACE_RADIUS_MAP
#pragma shader_feature _THICKNESSMAP
#pragma shader_feature _SPECULARCOLORMAP
#pragma shader_feature _VERTEX_WIND
#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"

Pass
{
Name "ForwardDisplayDebug" // Name is not used
Tags{ "LightMode" = "ForwardDisplayDebug" } // This will be only for transparent object based on the RenderQueue index
Name "ForwardDebugDisplay" // Name is not used
Tags{ "LightMode" = "ForwardDebugDisplay" } // This will be only for transparent object based on the RenderQueue index
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]

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

6
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitDistortionPass.hlsl


// If we have a layered shader, any UV can be use for this. To reduce the number of variant we groupt UV0/UV1 and UV2/UV3 instead of having variant for UV0/UV1/UV2/UV3
// When UVX is present, we assume that UVX - 1 ... UV0 is present
#if REQUIRE_UV_FOR_TESSELATION || REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON) || defined(_DISTORTION_ON)
#if REQUIRE_UV_FOR_TESSELATION || REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON)
#ifdef LAYERED_LIT_SHADER
#define ATTRIBUTES_NEED_TEXCOORD1
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)

#define VARYINGS_NEED_TANGENT_TO_WORLD
#endif
#if REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON) || defined(_DISTORTION_ON)
#if REQUIRE_TANGENT_TO_WORLD || defined(_ALPHATEST_ON)
#ifdef LAYERED_LIT_SHADER
#define VARYINGS_NEED_TEXCOORD1
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3)

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
}

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


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

public static GUIContent alphaCutoffEnableText = new GUIContent("Alpha Cutoff Enable", "Threshold for alpha cutoff");
public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff");
public static GUIContent alphaCutoffShadowText = new GUIContent("Alpha Cutoff Shadow", "Threshold for alpha cutoff in case of shadow pass");
public static GUIContent alphaCutoffPrepassText = new GUIContent("Alpha Cutoff Prepass", "Threshold for alpha cutoff in case of depth prepass");
public static GUIContent transparentDepthPrepassEnableText = new GUIContent("Enable transparent depth prepass", "It allow to ");
public static GUIContent doubleSidedEnableText = new GUIContent("Double Sided", "This will render the two face of the objects (disable backface culling) and flip/mirror normal");
public static GUIContent distortionEnableText = new GUIContent("Distortion", "Enable distortion on this shader");
public static GUIContent distortionOnlyText = new GUIContent("Distortion Only", "This shader will only be use to render distortion");

protected const string kAlphaCutoffEnabled = "_AlphaCutoffEnable";
protected MaterialProperty alphaCutoff = null;
protected const string kAlphaCutoff = "_AlphaCutoff";
protected MaterialProperty alphaCutoffShadow = null;
protected const string kAlphaCutoffShadow = "_AlphaCutoffShadow";
protected MaterialProperty alphaCutoffPrepass = null;
protected const string kAlphaCutoffPrepass = "_AlphaCutoffPrepass";
protected MaterialProperty transparentDepthPrepassEnable = null;
protected const string kTransparentDepthPrepassEnable = "_TransparentDepthPrepassEnable";
protected MaterialProperty doubleSidedEnable = null;
protected const string kDoubleSidedEnable = "_DoubleSidedEnable";
protected MaterialProperty blendMode = null;

surfaceType = FindProperty(kSurfaceType, props);
alphaCutoffEnable = FindProperty(kAlphaCutoffEnabled, props);
alphaCutoff = FindProperty(kAlphaCutoff, props);
alphaCutoffShadow = FindProperty(kAlphaCutoffShadow, props, false);
alphaCutoffPrepass = FindProperty(kAlphaCutoffPrepass, props, false);
transparentDepthPrepassEnable = FindProperty(kTransparentDepthPrepassEnable, props, false);
doubleSidedEnable = FindProperty(kDoubleSidedEnable, props);
blendMode = FindProperty(kBlendMode, props);
distortionEnable = FindProperty(kDistortionEnable, props, false);

if (distortionEnable.floatValue == 1.0f)
{
EditorGUI.indentLevel++;
EditorGUI.indentLevel--;
}
}
}

EditorGUI.indentLevel++;
// With transparent object and few specific materials like Hair, we need more control on the cutoff to apply
// This allow to get a better sorting (with prepass), better shadow (better silouhette fidelity) etc...
if ((SurfaceType)surfaceType.floatValue == SurfaceType.Transparent)
{
if (alphaCutoffShadow != null)
{
m_MaterialEditor.ShaderProperty(alphaCutoffShadow, StylesBaseUnlit.alphaCutoffShadowText);
}
if (transparentDepthPrepassEnable != null)
{
m_MaterialEditor.ShaderProperty(transparentDepthPrepassEnable, StylesBaseUnlit.transparentDepthPrepassEnableText);
if (transparentDepthPrepassEnable.floatValue == 1.0f)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(alphaCutoffPrepass, StylesBaseUnlit.alphaCutoffPrepassText);
EditorGUI.indentLevel--;
}
}
}
EditorGUI.indentLevel--;
}
// This function must finish with double sided option (see LitUI.cs)
m_MaterialEditor.ShaderProperty(doubleSidedEnable, StylesBaseUnlit.doubleSidedEnableText);

SetKeyword(material, "_ALPHATEST_ON", alphaTestEnable);
if (material.HasProperty(kDistortionEnable))
{
bool distortionEnable = material.GetFloat(kDistortionEnable) > 0.0f;
if (distortionEnable)
{
material.SetShaderPassEnabled("DistortionVectors", true);
}
else
{
material.SetShaderPassEnabled("DistortionVectors", false);
}
{
bool distortionDepthTest = material.GetFloat(kDistortionDepthTest) > 0.0f;
if (distortionDepthTest)
{

{
material.SetInt("_ZTestMode", (int)UnityEngine.Rendering.CompareFunction.Always);
}
SetKeyword(material, "_DISTORTION_ON", distortionEnable);
}
// A material's GI flag internally keeps track of whether emission is enabled at all, it's enabled but has no effect

if (material.HasProperty(kDistortionEnable))
{
bool distortionEnable = material.GetFloat(kDistortionEnable) > 0.0f;
bool distortionOnly = material.GetFloat(kDistortionOnly) > 0.0f;
if (distortionEnable && distortionOnly)
bool distortionOnly = false;
if (material.HasProperty(kDistortionOnly))
// Disable all passes except debug material
material.SetShaderPassEnabled("GBuffer", false);
material.SetShaderPassEnabled("DebugViewMaterial", true);
material.SetShaderPassEnabled("Meta", false);
material.SetShaderPassEnabled("ShadowCaster", false);
material.SetShaderPassEnabled("DepthOnly", false);
material.SetShaderPassEnabled("MotionVectors", false);
material.SetShaderPassEnabled("Forward", false);
distortionOnly = material.GetFloat(kDistortionOnly) > 0.0f;
}
// If distortion only is enabled, disable all passes (except distortion and debug)
bool enablePass = !(distortionEnable && distortionOnly);
// Disable all passes except distortion
// Distortion is setup in code above
material.SetShaderPassEnabled(HDShaderPassNames.s_ForwardStr, enablePass);
material.SetShaderPassEnabled(HDShaderPassNames.s_ForwardDebugDisplayStr, true);
material.SetShaderPassEnabled(HDShaderPassNames.s_DepthOnlyStr, enablePass);
material.SetShaderPassEnabled(HDShaderPassNames.s_ForwardOnlyOpaqueDepthOnlyStr, enablePass);
material.SetShaderPassEnabled(HDShaderPassNames.s_ForwardOnlyOpaqueStr, enablePass);
material.SetShaderPassEnabled(HDShaderPassNames.s_ForwardOnlyOpaqueDebugDisplayStr, true);
material.SetShaderPassEnabled(HDShaderPassNames.s_GBufferStr, enablePass);
material.SetShaderPassEnabled(HDShaderPassNames.s_GBufferWithPrepassStr, enablePass);
material.SetShaderPassEnabled(HDShaderPassNames.s_GBufferDebugDisplayStr, true);
material.SetShaderPassEnabled(HDShaderPassNames.s_MotionVectorsStr, enablePass);
material.SetShaderPassEnabled(HDShaderPassNames.s_DistortionVectorsStr, distortionEnable); // note: use distortionEnable
material.SetShaderPassEnabled(HDShaderPassNames.s_TransparentDepthPrepassStr, enablePass);
material.SetShaderPassEnabled(HDShaderPassNames.s_MetaStr, enablePass);
material.SetShaderPassEnabled(HDShaderPassNames.s_ShadowCasterStr, enablePass);
}
if (material.HasProperty(kTransparentDepthPrepassEnable))
{
bool depthWriteEnable = (material.GetFloat(kTransparentDepthPrepassEnable) > 0.0f) && ((SurfaceType)material.GetFloat(kSurfaceType) == SurfaceType.Transparent);
if (depthWriteEnable)
{
material.SetShaderPassEnabled(HDShaderPassNames.s_TransparentDepthPrepassStr, true);
material.SetShaderPassEnabled("GBuffer", true);
material.SetShaderPassEnabled("DebugViewMaterial", true);
material.SetShaderPassEnabled("Meta", true);
material.SetShaderPassEnabled("ShadowCaster", true);
material.SetShaderPassEnabled("DepthOnly", true);
material.SetShaderPassEnabled("MotionVectors", true);
material.SetShaderPassEnabled("Forward", true);
material.SetShaderPassEnabled(HDShaderPassNames.s_TransparentDepthPrepassStr, false);
}
}
}

EditorGUILayout.Space();
EditorGUILayout.LabelField(StylesBaseUnlit.advancedText, EditorStyles.boldLabel);
// NB renderqueue editor is not shown on purpose: we want to override it based on blend mode
// NB RenderQueue editor is not shown on purpose: we want to override it based on blend mode
EditorGUI.indentLevel++;
m_MaterialEditor.EnableInstancingField();
m_MaterialEditor.DoubleSidedGIField();

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

7
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.shader


//-------------------------------------------------------------------------------------
#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _DISTORTION_ON
// #pragma shader_feature _DOUBLESIDED_ON - We have no lighting, so no need to have this combination for shader, the option will just disable backface culling
#pragma shader_feature _EMISSIVE_COLOR_MAP

Pass
{
Name "ForwardUnlit"
Tags { "LightMode" = "ForwardDisplayDebug" }
Name "ForwardDebugDisplay"
Tags { "LightMode" = "ForwardDebugDisplay" }
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]

Pass
{
Name "ForwardUnlit"
Tags { "LightMode" = "ForwardOnlyOpaqueDisplayDebug" }
Tags { "LightMode" = "ForwardOnlyOpaqueDebugDisplay" }
Blend [_SrcBlend] [_DstBlend]
ZWrite [_ZWrite]

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/UnlitData.hlsl


builtinData.velocity = float2(0.0, 0.0);
#ifdef _DISTORTION_ON
#if (SHADERPASS == SHADERPASS_DISTORTION)
float3 distortion = SAMPLE_TEXTURE2D(_DistortionVectorMap, sampler_DistortionVectorMap, input.texCoord0).rgb;
builtinData.distortion = distortion.rg;
builtinData.distortionBlur = distortion.b;

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

45
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
positionWS = GetCameraRelativePositionWS(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)
#if SHADERPASS == SHADERPASS_VELOCITY
#if (SHADERPASS == SHADERPASS_VELOCITY)
output.normalWS = float3(0.0, 0.0, 1.0);
#else
output.normalWS = normalWS;

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

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


using UnityEngine.Rendering;
private HDRISkySettings m_HdriSkyParams;
MaterialPropertyBlock m_PropertyBlock;
HDRISkySettings m_HdriSkyParams;
m_PropertyBlock = new MaterialPropertyBlock();
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);
}
}

m_SkyHDRIMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_HdriSkyParams.exposure, m_HdriSkyParams.multiplier, m_HdriSkyParams.rotation, 0.0f));
// This matrix needs to be updated at the draw call frequency.
MaterialPropertyBlock properties = new MaterialPropertyBlock();
properties.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, builtinParams.pixelCoordToViewDirMatrix);
m_PropertyBlock.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, builtinParams.pixelCoordToViewDirMatrix);
Utilities.DrawFullScreen(builtinParams.commandBuffer, m_SkyHDRIMaterial, properties, renderForCubemap ? 0 : 1);
CoreUtils.DrawFullScreen(builtinParams.commandBuffer, m_SkyHDRIMaterial, m_PropertyBlock, renderForCubemap ? 0 : 1);
}
public override bool IsSkyValid()

16
ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/HDRISkySettings.cs


namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[DisallowMultipleComponent]
public class HDRISkySettings
: SkySettings
public class HDRISkySettings : SkySettings
}
public override int GetHashCode()
{
int hash = base.GetHashCode();
unchecked
{
hash = skyHDRI != null ? hash * 23 + skyHDRI.GetHashCode() : hash;
}
return hash;
}
}
}

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

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

正在加载...
取消
保存