浏览代码

Merge remote-tracking branch 'refs/remotes/origin/master' into Add-physical-Light-unit-2

/main
sebastienlagarde 7 年前
当前提交
a450e83a
共有 354 个文件被更改,包括 6067 次插入6746 次删除
  1. 23
      .gitignore
  2. 978
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1101_Unlit.unity.png
  3. 999
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1102_Unlit_Distortion.unity.png
  4. 999
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1103_Unlit_Distortion_DepthTest.unity.png
  5. 987
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1202_Lit_DoubleSideNormalMode.unity.png
  6. 999
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion.unity.png
  7. 45
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion.unity.png.meta
  8. 999
      ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2201_ReflectionProbes_Priority.unity.png
  9. 999
      ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2401_Light_on_Tesselation.unity.png
  10. 999
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3001_DebugView.unity.png
  11. 999
      ImageTemplates/HDRenderPipeline/Scenes/9xxx_Other/9001_Decals.unity.png
  12. 2
      ImageTemplates/HDRenderPipeline/Scenes/9xxx_Other/9001_Decals.unity.png.meta
  13. 244
      SampleScenes/HDTest/HDRenderLoopTest.unity
  14. 96
      ScriptableRenderPipeline/Core/CoreRP/CoreUtils.cs
  15. 15
      ScriptableRenderPipeline/Core/CoreRP/Debugging/DebugItemHandler.cs
  16. 2
      ScriptableRenderPipeline/Core/CoreRP/Debugging/DebugMenuManager.cs
  17. 90
      ScriptableRenderPipeline/Core/CoreRP/Editor/CoreEditorDrawers.cs
  18. 2
      ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugMenuEditor.cs
  19. 2
      ScriptableRenderPipeline/Core/CoreRP/Editor/ShaderGenerator/ShaderGeneratorMenu.cs
  20. 28
      ScriptableRenderPipeline/Core/CoreRP/Editor/ShaderGenerator/ShaderTypeGeneration.cs
  21. 494
      ScriptableRenderPipeline/Core/CoreRP/RTHandle.cs
  22. 8
      ScriptableRenderPipeline/Core/CoreRP/Resources/GPUCopy.compute
  23. 3
      ScriptableRenderPipeline/Core/CoreRP/Resources/GPUCopy.cs
  24. 11
      ScriptableRenderPipeline/Core/CoreRP/Resources/GPUCopyAsset.cs
  25. 15
      ScriptableRenderPipeline/Core/CoreRP/ShaderGenerator/ShaderGeneratorAttributes.cs
  26. 14
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Color.hlsl
  27. 79
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Common.hlsl
  28. 66
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/CommonLighting.hlsl
  29. 18
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Debug.hlsl
  30. 2
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/ImageBasedLighting.hlsl
  31. 4
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Shadow/Shadow.hlsl
  32. 7
      ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/VolumeRendering.hlsl
  33. 1
      ScriptableRenderPipeline/Core/CoreRP/Shadow/Shadow.cs
  34. 2
      ScriptableRenderPipeline/Core/CoreRP/TextureCache.cs
  35. 2
      ScriptableRenderPipeline/Core/package.json
  36. 106
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCamera.cs
  37. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugColorPicker.shader
  38. 63
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.cs
  39. 57
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.hlsl
  40. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplayLatlong.shader
  41. 28
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugFullScreen.shader
  42. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/LightingDebugPanel.cs
  43. 117
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/MaterialDebug.cs
  44. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalProjectorComponent.cs
  45. 66
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalSystem.cs
  46. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraEditor.cs
  47. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraUI.cs
  48. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Decal/DecalMenuItems.cs
  49. 94
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/EditorRenderPipelineResources/ReflectionProbesPreview.shader
  50. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDAssetFactory.cs
  51. 71
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDRenderPipelineMenuItems.cs
  52. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.cs
  53. 16
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.Drawers.cs
  54. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Drawers.cs
  55. 20
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Handles.cs
  56. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Drawers.cs
  57. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/Volume/ProxyVolumeUI.cs
  58. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Decal/DecalProjectorComponentEditor.cs
  59. 69
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/LayeredLit/LayeredLitUI.cs
  60. 43
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/BaseLitUI.cs
  61. 123
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/LitUI.cs
  62. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Unlit/BaseUnlitUI.cs
  63. 14
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/FrameSettingsUI.cs
  64. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/LightLoopSettingsUI.cs
  65. 16
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/RenderPipelineSettingsUI.cs
  66. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/SerializedRenderPipelineSettings.cs
  67. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/UpgradeStandardShaderMaterials.cs
  68. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDCustomSamplerId.cs
  69. 738
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs
  70. 13
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipelineAsset.asset
  71. 19
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipelineAsset.cs
  72. 57
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs
  73. 197
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs
  74. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Deferred.shader
  75. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/DeferredDirectionalShadow.compute
  76. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/GlobalLightLoopSettings.cs
  77. 111
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs
  78. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs.hlsl
  79. 24
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopDef.hlsl
  80. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopSettings.cs
  81. 28
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-clustered.compute
  82. 19
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/PlanarReflectionProbeCache.cs
  83. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ProbeWrapper.cs
  84. 20
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ReflectionProbeCache.cs
  85. 16
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ReflectionSystemInternal.cs
  86. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/HomogeneousFog.cs
  87. 72
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/Resources/VolumetricLighting.compute
  88. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VBuffer.hlsl
  89. 51
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumetricLighting.cs
  90. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Builtin/BuiltinData.cs
  91. 16
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Builtin/BuiltinData.cs.hlsl
  92. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs
  93. 9
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs.hlsl
  94. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.hlsl
  95. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalData.hlsl
  96. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalUtilities.hlsl
  97. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/RuntimeFilterIBL.cs
  98. 92
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLit.shader
  99. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitData.hlsl
  100. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitDataDisplacement.hlsl

23
.gitignore


artifacts/**
build/**
DataSource/*
obj/*
obj/*
*.aspx
*.browser
*.sln
*.suo
DataSource/*
*.exe
*.ini
*.map
*.browser
*.map
*.ini
*.npmrc
*.pyc
*.exe
*.aspx
*.sln
*.suo
*.npmrc

978
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1101_Unlit.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1102_Unlit_Distortion.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1103_Unlit_Distortion_DepthTest.unity.png
文件差异内容过多而无法显示
查看文件

987
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1202_Lit_DoubleSideNormalMode.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion.unity.png
文件差异内容过多而无法显示
查看文件

45
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion.unity.png.meta


serializedVersion: 5
mipmaps:
mipMapMode: 0
enableMipMap: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0

filterMode: -1
aniso: -1
mipBias: -1
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0

spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaUsage: 0
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0

platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Windows Store Apps
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1

999
ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2201_ReflectionProbes_Priority.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2401_Light_on_Tesselation.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3001_DebugView.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/HDRenderPipeline/Scenes/9xxx_Other/9001_Decals.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/HDRenderPipeline/Scenes/9xxx_Other/9001_Decals.unity.png.meta


fileFormatVersion: 2
guid: 9fab586a042724c48b681e13f81155d0
guid: 268e3faaa8b5b3644b9e5cab43b226c9
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

244
SampleScenes/HDTest/HDRenderLoopTest.unity


shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

m_LookSpeedController: 120
m_LookSpeedMouse: 10
m_MoveSpeed: 50
m_MoveSpeedIncrement: 2.5
m_Turbo: 10
--- !u!114 &1828470167
MonoBehaviour:

type: 2}
--- !u!114 &1828470169
MonoBehaviour:
m_ObjectHideFlags: 0
m_ObjectHideFlags: 2
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1828470159}

m_Bits: 4294967295
m_FrameSettings:
enableShadow: 1
enableContactShadows: 1
enableSSR: 1
enableSSAO: 1
enableSubsurfaceScattering: 1

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 1024
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

96
ScriptableRenderPipeline/Core/CoreRP/CoreUtils.cs


public const int editMenuPriority1 = 320;
public const int editMenuPriority2 = 331;
public const int editMenuPriority3 = 342;
public const int assetCreateMenuPriority1 = 230;
public const int assetCreateMenuPriority2 = 241;
public const int gameObjectMenuPriority = 10;

}
}
static RenderTexture m_EmptyUAV;
public static RenderTexture emptyUAV
{
get
{
if(m_EmptyUAV == null)
{
m_EmptyUAV = new RenderTexture(1, 1, 0);
m_EmptyUAV.enableRandomWrite = true;
m_EmptyUAV.Create();
}
return m_EmptyUAV;
}
}
public static void ClearRenderTarget(CommandBuffer cmd, ClearFlag clearFlag, Color clearColor)
{
if (clearFlag != ClearFlag.None)
cmd.ClearRenderTarget((clearFlag & ClearFlag.Depth) != 0, (clearFlag & ClearFlag.Color) != 0, clearColor);
}
if (clearFlag != ClearFlag.None)
cmd.ClearRenderTarget((clearFlag & ClearFlag.Depth) != 0, (clearFlag & ClearFlag.Color) != 0, clearColor);
ClearRenderTarget(cmd, clearFlag, clearColor);
}
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier buffer, ClearFlag clearFlag = ClearFlag.None, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)

public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthBuffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
{
cmd.SetRenderTarget(colorBuffer, depthBuffer, miplevel, cubemapFace, depthSlice);
if (clearFlag != ClearFlag.None)
cmd.ClearRenderTarget((clearFlag & ClearFlag.Depth) != 0, (clearFlag & ClearFlag.Color) != 0, clearColor);
ClearRenderTarget(cmd, clearFlag, clearColor);
}
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthBuffer)

public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthBuffer, ClearFlag clearFlag, Color clearColor)
{
cmd.SetRenderTarget(colorBuffers, depthBuffer);
if (clearFlag != ClearFlag.None)
cmd.ClearRenderTarget((clearFlag & ClearFlag.Depth) != 0, (clearFlag & ClearFlag.Color) != 0, clearColor);
}
public static RenderTexture CreateRenderTexture(RenderTextureDescriptor baseDesc, int depthBufferBits, RenderTextureFormat format,
RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default)
{
baseDesc.depthBufferBits = depthBufferBits;
baseDesc.colorFormat = format;
baseDesc.sRGB = (readWrite != RenderTextureReadWrite.Linear);
// Depth-only needs bindMS in order to use with CopyTexture
if ((format == RenderTextureFormat.Depth) && (baseDesc.msaaSamples > 1))
baseDesc.bindMS = true;
return new RenderTexture(baseDesc);
ClearRenderTarget(cmd, clearFlag, clearColor);
public static void CreateCmdTemporaryRT(CommandBuffer cmd, int nameID, RenderTextureDescriptor baseDesc,
int depthBufferBits, FilterMode filter, RenderTextureFormat format,
RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default, int msaaSamplesOverride = 0, bool enableRandomWrite = false)
public static string GetRenderTargetAutoName(int width, int height, RenderTextureFormat format, string name = "", bool mips = false, bool enableMSAA = false, MSAASamples msaaSamples = MSAASamples.None)
if (msaaSamplesOverride > 0)
UpdateRenderTextureDescriptor(ref baseDesc, depthBufferBits, format, readWrite, msaaSamplesOverride, enableRandomWrite);
string temp;
if (enableMSAA)
temp = string.Format("{0}x{1}_{2}{3}_{4}", width, height, format, mips ? "_Mips" : "", msaaSamples.ToString());
UpdateRenderTextureDescriptor(ref baseDesc, depthBufferBits, format, readWrite, baseDesc.msaaSamples, enableRandomWrite);
temp = string.Format("{0}x{1}_{2}{3}", width, height, format, mips ? "_Mips" : "");
temp = String.Format("{0}_{1}", name == "" ? "RenderTarget" : name, temp);
cmd.GetTemporaryRT(nameID, baseDesc, filter);
}
public static void UpdateRenderTextureDescriptor(ref RenderTextureDescriptor baseDesc, int depthBufferBits, RenderTextureFormat format, RenderTextureReadWrite readWrite, int msaaSamples, bool enableRandomWrite)
{
baseDesc.depthBufferBits = depthBufferBits;
baseDesc.colorFormat = format;
baseDesc.sRGB = (readWrite != RenderTextureReadWrite.Linear);
Debug.Assert(!enableRandomWrite || (msaaSamples == 1));
baseDesc.msaaSamples = msaaSamples;
baseDesc.enableRandomWrite = enableRandomWrite;
}
public static void ClearCubemap(CommandBuffer cmd, RenderTargetIdentifier buffer, Color clearColor)
{
// We should have the option to clear mip maps here, but since RenderTargetIdentifier, we can't know the number to clear...
// So for now, we won't do it.
for (int i = 0; i < 6; ++i)
SetRenderTarget(cmd, buffer, ClearFlag.Color, clearColor, 0, (CubemapFace)i);
return temp;
}
public static void ClearCubemap(CommandBuffer cmd, RenderTexture renderTexture, Color clearColor, bool clearMips = false)

mesh.triangles = triangles;
return mesh;
}
public static void ResizeHTile(ref RenderTexture hTile, ref RenderTargetIdentifier hTileRT, RenderTextureDescriptor desc)
{
// We must use a RenderTexture and not GetTemporaryRT() as currently Unity only aloow to bind a RenderTexture for a UAV in a pixel shader
// We use 8x8 tiles in order to match the native GCN HTile as closely as possible.
desc.width = (desc.width + 7) / 8;
desc.height = (desc.height + 7) / 8;
// TODO: This fails allocation with MSAA enabled?
hTile = CreateRenderTexture(desc, 0, RenderTextureFormat.R8, RenderTextureReadWrite.Linear); // DXGI_FORMAT_R8_UINT is not supported by Unity
hTile.filterMode = FilterMode.Point;
hTile.enableRandomWrite = true;
hTile.Create();
hTileRT = new RenderTargetIdentifier(hTile);
}
}
}

15
ScriptableRenderPipeline/Core/CoreRP/Debugging/DebugItemHandler.cs


{
protected uint m_Min = 0;
protected uint m_Max = 1;
protected Func<uint> m_MinGetter = null;
protected Func<uint> m_MaxGetter = null;
public uint min { get { return m_MinGetter != null ? m_MinGetter() : m_Min; } }
public uint max { get { return m_MaxGetter != null ? m_MaxGetter() : m_Max; } }
public DebugItemHandlerUIntMinMax(uint min, uint max)
{

public DebugItemHandlerUIntMinMax(Func<uint> minGetter, Func<uint> maxGetter)
{
m_MinGetter = minGetter;
m_MaxGetter = maxGetter;
}
setter(Math.Min(m_Max, Math.Max(m_Min, (uint)getter())));
setter(Math.Min(max, Math.Max(min, (uint)getter())));
}
#if UNITY_EDITOR

EditorGUI.BeginChangeCheck();
int value = EditorGUILayout.IntSlider(m_DebugItem.name, (int)(uint)m_DebugItem.GetValue(), (int)m_Min, (int)m_Max);
int value = EditorGUILayout.IntSlider(m_DebugItem.name, (int)(uint)m_DebugItem.GetValue(), (int)min, (int)max);
if (EditorGUI.EndChangeCheck())
{
m_DebugItem.SetValue((uint)value);

2
ScriptableRenderPipeline/Core/CoreRP/Debugging/DebugMenuManager.cs


public void AddDebugItem<DebugItemType>(string debugPanelName, string name, Func<object> getter, Action<object> setter = null, DebugItemFlag flags = DebugItemFlag.None, DebugItemHandler handler = null)
{
DebugPanel debugPanel = GetDebugPanel(debugPanelName);
// If the menu does not exist, create a generic one. This way, users don't have to explicitely create a new DebugMenu class if they don't need any particular overriding of default behavior.
// If the menu does not exist, create a generic one. This way, users don't have to explicitly create a new DebugMenu class if they don't need any particular overriding of default behavior.
if(debugPanel == null)
{
debugPanel = new DebugPanel<DebugPanelUI>(debugPanelName);

90
ScriptableRenderPipeline/Core/CoreRP/Editor/CoreEditorDrawers.cs


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

[Flags]
public enum FoldoutOption
{
None = 0,
Indent = 1 << 0,
Animate = 1 << 1
}
[Flags]
public enum FadeOption
{
None = 0,
Indent = 1 << 0,
Animate = 1 << 1
}
public static class CoreEditorDrawer<TUIState, TData>
{
public interface IDrawer

return new ActionDrawerInternal(drawers);
}
public static IDrawer FadeGroup(AnimBoolItemGetter fadeGetter, bool indent, params IDrawer[] groupDrawers)
public static IDrawer FadeGroup(AnimBoolItemGetter fadeGetter, FadeOption options, params IDrawer[] groupDrawers)
return new FadeGroupsDrawerInternal(fadeGetter, indent, groupDrawers);
return new FadeGroupsDrawerInternal(fadeGetter, options, groupDrawers);
public static IDrawer FoldoutGroup(string title, AnimBoolGetter root, bool indent, params IDrawer[] bodies)
public static IDrawer FoldoutGroup(string title, AnimBoolGetter root, FoldoutOption options, params IDrawer[] bodies)
return new FoldoutDrawerInternal(title, root, indent, bodies);
return new FoldoutDrawerInternal(title, root, options, bodies);
}
public static IDrawer Select<T2UIState, T2Data>(

class FadeGroupsDrawerInternal : IDrawer
{
IDrawer[] groupDrawers;
AnimBoolItemGetter getter;
bool indent;
IDrawer[] m_GroupDrawers;
AnimBoolItemGetter m_Getter;
FadeOption m_Options;
public FadeGroupsDrawerInternal(AnimBoolItemGetter getter, bool indent, params IDrawer[] groupDrawers)
bool indent { get { return (m_Options & FadeOption.Indent) != 0; } }
bool animate { get { return (m_Options & FadeOption.Animate) != 0; } }
public FadeGroupsDrawerInternal(AnimBoolItemGetter getter, FadeOption options, params IDrawer[] groupDrawers)
this.groupDrawers = groupDrawers;
this.getter = getter;
this.indent = indent;
m_GroupDrawers = groupDrawers;
m_Getter = getter;
m_Options = options;
}
void IDrawer.Draw(TUIState s, TData p, Editor owner)

GUILayout.BeginVertical();
for (var i = 0; i < groupDrawers.Length; ++i)
for (var i = 0; i < m_GroupDrawers.Length; ++i)
var b = getter(s, p, owner, i);
if (EditorGUILayout.BeginFadeGroup(b.faded))
var b = m_Getter(s, p, owner, i);
if (animate && EditorGUILayout.BeginFadeGroup(b.faded)
|| !animate && b.target)
groupDrawers[i].Draw(s, p, owner);
m_GroupDrawers[i].Draw(s, p, owner);
EditorGUILayout.EndFadeGroup();
if (animate)
EditorGUILayout.EndFadeGroup();
}
GUILayout.EndVertical();
}

{
IDrawer[] bodies;
AnimBoolGetter isExpanded;
string title;
bool indent;
IDrawer[] m_Bodies;
AnimBoolGetter m_IsExpanded;
string m_Title;
FoldoutOption m_Options;
bool m_Animate;
bool animate { get { return (m_Options & FoldoutOption.Animate) != 0; } }
bool indent { get { return (m_Options & FoldoutOption.Indent) != 0; } }
public FoldoutDrawerInternal(string title, AnimBoolGetter isExpanded, bool indent, params IDrawer[] bodies)
public FoldoutDrawerInternal(string title, AnimBoolGetter isExpanded, FoldoutOption options, params IDrawer[] bodies)
this.title = title;
this.isExpanded = isExpanded;
this.bodies = bodies;
this.indent = indent;
m_Title = title;
m_IsExpanded = isExpanded;
m_Bodies = bodies;
m_Options = options;
var r = isExpanded(s, p, owner);
var r = m_IsExpanded(s, p, owner);
r.target = CoreEditorUtils.DrawHeaderFoldout(title, r.target);
r.target = CoreEditorUtils.DrawHeaderFoldout(m_Title, r.target);
if (EditorGUILayout.BeginFadeGroup(r.faded))
if (animate && EditorGUILayout.BeginFadeGroup(r.faded)
|| !animate && r.target)
for (var i = 0; i < bodies.Length; i++)
bodies[i].Draw(s, p, owner);
for (var i = 0; i < m_Bodies.Length; i++)
m_Bodies[i].Draw(s, p, owner);
EditorGUILayout.EndFadeGroup();
if (animate)
EditorGUILayout.EndFadeGroup();
GUILayout.EndVertical();
}
}

2
ScriptableRenderPipeline/Core/CoreRP/Editor/Debugging/DebugMenuEditor.cs


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

2
ScriptableRenderPipeline/Core/CoreRP/Editor/ShaderGenerator/ShaderGeneratorMenu.cs


{
public class ShaderGeneratorMenu
{
[UnityEditor.MenuItem("Edit/Render Pipeline/Tools/Generate Shader Includes", priority = CoreUtils.editMenuPriority1)]
[UnityEditor.MenuItem("Edit/Render Pipeline/Generate Shader Includes", priority = CoreUtils.editMenuPriority1)]
static void GenerateShaderIncludes()
{
CSharpToHLSL.GenerateAll();

28
ScriptableRenderPipeline/Core/CoreRP/Editor/ShaderGenerator/ShaderTypeGeneration.cs


if (attr.needParamDebug)
{
string className = type.FullName.Substring(type.FullName.LastIndexOf((".")) + 1); // ClassName include nested class
className = className.Replace('+', '_'); // FullName is Class+NestedClass replace by Class_NestedClass
string name = InsertUnderscore(field.Name);
string defineName = ("DEBUGVIEW_" + className + "_" + name).ToUpper();
m_Statics[defineName] = Convert.ToString(attr.paramDefinesStart + debugCounter++);
List<string> displayNames = new List<string>();
displayNames.Add(field.Name);
bool isDirection = false;
bool sRGBDisplay = false;

{
var propertyAttr = (SurfaceDataAttributes[])field.GetCustomAttributes(typeof(SurfaceDataAttributes), false);
// User can want to only override isDirection and sRGBDisplay
// in this case it can specify empty string
if (propertyAttr[0].displayNames[0] != "")
{
displayNames.Clear();
displayNames.AddRange(propertyAttr[0].displayNames);
}
m_DebugFields.Add(new DebugFieldInfo(defineName, field.Name, field.FieldType, isDirection, sRGBDisplay));
string className = type.FullName.Substring(type.FullName.LastIndexOf((".")) + 1); // ClassName include nested class
className = className.Replace('+', '_'); // FullName is Class+NestedClass replace by Class_NestedClass
foreach (string it in displayNames)
{
string fieldName = it.Replace(' ', '_');
string name = InsertUnderscore(fieldName);
string defineName = ("DEBUGVIEW_" + className + "_" + name).ToUpper();
m_Statics[defineName] = Convert.ToString(attr.paramDefinesStart + debugCounter++);
m_DebugFields.Add(new DebugFieldInfo(defineName, field.Name, field.FieldType, isDirection, sRGBDisplay));
}
}
if (field.FieldType.IsPrimitive)

494
ScriptableRenderPipeline/Core/CoreRP/RTHandle.cs


public class RTHandle
{
public static int s_MaxWidth { get; private set; }
public static int s_MaxHeight { get; private set; }
enum RTCategory
{
Regular = 0,
MSAA = 1,
Count
}
// Static management.
public static int s_MaxWidth { get { return s_MaxWidths[(int)RTCategory.Regular]; } }
public static int s_MaxHeight { get { return s_MaxHeights[(int)RTCategory.Regular]; } }
public static int s_MaxWidthMSAAA { get { return s_MaxWidths[(int)RTCategory.MSAA]; } }
public static int s_MaxHeightMSAA { get { return s_MaxHeights[(int)RTCategory.MSAA]; } }
private static int GetMaxWidth(RTCategory category) { return s_MaxWidths[(int)category]; }
private static int GetMaxHeight(RTCategory category) { return s_MaxHeights[(int)category]; }
static List<RTHandle> s_AutoSizedRTs;
public RenderTexture rt { get; private set; }
public RenderTargetIdentifier nameID;
// Parameters for auto-scaled Render Textures
static bool s_ScaledRTSupportsMSAA = false;
static MSAASamples s_ScaledRTCurrentMSAASamples = MSAASamples.None;
static List<RTHandle> s_AutoSizedRTs;
static RTCategory s_ScaledRTCurrentCategory = RTCategory.Regular;
Vector2 scaleFactor = Vector2.one;
ScaleFunc scaleFunc;
static int[] s_MaxWidths = new int[(int)RTCategory.Count];
static int[] s_MaxHeights = new int[(int)RTCategory.Count];
public static int maxWidth { get { return GetMaxWidth(s_ScaledRTCurrentCategory); } }
public static int maxHeight { get { return GetMaxHeight(s_ScaledRTCurrentCategory); } }
s_MaxWidth = 1;
s_MaxHeight = 1;
for (int i = 0; i < (int)RTCategory.Count; ++i)
{
s_MaxWidths[i] = 1;
s_MaxHeights[i] = 1;
}
RTHandle(RenderTexture rt)
// Call this once to set the initial size and allow msaa targets or not.
public static void Initialize(int width, int height, bool scaledRTsupportsMSAA, MSAASamples scaledRTMSAASamples)
this.rt = rt;
nameID = new RenderTargetIdentifier(rt);
}
Debug.Assert(s_AutoSizedRTs.Count == 0, "RTHandle.Initialize should only be called once before allocating any Render Texture.");
for (int i = 0; i < (int)RTCategory.Count; ++i)
{
s_MaxWidths[i] = width;
s_MaxHeights[i] = height;
}
public void Release()
{
s_AutoSizedRTs.Remove(this);
CoreUtils.Destroy(rt);
rt = null;
nameID = BuiltinRenderTextureType.None;
s_ScaledRTSupportsMSAA = scaledRTsupportsMSAA;
s_ScaledRTCurrentMSAASamples = scaledRTMSAASamples;
rth.Release();
if(rth != null)
rth.Release();
public static void SetReferenceSize(int width, int height)
public static void SetReferenceSize(int width, int height, bool msaa, MSAASamples msaaSamples)
// Technically, the enum could be passed as argument directly but let's not pollute public API with unnecessary complexity for now.
RTCategory category = msaa ? RTCategory.MSAA : RTCategory.Regular;
if (width > s_MaxWidth || height > s_MaxHeight)
Resize(width, height);
bool msaaSamplesChanged = msaa && (msaaSamples != s_ScaledRTCurrentMSAASamples);
if (width > GetMaxWidth(category) || height > GetMaxHeight(category) || msaaSamplesChanged)
Resize(width, height, category, msaaSamples);
public static void ResetReferenceSize(int width, int height)
public static void ResetReferenceSize(int width, int height, bool msaa, MSAASamples msaaSamples)
// Technically, the enum could be passed as argument directly but let's not pollute public API with unnecessary complexity for now.
RTCategory category = msaa ? RTCategory.MSAA : RTCategory.Regular;
if (width != s_MaxWidth || height != s_MaxHeight)
Resize(width, height);
bool msaaSamplesChanged = msaa && (msaaSamples != s_ScaledRTCurrentMSAASamples);
if (width != GetMaxWidth(category) || height != GetMaxHeight(category) || msaaSamplesChanged)
Resize(width, height, category, msaaSamples);
static void Resize(int width, int height)
static void Resize(int width, int height, RTCategory category, MSAASamples msaaSamples)
s_MaxWidth = width;
s_MaxHeight = height;
var maxSize = new Vector2Int(s_MaxWidth, s_MaxHeight);
s_MaxWidths[(int)category] = width;
s_MaxHeights[(int)category] = height;
s_ScaledRTCurrentMSAASamples = msaaSamples;
var maxSize = new Vector2Int(width, height);
s_ScaledRTCurrentCategory = category;
var rt = rth.rt;
rt.Release();
var rt = rth.m_RTs[(int)category];
// This can happen if you create a RTH for MSAA. By default we only create the MSAA version of the target.
// Missing version will be created when needed in the getter.
if (rt != null)
{
rt.Release();
Vector2Int scaledSize = rth.GetScaledSize(maxSize);
rt.width = Mathf.Max(scaledSize.x, 1);
rt.height = Mathf.Max(scaledSize.y, 1);
Vector2Int scaledSize;
if (category == RTCategory.MSAA)
rt.antiAliasing = (int)s_ScaledRTCurrentMSAASamples;
if (rth.scaleFunc != null)
{
scaledSize = rth.scaleFunc(maxSize);
}
else
{
scaledSize = new Vector2Int(
x: Mathf.RoundToInt(rth.scaleFactor.x * s_MaxWidth),
y: Mathf.RoundToInt(rth.scaleFactor.y * s_MaxHeight)
);
rt.name = CoreUtils.GetRenderTargetAutoName(rt.width, rt.height, rt.format, rth.m_Name, mips: rt.useMipMap, enableMSAA : category == RTCategory.MSAA, msaaSamples: s_ScaledRTCurrentMSAASamples);
rt.Create();
rt.width = Mathf.Max(scaledSize.x, 1);
rt.height = Mathf.Max(scaledSize.y, 1);
rt.Create();
// This method wraps around regular RenderTexture creation.
// There is no specific logic applied to RenderTextures created this way.
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0f,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0f,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
string name = ""
bool enableMSAA = msaaSamples != MSAASamples.None;
if (!enableMSAA && bindTextureMS == true)
{
Debug.LogWarning("RTHandle allocated without MSAA but with bindMS set to true, forcing bindMS to false.");
bindTextureMS = false;
}
var rt = new RenderTexture(width, height, (int)depthBufferBits, colorFormat, sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear)
{
hideFlags = HideFlags.HideAndDontSave,

bindTextureMS = bindTextureMS,
useDynamicScale = useDynamicScale,
vrUsage = vrUsage,
memorylessMode = memoryless
memorylessMode = memoryless,
name = CoreUtils.GetRenderTargetAutoName(width, height, colorFormat, name, mips: useMipMap, enableMSAA: enableMSAA, msaaSamples: msaaSamples)
return new RTHandle(rt);
RTCategory category = enableMSAA ? RTCategory.MSAA : RTCategory.Regular;
var newRT = new RTHandle();
newRT.SetRenderTexture(rt, category);
newRT.useScaling = false;
newRT.m_EnableRandomWrite = enableRandomWrite;
newRT.m_EnableMSAA = enableMSAA;
newRT.m_Name = name;
return newRT;
// Next two methods are used to allocate RenderTexture that depend on the frame settings (resolution and msaa for now)
// RenderTextures allocated this way are meant to be defined by a scale of camera resolution (full/half/quarter resolution for example).
// The idea is that internally the system will scale up the size of all render texture so that it amortizes with time and not reallocate when a smaller size is required (which is what happens with TemporaryRTs).
// Since MSAA cannot be changed on the fly for a given RenderTexture, a separate instance will be created if the user requires it. This instance will be the one used after the next call of SetReferenceSize if MSAA is required.
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0f,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0f,
bool enableMSAA = false,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
string name = ""
int width = Mathf.Max(Mathf.RoundToInt(scaleFactor.x * s_MaxWidth), 1);
int height = Mathf.Max(Mathf.RoundToInt(scaleFactor.y * s_MaxHeight), 1);
bool allocForMSAA = s_ScaledRTSupportsMSAA ? enableMSAA : false;
RTCategory category = allocForMSAA ? RTCategory.MSAA : RTCategory.Regular;
int width = Mathf.Max(Mathf.RoundToInt(scaleFactor.x * GetMaxWidth(category)), 1);
int height = Mathf.Max(Mathf.RoundToInt(scaleFactor.y * GetMaxHeight(category)), 1);
var rth = Alloc(width,
var rth = AllocAutoSizedRenderTexture(width,
height,
1,
depthBufferBits,

autoGenerateMips,
anisoLevel,
mipMapBias,
msaaSamples,
enableMSAA,
memoryless
memoryless,
name
s_AutoSizedRTs.Add(rth);
return rth;
}

//
public static RTHandle Alloc(
ScaleFunc scaleFunc,
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0f,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None
DepthBits depthBufferBits = DepthBits.None,
RenderTextureFormat colorFormat = RenderTextureFormat.Default,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool sRGB = true,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
int anisoLevel = 1,
float mipMapBias = 0f,
bool enableMSAA = false,
bool bindTextureMS = false,
bool useDynamicScale = false,
VRTextureUsage vrUsage = VRTextureUsage.None,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
string name = ""
var scaleFactor = scaleFunc(new Vector2Int(s_MaxWidth, s_MaxHeight));
bool allocForMSAA = s_ScaledRTSupportsMSAA ? enableMSAA : false;
RTCategory category = allocForMSAA ? RTCategory.MSAA : RTCategory.Regular;
var scaleFactor = scaleFunc(new Vector2Int(GetMaxWidth(category), GetMaxHeight(category)));
var rth = Alloc(width,
var rth = AllocAutoSizedRenderTexture(width,
height,
1,
depthBufferBits,

autoGenerateMips,
anisoLevel,
mipMapBias,
msaaSamples,
enableMSAA,
memoryless
memoryless,
name
return rth;
}
// Internal function
static RTHandle AllocAutoSizedRenderTexture(
int width,
int height,
int slices,
DepthBits depthBufferBits,
RenderTextureFormat colorFormat,
FilterMode filterMode,
TextureWrapMode wrapMode,
TextureDimension dimension,
bool sRGB,
bool enableRandomWrite,
bool useMipMap,
bool autoGenerateMips,
int anisoLevel,
float mipMapBias,
bool enableMSAA,
bool bindTextureMS,
bool useDynamicScale,
VRTextureUsage vrUsage,
RenderTextureMemoryless memoryless,
string name
)
{
// Here user made a mistake in setting up msaa/bindMS, hence the warning
if (!enableMSAA && bindTextureMS == true)
{
Debug.LogWarning("RTHandle allocated without MSAA but with bindMS set to true, forcing bindMS to false.");
bindTextureMS = false;
}
bool allocForMSAA = s_ScaledRTSupportsMSAA ? enableMSAA : false;
// Here we purposefully disable MSAA so we just force the bindMS param to false.
if (!allocForMSAA)
{
bindTextureMS = false;
}
// MSAA Does not support random read/write.
bool UAV = enableRandomWrite;
if (allocForMSAA && (UAV == true))
{
Debug.LogWarning("RTHandle that is MSAA-enabled cannot allocate MSAA RT with 'enableRandomWrite = true'.");
UAV = false;
}
int msaaSamples = allocForMSAA ? (int)s_ScaledRTCurrentMSAASamples : 1;
RTCategory category = allocForMSAA ? RTCategory.MSAA : RTCategory.Regular;
var rt = new RenderTexture(width, height, (int)depthBufferBits, colorFormat, sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear)
{
hideFlags = HideFlags.HideAndDontSave,
volumeDepth = slices,
filterMode = filterMode,
wrapMode = wrapMode,
dimension = dimension,
enableRandomWrite = UAV,
useMipMap = useMipMap,
autoGenerateMips = autoGenerateMips,
anisoLevel = anisoLevel,
mipMapBias = mipMapBias,
antiAliasing = msaaSamples,
bindTextureMS = bindTextureMS,
useDynamicScale = useDynamicScale,
vrUsage = vrUsage,
memorylessMode = memoryless,
name = CoreUtils.GetRenderTargetAutoName(width, height, colorFormat, name, mips : useMipMap, enableMSAA: allocForMSAA, msaaSamples : s_ScaledRTCurrentMSAASamples)
};
rt.Create();
RTHandle rth = new RTHandle();
rth.SetRenderTexture(rt, category);
rth.m_EnableMSAA = enableMSAA;
rth.m_EnableRandomWrite = enableRandomWrite;
rth.useScaling = true;
rth.m_Name = name;
s_AutoSizedRTs.Add(rth);
return rth;
}

public static implicit operator RenderTargetIdentifier(RTHandle handle)
{
return handle.nameID;
}
public static string DumpRTInfo()
{
string result = "";
for (int i = 0; i < s_AutoSizedRTs.Count; ++i)
{
RenderTexture rt = s_AutoSizedRTs[i].rt;
result = string.Format("{0}\nRT ({1})\t Format: {2} W: {3} H {4}\n", result, i, rt.format, rt.width, rt.height );
}
return result;
}
// Instance data
RenderTexture[] m_RTs = new RenderTexture[2];
RenderTargetIdentifier[] m_NameIDs = new RenderTargetIdentifier[2];
bool m_EnableMSAA = false;
bool m_EnableRandomWrite = false;
string m_Name;
Vector2 scaleFactor = Vector2.one;
ScaleFunc scaleFunc;
public bool useScaling { get; private set; }
public RenderTexture rt
{
get
{
if(!useScaling)
{
return m_EnableMSAA ? m_RTs[(int)RTCategory.MSAA] : m_RTs[(int)RTCategory.Regular];
}
else
{
RTCategory category = (m_EnableMSAA && s_ScaledRTCurrentCategory == RTCategory.MSAA) ? RTCategory.MSAA : RTCategory.Regular;
CreateIfNeeded(category);
return m_RTs[(int)category];
}
}
}
public RenderTargetIdentifier nameID
{
get
{
if (!useScaling)
{
return m_EnableMSAA ? m_NameIDs[(int)RTCategory.MSAA] : m_RTs[(int)RTCategory.Regular];
}
else
{
RTCategory category = (m_EnableMSAA && s_ScaledRTCurrentCategory == RTCategory.MSAA) ? RTCategory.MSAA : RTCategory.Regular;
CreateIfNeeded(category);
return m_NameIDs[(int)category];
}
}
}
// Keep constructor private
RTHandle()
{
}
void SetRenderTexture(RenderTexture rt, RTCategory category)
{
m_RTs[(int)category] = rt;
m_NameIDs[(int)category] = new RenderTargetIdentifier(rt);
}
void CreateIfNeeded(RTCategory category)
{
// If a RT was first created for MSAA then the regular one might be null, in this case we create it.
// That's why we never test the MSAA version: It should always be there if RT was declared correctly.
if(category == RTCategory.Regular && m_RTs[(int)RTCategory.Regular] == null)
{
RenderTexture refRT = m_RTs[(int)RTCategory.MSAA];
Debug.Assert(refRT != null);
Vector2Int scaledSize = GetScaledSize(new Vector2Int(s_MaxWidth, s_MaxHeight));
RenderTexture newRT = new RenderTexture(scaledSize.x, scaledSize.y, refRT.depth, refRT.format, refRT.sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear)
{
hideFlags = HideFlags.HideAndDontSave,
volumeDepth = refRT.volumeDepth,
filterMode = refRT.filterMode,
wrapMode = refRT.wrapMode,
dimension = refRT.dimension,
enableRandomWrite = m_EnableRandomWrite, // We cannot take the info from the msaa rt since we force it to 1
useMipMap = refRT.useMipMap,
autoGenerateMips = refRT.autoGenerateMips,
anisoLevel = refRT.anisoLevel,
mipMapBias = refRT.mipMapBias,
antiAliasing = 1, // No MSAA for the regular version of the texture.
bindTextureMS = false, // Somehow, this can be true even if antiAliasing == 1. Leads to Unity-internal binding errors.
useDynamicScale = refRT.useDynamicScale,
vrUsage = refRT.vrUsage,
memorylessMode = refRT.memorylessMode,
name = CoreUtils.GetRenderTargetAutoName(refRT.width, refRT.height, refRT.format, m_Name, mips : refRT.useMipMap)
};
newRT.Create();
m_RTs[(int)RTCategory.Regular] = newRT;
m_NameIDs[(int)RTCategory.Regular] = new RenderTargetIdentifier(newRT);
}
}
public void Release()
{
s_AutoSizedRTs.Remove(this);
for (int i = 0; i < (int)RTCategory.Count; ++i)
{
CoreUtils.Destroy(m_RTs[i]);
m_NameIDs[i] = BuiltinRenderTextureType.None;
m_RTs[i] = null;
}
}
public Vector2Int GetScaledSize(Vector2Int refSize)
{
if (scaleFunc != null)
{
return scaleFunc(refSize);
}
else
{
return new Vector2Int(
x: Mathf.RoundToInt(scaleFactor.x * refSize.x),
y: Mathf.RoundToInt(scaleFactor.y * refSize.y)
);
}
}
}
}

8
ScriptableRenderPipeline/Core/CoreRP/Resources/GPUCopy.compute


#include "../ShaderLibrary/Common.hlsl"
SamplerState sampler_LinearClamp;
CBUFFER_START(cb)
float4 _Size;
CBUFFER_END
RWTexture2D<float1> _Result1;
Texture2D<float4> _Source4;

[numthreads(8, 8, 1)]
void KSampleCopy4_1_x(uint2 dispatchThreadId : SV_DispatchThreadID)
{
_Result1[dispatchThreadId] = SAMPLE_TEXTURE2D_LOD(_Source4, sampler_LinearClamp, float2(dispatchThreadId) * _Size.zw, 0.0).x;
_Result1[dispatchThreadId] = LOAD_TEXTURE2D(_Source4, dispatchThreadId).x;
}

3
ScriptableRenderPipeline/Core/CoreRP/Resources/GPUCopy.cs


static readonly int _Result1 = Shader.PropertyToID("_Result1");
static readonly int _Source4 = Shader.PropertyToID("_Source4");
static readonly int _Size = Shader.PropertyToID("_Size");
var s = new Vector4(size.x, size.y, 1f / size.x, 1f / size.y);
cmd.SetComputeVectorParam(m_Shader, _Size, s);
cmd.SetComputeTextureParam(m_Shader, k_SampleKernel_xyzw2x, _Source4, source);
cmd.SetComputeTextureParam(m_Shader, k_SampleKernel_xyzw2x, _Result1, target);
cmd.DispatchCompute(m_Shader, k_SampleKernel_xyzw2x, (int)Mathf.Max((size.x) / 8, 1), (int)Mathf.Max((size.y) / 8, 1), 1);

11
ScriptableRenderPipeline/Core/CoreRP/Resources/GPUCopyAsset.cs


csc.AppendLine(" public GPUCopy(ComputeShader shader)");
csc.AppendLine(" {");
csc.AppendLine(" m_Shader = shader;");
csm.AppendLine(" static readonly int _Size = Shader.PropertyToID(\"_Size\");");
for (var i = 0; i < operations.Length; i++)
{
var o = operations[i];

k_KernelSize.ToString(), k_KernelSize.ToString()));
cck.AppendLine(string.Format(@"void {0}(uint2 dispatchThreadId : SV_DispatchThreadID)", kernelName));
cck.AppendLine("{");
cck.AppendLine(string.Format(" _Result{0}[dispatchThreadId] = SAMPLE_TEXTURE2D_LOD(_Source{1}, sampler_LinearClamp, float2(dispatchThreadId) * _Size.zw, 0.0).{2};",
cck.AppendLine(string.Format(" _Result{0}[dispatchThreadId] = LOAD_TEXTURE2D(_Source{1}, dispatchThreadId).{2};",
o.targetChannel.ToString(), o.sourceChannel.ToString(), o.subscript));
cck.AppendLine("}");
cck.AppendLine();

// CSharp method
csm.AppendLine(string.Format(@" public void SampleCopyChannel_{0}2{1}(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier target, Vector2 size)", channelName, o.subscript));
csm.AppendLine(" {");
csm.AppendLine(" var s = new Vector4(size.x, size.y, 1f / size.x, 1f / size.y);");
csm.AppendLine(" cmd.SetComputeVectorParam(m_Shader, _Size, s);");
csm.AppendLine(string.Format(" cmd.SetComputeTextureParam(m_Shader, {0}, _Source{1}, source);", kernelIndexName, o.sourceChannel.ToString()));
csm.AppendLine(string.Format(" cmd.SetComputeTextureParam(m_Shader, {0}, _Result{1}, target);", kernelIndexName, o.targetChannel.ToString()));
csm.AppendLine(string.Format(" cmd.DispatchCompute(m_Shader, {0}, (int)Mathf.Max((size.x) / {1}, 1), (int)Mathf.Max((size.y) / {1}, 1), 1);", kernelIndexName, k_KernelSize.ToString()));

cc.AppendLine(@"// Autogenerated file. Do not edit by hand");
cc.AppendLine();
cc.AppendLine(@"#include ""../ShaderLibrary/Common.hlsl""");
cc.AppendLine();
cc.AppendLine(@"SamplerState sampler_LinearClamp;");
cc.AppendLine();
cc.AppendLine(@"CBUFFER_START(cb)");
cc.AppendLine(@" float4 _Size;");
cc.AppendLine(@"CBUFFER_END");
cc.AppendLine(ccp.ToString()); // Properties
cc.AppendLine(cck.ToString()); // Kernels

15
ScriptableRenderPipeline/Core/CoreRP/ShaderGenerator/ShaderGeneratorAttributes.cs


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

[AttributeUsage(AttributeTargets.Field)]
public class SurfaceDataAttributes : System.Attribute
{
public string displayName;
public string[] displayNames;
this.displayName = displayName;
displayNames = new string[1];
displayNames[0] = displayName;
this.isDirection = isDirection;
this.sRGBDisplay = sRGBDisplay;
}
// We allow users to add several names for one field, so user can override the auto behavior and do something else with the same data
// typical example is normal that you want to draw in view space or world space. So user can override view space case and do the transform.
public SurfaceDataAttributes(string[] displayName, bool isDirection = false, bool sRGBDisplay = false)
{
displayNames = displayName;
this.isDirection = isDirection;
this.sRGBDisplay = sRGBDisplay;
}

14
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Color.hlsl


// Gamma22
real Gamma22ToLinear(real c)
{
return pow(c, 2.2);
return PositivePow(c, 2.2);
return pow(c.rgb, real3(2.2, 2.2, 2.2));
return PositivePow(c.rgb, real3(2.2, 2.2, 2.2));
}
real4 Gamma22ToLinear(real4 c)

real LinearToGamma22(real c)
{
return pow(c, 0.454545454545455);
return PositivePow(c, 0.454545454545455);
return pow(c.rgb, real3(0.454545454545455, 0.454545454545455, 0.454545454545455));
return PositivePow(c.rgb, real3(0.454545454545455, 0.454545454545455, 0.454545454545455));
}
real4 LinearToGamma22(real4 c)

real3 SRGBToLinear(real3 c)
{
real3 linearRGBLo = c / 12.92;
real3 linearRGBHi = pow((c + 0.055) / 1.055, real3(2.4, 2.4, 2.4));
real3 linearRGBHi = PositivePow((c + 0.055) / 1.055, real3(2.4, 2.4, 2.4));
real3 linearRGB = (c <= 0.04045) ? linearRGBLo : linearRGBHi;
return linearRGB;
}

real3 LinearToSRGB(real3 c)
{
real3 sRGBLo = c * 12.92;
real3 sRGBHi = (pow(c, real3(1.0/2.4, 1.0/2.4, 1.0/2.4)) * 1.055) - 0.055;
real3 sRGBHi = (PositivePow(c, real3(1.0/2.4, 1.0/2.4, 1.0/2.4)) * 1.055) - 0.055;
real3 sRGB = (c <= 0.0031308) ? sRGBLo : sRGBHi;
return sRGB;
}

real3 FastLinearToSRGB(real3 c)
{
return saturate(1.055 * pow(abs(c), 0.416666667) - 0.055);
return saturate(1.055 * PositivePow(c, 0.416666667) - 0.055);
}
real4 FastLinearToSRGB(real4 c)

79
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Common.hlsl


}
#endif // INTRINSIC_CUBEMAP_FACE_ID
// Intrinsic isnan can't be used because it require /Gic to be enabled on fxc that we can't do. So use IsNAN instead
bool IsNAN(float n)
// Intrinsic isnan can't be used because it require /Gic to be enabled on fxc that we can't do. So use AnyIsNan instead
bool IsNan(float n)
bool IsNAN(float2 v)
bool AnyIsNan(float2 v)
return (IsNAN(v.x) || IsNAN(v.y)) ? true : false;
return (IsNan(v.x) || IsNan(v.y));
bool IsNAN(float3 v)
bool AnyIsNan(float3 v)
return (IsNAN(v.x) || IsNAN(v.y) || IsNAN(v.z)) ? true : false;
return (IsNan(v.x) || IsNan(v.y) || IsNan(v.z));
bool IsNAN(float4 v)
bool AnyIsNan(float4 v)
return (IsNAN(v.x) || IsNAN(v.y) || IsNAN(v.z) || IsNAN(v.w)) ? true : false;
return (IsNan(v.x) || IsNan(v.y) || IsNan(v.z) || IsNan(v.w));
}
// ----------------------------------------------------------------------------

// Using pow often result to a warning like this
// "pow(f, e) will not work for negative f, use abs(f) or conditionally handle negative values if you expect them"
// PositivePow remove this warning when you know the value is positive and avoid inf/NAN.
TEMPLATE_2_REAL(PositivePow, base, power, return pow(max(abs(base), FLT_EPS), power))
// PositivePow remove this warning when you know the value is positive or 0 and avoid inf/NAN.
// Note: https://msdn.microsoft.com/en-us/library/windows/desktop/bb509636(v=vs.85).aspx pow(0, >0) == 0
TEMPLATE_2_REAL(PositivePow, base, power, return pow(abs(base), power))
// Composes a floating point value with the magnitude of 'x' and the sign of 's'.
// See the comment about FastSign() below.

0, 0, 1, 0,
0, 0, 0, 1};
// Use case examples:
// (position = positionCS) => (clipSpaceTransform = use default)
// (position = positionVS) => (clipSpaceTransform = UNITY_MATRIX_P)
// (position = positionWS) => (clipSpaceTransform = UNITY_MATRIX_VP)
float4 ComputeClipSpaceCoordinates(float3 position, float4x4 clipSpaceTransform = k_identity4x4)
float4 ComputeClipSpacePosition(float2 positionNDC, float deviceDepth)
float4 positionCS = mul(clipSpaceTransform, float4(position, 1.0));
float4 positionCS = float4(positionNDC * 2.0 - 1.0, deviceDepth, 1.0);
// Our clip space is correct, but the NDC is flipped.
// Conceptually, it should be (positionNDC.y = 1.0 - positionNDC.y), but this is more efficient.
// Our world space, view space, screen space and NDC space are Y-up.
// Our clip space is flipped upside-down due to poor legacy Unity design.
// The flip is baked into the projection matrix, so we only have to flip
// manually when going from CS to NDC and back.
positionCS.y = -positionCS.y;
#endif

// (position = positionCS) => (clipSpaceTransform = use default)
// (position = positionVS) => (clipSpaceTransform = UNITY_MATRIX_P)
// (position = positionWS) => (clipSpaceTransform = UNITY_MATRIX_VP)
float2 ComputeNormalizedDeviceCoordinates(float3 position, float4x4 clipSpaceTransform = k_identity4x4)
float4 ComputeClipSpacePosition(float3 position, float4x4 clipSpaceTransform = k_identity4x4)
float4 positionCS = ComputeClipSpaceCoordinates(position, clipSpaceTransform);
return positionCS.xy * (rcp(positionCS.w) * 0.5) + 0.5;
return mul(clipSpaceTransform, float4(position, 1.0));
float4 ComputeClipSpacePosition(float2 positionNDC, float deviceDepth)
// Use case examples:
// (position = positionCS) => (clipSpaceTransform = use default)
// (position = positionVS) => (clipSpaceTransform = UNITY_MATRIX_P)
// (position = positionWS) => (clipSpaceTransform = UNITY_MATRIX_VP)
float3 ComputeNormalizedDeviceCoordinatesWithZ(float3 position, float4x4 clipSpaceTransform = k_identity4x4)
float4 positionCS = float4(positionNDC * 2.0 - 1.0, deviceDepth, 1.0);
float4 positionCS = ComputeClipSpacePosition(position, clipSpaceTransform);
// Our clip space is correct, but the NDC is flipped.
// Conceptually, it should be (positionNDC.y = 1.0 - positionNDC.y), but this is more efficient.
// Our world space, view space, screen space and NDC space are Y-up.
// Our clip space is flipped upside-down due to poor legacy Unity design.
// The flip is baked into the projection matrix, so we only have to flip
// manually when going from CS to NDC and back.
return positionCS;
positionCS *= rcp(positionCS.w);
positionCS.xy = positionCS.xy * 0.5 + 0.5;
return positionCS.xyz;
}
// Use case examples:
// (position = positionCS) => (clipSpaceTransform = use default)
// (position = positionVS) => (clipSpaceTransform = UNITY_MATRIX_P)
// (position = positionWS) => (clipSpaceTransform = UNITY_MATRIX_VP)
float2 ComputeNormalizedDeviceCoordinates(float3 position, float4x4 clipSpaceTransform = k_identity4x4)
{
return ComputeNormalizedDeviceCoordinatesWithZ(position, clipSpaceTransform).xy;
}
float3 ComputeViewSpacePosition(float2 positionNDC, float deviceDepth, float4x4 invProjMatrix)

struct PositionInputs
{
float3 positionWS; // World space position (could be camera-relative)
float2 positionNDC; // Normalized screen UVs : [0, 1) (with the half-pixel offset)
uint2 positionSS; // Screen space pixel coordinates : [0, NumPixels)
uint2 tileCoord; // Screen tile coordinates : [0, NumTiles)
float deviceDepth; // Depth from the depth buffer : [0, 1] (typically reversed)
float linearDepth; // View space Z coordinate : [Near, Far]
float2 positionNDC; // Normalized screen coordinates within the viewport : [0, 1) (with the half-pixel offset)
uint2 positionSS; // Screen space pixel coordinates : [0, NumPixels)
uint2 tileCoord; // Screen tile coordinates : [0, NumTiles)
float deviceDepth; // Depth from the depth buffer : [0, 1] (typically reversed)
float linearDepth; // View space Z coordinate : [Near, Far]
};
// This function is use to provide an easy way to sample into a screen texture, either from a pixel or a compute shaders.

66
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/CommonLighting.hlsl


// texelArea = 4.0 / (resolution * resolution).
// Ref: http://bpeers.com/blog/?itemid=1017
// This version is less accurate, but much faster than this one:
// http://www.rorydriscoll.com/2012/01/15/cubemap-texel-solid-angle/
real ComputeCubemapTexelSolidAngle(real3 L, real texelArea)
{
// Stretch 'L' by (1/d) so that it points at a side of a [-1, 1]^2 cube.

return texelArea * invDist * invDist * invDist;
}
// Only makes sense for Monte-Carlo integration.
// Normalize by dividing by the total weight (or the number of samples) in the end.
// Integrate[6*(u^2+v^2+1)^(-3/2), {u,-1,1},{v,-1,1}] = 4 * Pi
// Ref: "Stupid Spherical Harmonics Tricks", p. 9.
real ComputeCubemapTexelSolidAngle(real2 uv)
{
float u = uv.x, v = uv.y;
return pow(1 + u * u + v * v, -1.5);
}
real QuadraticAttenuation(real attenuation)
{
return attenuation * attenuation;
}
real DistanceAttenuation(real squaredDistance, real invSqrAttenuationRadius)
// SmoothInfluenceAttenuation must be use, InfluenceAttenuation is just for optimization with SmoothQuadraticDistanceAttenuation
real InfluenceAttenuation(real distSquare, real invSqrAttenuationRadius)
real factor = squaredDistance * invSqrAttenuationRadius;
real factor = distSquare * invSqrAttenuationRadius;
real SmoothDistanceAttenuation(real squaredDistance, real invSqrAttenuationRadius)
real SmoothInfluenceAttenuation(real distSquare, real invSqrAttenuationRadius)
real smoothFactor = DistanceAttenuation(squaredDistance, invSqrAttenuationRadius);
return QuadraticAttenuation(smoothFactor);
real smoothFactor = InfluenceAttenuation(distSquare, invSqrAttenuationRadius);
return Sq(smoothFactor);
real SmoothQuadraticDistanceAttenuation(real distSq, real distRcp, real invSqrAttenuationRadius)
// Return physically based quadratic attenuation + influence limit to reach 0 at attenuationRadius
real SmoothQuadraticDistanceAttenuation(real distSquare, real distRcp, real invSqrAttenuationRadius)
// Becomes quadratic after the call to QuadraticAttenuation().
// Becomes quadratic after the call to Sq().
attenuation *= DistanceAttenuation(distSq, invSqrAttenuationRadius);
return QuadraticAttenuation(attenuation);
attenuation *= InfluenceAttenuation(distSquare, invSqrAttenuationRadius);
return Sq(attenuation);
real distSq = dot(unL, unL);
real distRcp = rsqrt(distSq);
return SmoothQuadraticDistanceAttenuation(distSq, distRcp, invSqrAttenuationRadius);
real distSquare = dot(unL, unL);
real distRcp = rsqrt(distSquare);
return SmoothQuadraticDistanceAttenuation(distSquare, distRcp, invSqrAttenuationRadius);
}
real AngleAttenuation(real cosFwd, real lightAngleScale, real lightAngleOffset)

real SmoothAngleAttenuation(real cosFwd, real lightAngleScale, real lightAngleOffset)
{
real attenuation = AngleAttenuation(cosFwd, lightAngleScale, lightAngleOffset);
return QuadraticAttenuation(attenuation);
return Sq(attenuation);
}
real SmoothAngleAttenuation(real3 L, real3 lightFwdDir, real lightAngleScale, real lightAngleOffset)

real cosFwd = distProj * distRcp;
real attenuation = min(distRcp, 1.0 / PUNCTUAL_LIGHT_THRESHOLD);
attenuation *= DistanceAttenuation(distSq, invSqrAttenuationRadius);
attenuation *= InfluenceAttenuation(distSq, invSqrAttenuationRadius);
return QuadraticAttenuation(attenuation);
return Sq(attenuation);
// Applies SmoothDistanceAttenuation() after transforming the attenuation ellipsoid into a sphere.
// Applies SmoothInfluenceAttenuation() after transforming the attenuation ellipsoid into a sphere.
// If r = rsqrt(invSqRadius), then the ellipsoid is defined s.t. r1 = r / invAspectRatio, r2 = r3 = r.
// The transformation is performed along the major axis of the ellipsoid (corresponding to 'r1').
// Both the ellipsoid (e.i. 'axis') and 'unL' should be in the same coordinate system.

unL -= diff * axis;
real sqDist = dot(unL, unL);
return SmoothDistanceAttenuation(sqDist, invSqRadius);
return SmoothInfluenceAttenuation(sqDist, invSqRadius);
// Applies SmoothDistanceAttenuation() using the axis-aligned ellipsoid of the given dimensions.
// Applies SmoothInfluenceAttenuation() using the axis-aligned ellipsoid of the given dimensions.
// Both the ellipsoid and 'unL' should be in the same coordinate system.
// 'unL' should be computed from the center of the ellipsoid.
real EllipsoidalDistanceAttenuation(real3 unL, real3 invHalfDim)

unL *= invHalfDim;
real sqDist = dot(unL, unL);
return SmoothDistanceAttenuation(sqDist, 1.0);
return SmoothInfluenceAttenuation(sqDist, 1.0);
// Applies SmoothDistanceAttenuation() after mapping the axis-aligned box to a sphere.
// Applies SmoothInfluenceAttenuation() after mapping the axis-aligned box to a sphere.
// If the diagonal of the box is 'd', invHalfDim = rcp(0.5 * d).
// Both the box and 'unL' should be in the same coordinate system.
// 'unL' should be computed from the center of the box.

if (Max3(abs(unL.x), abs(unL.y), abs(unL.z)) > 1.0) return 0.0;
real sqDist = ComputeCubeToSphereMapSqMagnitude(unL);
return SmoothDistanceAttenuation(sqDist, 1.0);
return SmoothInfluenceAttenuation(sqDist, 1.0);
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Helper functions
//-----------------------------------------------------------------------------
// Ref: "Crafting a Next-Gen Material Pipeline for The Order: 1886".
float ClampNdotV(float NdotV)
{
return max(NdotV, 0.0001);
}
// Inputs: normalized normal and view vectors.
// Outputs: front-facing normal, and the new non-negative value of the cosine of the view angle.

18
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/Debug.hlsl


return GetDebugMipColor(originalColor, tex, texelSize, uv);
}
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
float3 outColor = float3(1.0, 0.0, 1.0); // Can't calculate without original mip count - return magenta
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
return float3(0, mipCol, 0);
outColor = float3(0, mipCol, 0);
// Can't calculate without original mip count - return magenta
return float3(1.0, 0.0, 1.0);
return outColor;
}
// Convert an arbitrary range to color base on threshold provide to the function, threshold must be in growing order

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


// Ref: Listing 18 in "Moving Frostbite to PBR" + https://knarkowicz.wordpress.com/2014/12/27/analytical-dfg-term-for-ibl/
real4 IntegrateGGXAndDisneyFGD(real3 V, real3 N, real roughness, uint sampleCount = 8192)
{
real NdotV = saturate(dot(N, V));
real NdotV = ClampNdotV(dot(N, V));
real4 acc = real4(0.0, 0.0, 0.0, 0.0);
// Add some jittering on Hammersley2d
real2 randNum = InitRandom(V.xy * 0.5 + 0.5);

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


#define SHADOW_OPTIMIZE_REGISTER_USAGE 0
#endif
#if SHADOW_OPTIMIZE_REGISTER_USAGE == 1
# pragma warning(disable : 3557) // loop only executes for 1 iteration(s)
#endif
#include "CoreRP/Shadow/ShadowBase.cs.hlsl" // ShadowData definition, auto generated (don't modify)
#include "ShadowTexFetch.hlsl" // Resource sampling definitions (don't modify)

7
ScriptableRenderPipeline/Core/CoreRP/ShaderLibrary/VolumeRendering.hlsl


real x = 1 - exp(-extinction * intervalLength);
// Avoid division by 0.
real rcpExt = (extinction != 0) ? rcp(extinction) : 0;
weight = x * rcpExt;
offset = -log(1 - rndVal * x) * rcpExt;
weight = x * rcp(extinction);
offset = -log(1 - rndVal * x) * rcp(extinction);
}
// Implements equiangular light sampling.

1
ScriptableRenderPipeline/Core/CoreRP/Shadow/Shadow.cs


m_Shadowmap.hideFlags = HideFlags.DontSaveInEditor | HideFlags.DontSaveInBuild;
m_Shadowmap.dimension = TextureDimension.Tex2DArray;
m_Shadowmap.volumeDepth = (int) m_Slices;
m_Shadowmap.name = CoreUtils.GetRenderTargetAutoName(shadowmap.width, shadowmap.height, shadowmap.format, "Shadow", mips : shadowmap.useMipMap);
m_ShadowmapId = new RenderTargetIdentifier( m_Shadowmap );
}

2
ScriptableRenderPipeline/Core/CoreRP/TextureCache.cs


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

for (int m = 0; m < m_NumPanoMipLevels; m++)
{
m_StagingRTs[m] = new RenderTexture(Mathf.Max(1, panoWidthTop >> m), Mathf.Max(1, panoHeightTop >> m), 0, RenderTextureFormat.ARGBHalf) { hideFlags = HideFlags.HideAndDontSave };
m_StagingRTs[m].name = CoreUtils.GetRenderTargetAutoName(Mathf.Max(1, panoWidthTop >> m), Mathf.Max(1, panoHeightTop >> m), RenderTextureFormat.ARGBHalf, String.Format("PanaCache{0}", m));
}
if (m_CubeBlitMaterial)

2
ScriptableRenderPipeline/Core/package.json


{
"name": "com.unity.render-pipelines.core",
"description": "Core library for Unity render pipelines.",
"version": "0.1.28",
"version": "0.1.29",
"unity": "2018.1",
"dependencies": {
"com.unity.postprocessing": "0.1.8"

106
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCamera.cs


public Vector4 viewParam;
public PostProcessRenderContext postprocessRenderContext;
public Matrix4x4[] viewMatrixStereo;
public Matrix4x4[] projMatrixStereo;
// Non oblique projection matrix (RHS)
public Matrix4x4 nonObliqueProjMatrix
{

}
}
// This is the size actually used for this camera (as it can be altered by VR for example)
int m_ActualWidth;
int m_ActualHeight;
// This is the scale and bias of the camera viewport compared to the reference size of our Render Targets (RHandle.maxSize)
Vector2 m_CameraScaleBias;
// Current mssa sample
MSAASamples m_msaaSamples;
public int actualWidth { get { return m_ActualWidth; } }
public int actualHeight { get { return m_ActualHeight; } }
public Vector2 scaleBias { get { return m_CameraScaleBias; } }
public MSAASamples msaaSamples { get { return m_msaaSamples; } }
public Matrix4x4 viewProjMatrix
{
get { return projMatrix * viewMatrix; }

get { return nonJitteredProjMatrix * viewMatrix; }
}
public RenderTextureDescriptor renderTextureDesc { get; private set; }
public Matrix4x4 GetViewProjMatrixStereo(uint eyeIndex)
{
return (projMatrixStereo[eyeIndex] * viewMatrixStereo[eyeIndex]);
}
// Always true for cameras that just got added to the pool - needed for previous matrices to
// avoid one-frame jumps/hiccups with temporal effects (motion blur, TAA...)

camera = cam;
frustumPlanes = new Plane[6];
frustumPlaneEquations = new Vector4[6];
viewMatrixStereo = new Matrix4x4[2];
projMatrixStereo = new Matrix4x4[2];
postprocessRenderContext = new PostProcessRenderContext();
m_AdditionalCameraData = cam.GetComponent<HDAdditionalCameraData>();
Reset();

m_LastFrameActive = Time.frameCount;
RenderTextureDescriptor tempDesc;
m_ActualWidth = camera.pixelWidth;
m_ActualHeight = camera.pixelHeight;
var screenWidth = m_ActualWidth;
var screenHeight = m_ActualHeight;
screenSize = new Vector4(XRSettings.eyeTextureWidth, XRSettings.eyeTextureHeight, 1.0f / XRSettings.eyeTextureWidth, 1.0f / XRSettings.eyeTextureHeight);
tempDesc = XRSettings.eyeTextureDesc;
}
else
{
screenSize = new Vector4(camera.pixelWidth, camera.pixelHeight, 1.0f / camera.pixelWidth, 1.0f / camera.pixelHeight);
tempDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
}
screenWidth = XRSettings.eyeTextureWidth;
screenHeight = XRSettings.eyeTextureHeight;
if (frameSettings.enableMSAA)
{
// this is already pre-validated to be a valid sample count by InitializeFrameSettings
var sampleCount = QualitySettings.antiAliasing;
tempDesc.msaaSamples = sampleCount;
var xrDesc = XRSettings.eyeTextureDesc;
m_ActualWidth = xrDesc.width;
m_ActualHeight = xrDesc.height;
ConfigureStereoMatrices();
else
// Unfortunately sometime (like in the HDCameraEditor) HDUtils.hdrpSettings can be null because of scripts that change the current pipeline...
m_msaaSamples = HDUtils.hdrpSettings != null ? HDUtils.hdrpSettings.msaaSampleCount : MSAASamples.None;
RTHandle.SetReferenceSize(m_ActualWidth, m_ActualHeight, frameSettings.enableMSAA, m_msaaSamples);
int maxWidth = RTHandle.maxWidth;
int maxHeight = RTHandle.maxHeight;
m_CameraScaleBias.x = (float)m_ActualWidth / maxWidth;
m_CameraScaleBias.y = (float)m_ActualHeight / maxHeight;
screenSize = new Vector4(screenWidth, screenHeight, 1.0f / screenWidth, 1.0f / screenHeight);
}
void ConfigureStereoMatrices()
{
for (uint eyeIndex = 0; eyeIndex < 2; eyeIndex++)
tempDesc.msaaSamples = 1;
viewMatrixStereo[eyeIndex] = camera.GetStereoViewMatrix((Camera.StereoscopicEye)eyeIndex);
projMatrixStereo[eyeIndex] = camera.GetStereoProjectionMatrix((Camera.StereoscopicEye)eyeIndex);
projMatrixStereo[eyeIndex] = GL.GetGPUProjectionMatrix(projMatrixStereo[eyeIndex], true);
tempDesc.depthBufferBits = 0;
tempDesc.autoGenerateMips = false;
tempDesc.useMipMap = false;
tempDesc.enableRandomWrite = false;
tempDesc.memoryless = RenderTextureMemoryless.None;
renderTextureDesc = tempDesc;
// TODO: Fetch the single cull matrix stuff
public int GetViewID()
public long GetViewID()
int viewID = camera.GetInstanceID();
long viewID = camera.GetInstanceID();
// Make it positive.
viewID += (-(long)int.MinValue) + 1;
Debug.Assert(viewID > 0);
return viewID;
}

cmd.SetGlobalVector(HDShaderIDs._ViewParam, viewParam);
cmd.SetGlobalVector(HDShaderIDs._InvProjParam, invProjParam);
cmd.SetGlobalVector(HDShaderIDs._ScreenSize, screenSize);
cmd.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, scaleBias);
}
public void SetupGlobalStereoParams(CommandBuffer cmd)
{
var invProjStereo = new Matrix4x4[2];
var invViewProjStereo = new Matrix4x4[2];
for (uint eyeIndex = 0; eyeIndex < 2; eyeIndex++)
{
var proj = projMatrixStereo[eyeIndex];
invProjStereo[eyeIndex] = proj.inverse;
var vp = proj * viewMatrixStereo[eyeIndex];
invViewProjStereo[eyeIndex] = vp.inverse;
}
// corresponds to UnityPerPassStereo
// TODO: Migrate the other stereo matrices to HDRP-managed UnityPerPassStereo?
cmd.SetGlobalMatrixArray(HDShaderIDs._InvProjMatrixStereo, invProjStereo);
cmd.SetGlobalMatrixArray(HDShaderIDs._InvViewProjMatrixStereo, invViewProjStereo);
}
// TODO: We should set all the value below globally and not let it under the control of Unity,

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


{
Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
output.texcoord = GetFullScreenTriangleTexCoord(input.vertexID);
output.texcoord = GetNormalizedFullScreenTriangleTexCoord(input.vertexID);
return output;
}

{
if (_RequireToFlipInputTexture > 0.0)
{
input.texcoord.y = 1.0 - input.texcoord.y;
input.texcoord.y = 1.0 * _ScreenToTargetScale.y - input.texcoord.y;
}
float4 result = SAMPLE_TEXTURE2D(_DebugColorPickerTexture, sampler_DebugColorPickerTexture, input.texcoord);

63
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/DebugDisplay.cs


public float debugOverlayRatio = 0.33f;
public FullScreenDebugMode fullScreenDebugMode = FullScreenDebugMode.None;
public float fullscreenDebugMip = 0;
public float fullscreenDebugMip = 0.0f;
public MaterialDebugSettings materialDebugSettings = new MaterialDebugSettings();
public LightingDebugSettings lightingDebugSettings = new LightingDebugSettings();

DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, float>(kShadowMinValueDebug, () => lightingDebugSettings.shadowMinValue, (value) => lightingDebugSettings.shadowMinValue = (float)value);
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, float>(kShadowMaxValueDebug, () => lightingDebugSettings.shadowMaxValue, (value) => lightingDebugSettings.shadowMaxValue = (float)value);
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, int>(kFullScreenDebugMode, () => (int)fullScreenDebugMode, (value) => fullScreenDebugMode = (FullScreenDebugMode)value, DebugItemFlag.None, new DebugItemHandlerIntEnum(DebugDisplaySettings.lightingFullScreenDebugStrings, DebugDisplaySettings.lightingFullScreenDebugValues));
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, float>(kFullScreenDebugMip, () => fullscreenDebugMip, value => fullscreenDebugMip = (float)value, DebugItemFlag.None, new DebugItemHandlerFloatMinMax(0f, 1f));
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, uint>(
kFullScreenDebugMip,
() =>
{
var id = 0;
switch (fullScreenDebugMode)
{
default:
case FullScreenDebugMode.DepthPyramid:
id = HDShaderIDs._DepthPyramidMipSize;
break;
case FullScreenDebugMode.FinalColorPyramid:
case FullScreenDebugMode.PreRefractionColorPyramid:
id = HDShaderIDs._GaussianPyramidColorMipSize;
break;
}
var size = Shader.GetGlobalVector(id);
var lodCount = size.z;
return (uint)(fullscreenDebugMip * lodCount);
},
value =>
{
var id = 0;
switch (fullScreenDebugMode)
{
default:
case FullScreenDebugMode.DepthPyramid:
id = HDShaderIDs._DepthPyramidMipSize;
break;
case FullScreenDebugMode.FinalColorPyramid:
case FullScreenDebugMode.PreRefractionColorPyramid:
id = HDShaderIDs._GaussianPyramidColorMipSize;
break;
}
var size = Shader.GetGlobalVector(id);
var lodCount = size.z;
fullscreenDebugMip = (float)Convert.ChangeType(value, typeof(Single)) / lodCount;
},
DebugItemFlag.None,
new DebugItemHandlerUIntMinMax(() => 0,
() =>
{
var id = 0;
switch (fullScreenDebugMode)
{
default:
case FullScreenDebugMode.DepthPyramid:
id = HDShaderIDs._DepthPyramidMipSize;
break;
case FullScreenDebugMode.FinalColorPyramid:
case FullScreenDebugMode.PreRefractionColorPyramid:
id = HDShaderIDs._GaussianPyramidColorMipSize;
break;
}
var size = Shader.GetGlobalVector(id);
var lodCount = size.z;
return (uint)lodCount;
})
);
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, DebugLightingMode>(kLightingDebugMode, () => lightingDebugSettings.debugLightingMode, (value) => SetDebugLightingMode((DebugLightingMode)value));
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, bool>(kOverrideSmoothnessDebug, () => lightingDebugSettings.overrideSmoothness, (value) => lightingDebugSettings.overrideSmoothness = (bool)value);
DebugMenuManager.instance.AddDebugItem<LightingDebugPanel, float>(kOverrideSmoothnessValueDebug, () => lightingDebugSettings.overrideSmoothnessValue, (value) => lightingDebugSettings.overrideSmoothnessValue = (float)value, DebugItemFlag.None, new DebugItemHandlerFloatMinMax(0.0f, 1.0f));

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


float3 GetTextureDataDebug(uint paramId, float2 uv, Texture2D tex, float4 texelSize, float4 mipInfo, float3 originalColor)
{
float3 outColor = originalColor;
return GetDebugMipColorIncludingMipReduction(originalColor, tex, texelSize, uv, mipInfo);
outColor = GetDebugMipColorIncludingMipReduction(originalColor, tex, texelSize, uv, mipInfo);
break;
return GetDebugMipCountColor(originalColor, tex);
outColor = GetDebugMipCountColor(originalColor, tex);
break;
return GetDebugMipReductionColor(tex, mipInfo);
outColor = GetDebugMipReductionColor(tex, mipInfo);
break;
return GetDebugStreamingMipColor(tex, mipInfo);
outColor = GetDebugStreamingMipColor(tex, mipInfo);
break;
return GetDebugStreamingMipColorBlended(originalColor, tex, mipInfo);
outColor = GetDebugStreamingMipColorBlended(originalColor, tex, mipInfo);
break;
return originalColor;
return outColor;
}
// DebugFont code assume black and white font with texture size 256x128 with bloc of 16x16

// Draw a signed integer
// Can't display more than 16 digit
void DrawInteger(int intValue, float3 fontColor, uint2 currentUnormCoord, inout uint2 fixedUnormCoord, bool flipY, inout float3 color)
// The two following parameter are for float representation
// leading0 is used when drawing frac part of a float to draw the leading 0 (call is in charge of it)
// forceNegativeSign is used to force to display a negative sign as -0 is not recognize
void DrawInteger(int intValue, float3 fontColor, uint2 currentUnormCoord, inout uint2 fixedUnormCoord, bool flipY, inout float3 color, int leading0, bool forceNegativeSign)
int absIntValue = abs(intValue);
uint absIntValue = abs(intValue);
int numEntries = min((intValue == 0 ? 0 : log10(absIntValue)) + (intValue < 0 ? 1 : 0), maxStringSize);
int numEntries = min((intValue == 0 ? 0 : log10(absIntValue)) + ((intValue < 0 || forceNegativeSign) ? 1 : 0) + leading0, maxStringSize);
for (uint i = 0; i < maxStringSize; ++i)
for (uint j = 0; j < maxStringSize; ++j)
{
// Numeric value incurrent font start on the second row at 0
DrawCharacter((absIntValue % 10) + '0', fontColor, currentUnormCoord, fixedUnormCoord, flipY, color, -1);

}
// 4. Display sign
if (intValue < 0)
// 4. Display leading 0
for (int i = 0; i < leading0; ++i)
{
DrawCharacter('0', fontColor, currentUnormCoord, fixedUnormCoord, flipY, color, -1);
}
// 5. Display sign
if (intValue < 0 || forceNegativeSign)
// 5. Reset cursor at end location
// 6. Reset cursor at end location
void DrawInteger(int intValue, float3 fontColor, uint2 currentUnormCoord, inout uint2 fixedUnormCoord, bool flipY, inout float3 color)
{
DrawInteger(intValue, fontColor, currentUnormCoord, fixedUnormCoord, flipY, color, 0, false);
}
if (IsNAN(floatValue))
if (IsNan(floatValue))
{
DrawCharacter('N', fontColor, currentUnormCoord, fixedUnormCoord, flipY, color);
DrawCharacter('a', fontColor, currentUnormCoord, fixedUnormCoord, flipY, color);

{
int intValue = int(floatValue);
DrawInteger(intValue, fontColor, currentUnormCoord, fixedUnormCoord, flipY, color);
bool forceNegativeSign = floatValue >= 0.0f ? false : true;
DrawInteger(intValue, fontColor, currentUnormCoord, fixedUnormCoord, flipY, color, 0, forceNegativeSign);
int fracValue = int(frac(floatValue) * 1e6); // 6 digit
DrawInteger(fracValue, fontColor, currentUnormCoord, fixedUnormCoord, flipY, color);
int fracValue = int(frac(abs(floatValue)) * 1e6); // 6 digit
int leading0 = 6 - (int(log10(fracValue)) + 1); // Counting leading0 to add in front of the float
DrawInteger(fracValue, fontColor, currentUnormCoord, fixedUnormCoord, flipY, color, leading0, false);
}
}

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


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

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


#include "../Debug/DebugDisplay.cs.hlsl"
TEXTURE2D(_DebugFullScreenTexture);
SAMPLER(sampler_DebugFullScreenTexture);
float _FullScreenDebugMode;
float _RequireToFlipInputTexture;

{
Varyings output;
output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
output.texcoord = GetFullScreenTriangleTexCoord(input.vertexID);
output.texcoord = GetNormalizedFullScreenTriangleTexCoord(input.vertexID);
return output;
}

float2 SampleMotionVectors(float2 coords)
{
return SAMPLE_TEXTURE2D(_DebugFullScreenTexture, sampler_DebugFullScreenTexture, coords).xy;
return SAMPLE_TEXTURE2D(_DebugFullScreenTexture, s_point_clamp_sampler, coords).xy;
}
// end motion vector utilties

{
input.texcoord.y = 1.0 - input.texcoord.y;
// Texcoord are already scaled by _ScreenToTargetScale but we need to account for the flip here anyway.
input.texcoord.y = 1.0 * _ScreenToTargetScale.y - input.texcoord.y;
return 1.0f - SAMPLE_TEXTURE2D(_DebugFullScreenTexture, sampler_DebugFullScreenTexture, input.texcoord).xxxx;
return 1.0f - SAMPLE_TEXTURE2D(_DebugFullScreenTexture, s_point_clamp_sampler, input.texcoord).xxxx;
float4 color = SAMPLE_TEXTURE2D(_DebugFullScreenTexture, sampler_DebugFullScreenTexture, input.texcoord);
float4 color = SAMPLE_TEXTURE2D(_DebugFullScreenTexture, s_point_clamp_sampler, input.texcoord);
if (IsNAN(color) || any(isinf(color)))
if (AnyIsNan(color) || any(isinf(color)))
{
color = float4(1.0, 0.0, 0.0, 1.0);
}

{
arrow_coord.y = 1.0 - arrow_coord.y;
}
arrow_coord *= _ScreenToTargetScale.xy;
float2 mv_arrow = SampleMotionVectors(arrow_coord);

}
if (_FullScreenDebugMode == FULLSCREENDEBUGMODE_DEFERRED_SHADOWS)
{
float4 color = SAMPLE_TEXTURE2D(_DebugFullScreenTexture, sampler_DebugFullScreenTexture, input.texcoord);
return float4(color.rgb, 0.0);
float4 color = SAMPLE_TEXTURE2D(_DebugFullScreenTexture, s_point_clamp_sampler, input.texcoord);
return float4(color.rrr, 0.0);
float4 color = SAMPLE_TEXTURE2D(_DebugFullScreenTexture, sampler_DebugFullScreenTexture, input.texcoord);
float4 color = SAMPLE_TEXTURE2D(_DebugFullScreenTexture, s_point_clamp_sampler, input.texcoord);
float4 color = SAMPLE_TEXTURE2D(_DebugFullScreenTexture, sampler_DebugFullScreenTexture, input.texcoord);
return float4(color.rrr / (color.rrr + 1), 1.0);
// Reuse depth display function from DebugViewMaterial
float depth = SAMPLE_TEXTURE2D(_DebugFullScreenTexture, s_point_clamp_sampler, input.texcoord).r;
PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_VP);
float linearDepth = frac(posInput.linearDepth * 0.1);
return float4(linearDepth.xxx, 1.0);
}
return float4(0.0, 0.0, 0.0, 0.0);

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/LightingDebugPanel.cs


break;
}
default:
fullScreenDebugMipHandler.SetValue(0f);
fullScreenDebugMipHandler.SetValue(0);
break;
}

117
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Debug/MaterialDebug.cs


}
// className include the additional "/"
void FillWithProperties(Type type, GUIContent[] debugViewMaterialStrings, int[] debugViewMaterialValues, string className, ref int index)
void FillWithProperties(Type type, ref List<GUIContent> debugViewMaterialStringsList, ref List<int> debugViewMaterialValuesList, string className)
{
var attributes = type.GetCustomAttributes(true);
// Get attribute to get the start number of the value for the enum

var localIndex = 0;
foreach (var field in fields)
{
var fieldName = field.Name;
// Note: One field can have multiple name. This is to allow to have different debug view mode for the same field
// like for example display normal in world space or in view space. Same field but two different modes.
List<String> displayNames = new List<string>();
displayNames.Add(field.Name);
if (propertyAttr[0].displayName != "")
if (propertyAttr[0].displayNames.Length > 0 && propertyAttr[0].displayNames[0] != "")
fieldName = propertyAttr[0].displayName;
displayNames.Clear();
displayNames.AddRange(propertyAttr[0].displayNames);
fieldName = className + fieldName;
debugViewMaterialStrings[index] = new GUIContent(fieldName);
debugViewMaterialValues[index] = attr.paramDefinesStart + (int)localIndex;
index++;
localIndex++;
foreach (string fieldName in displayNames)
{
debugViewMaterialStringsList.Add(new GUIContent(className + fieldName));
debugViewMaterialValuesList.Add(attr.paramDefinesStart + (int)localIndex);
localIndex++;
}
void FillWithPropertiesEnum(Type type, GUIContent[] debugViewMaterialStrings, int[] debugViewMaterialValues, string prefix, ref int index)
void FillWithPropertiesEnum(Type type, ref List<GUIContent> debugViewMaterialStringsList, ref List<int> debugViewMaterialValuesList, string prefix)
{
var names = Enum.GetNames(type);

var valueName = prefix + names[localIndex];
debugViewMaterialStrings[index] = new GUIContent(valueName);
debugViewMaterialValues[index] = (int)value;
index++;
debugViewMaterialStringsList.Add(new GUIContent(valueName));
debugViewMaterialValuesList.Add((int)value);
localIndex++;
}
}

materialItems.Add(item);
}
// Material properties debug
var num = typeof(Builtin.BuiltinData).GetFields().Length * materialList.Count // BuildtinData are duplicated for each material
+ numSurfaceDataFields + 1; // +1 for None case
// Init list
List<GUIContent> debugViewMaterialStringsList = new List<GUIContent>();
List<int> debugViewMaterialValuesList = new List<int>();
List<GUIContent> debugViewEngineStringsList = new List<GUIContent>();
List<int> debugViewEngineValuesList = new List<int>();
List<GUIContent> debugViewMaterialVaryingStringsList = new List<GUIContent>();
List<int> debugViewMaterialVaryingValuesList = new List<int>();
List<GUIContent> debugViewMaterialPropertiesStringsList = new List<GUIContent>();
List<int> debugViewMaterialPropertiesValuesList = new List<int>();
List<GUIContent> debugViewMaterialTextureStringsList = new List<GUIContent>();
List<int> debugViewMaterialTextureValuesList = new List<int>();
List<GUIContent> debugViewMaterialGBufferStringsList = new List<GUIContent>();
List<int> debugViewMaterialGBufferValuesList = new List<int>();
debugViewMaterialStrings = new GUIContent[num];
debugViewMaterialValues = new int[num];
// First element is a reserved location and should not be used (allow to track error)
debugViewMaterialStrings[0] = new GUIContent("None");
debugViewMaterialValues[0] = 0;
var index = 1;
// 0 is a reserved number and should not be used (allow to track error)
debugViewMaterialStringsList.Add(new GUIContent("None"));
debugViewMaterialValuesList.Add(0);
FillWithProperties(typeof(Builtin.BuiltinData), debugViewMaterialStrings, debugViewMaterialValues, item.className, ref index);
FillWithProperties(item.surfaceDataType, debugViewMaterialStrings, debugViewMaterialValues, item.className, ref index);
FillWithProperties(typeof(Builtin.BuiltinData), ref debugViewMaterialStringsList, ref debugViewMaterialValuesList, item.className);
FillWithProperties(item.surfaceDataType, ref debugViewMaterialStringsList, ref debugViewMaterialValuesList, item.className);
num = numBSDFDataFields + 1; // +1 for None case
debugViewEngineStrings = new GUIContent[num];
debugViewEngineValues = new int[num];
// 0 is a reserved number and should not be used (allow to track error)
debugViewEngineStrings[0] = new GUIContent("None");
debugViewEngineValues[0] = 0;
index = 1;
// First element is a reserved location and should not be used (allow to track error)
// Special case for None since it cannot be inferred from SurfaceData/BuiltinData
debugViewEngineStringsList.Add(new GUIContent("None"));
debugViewEngineValuesList.Add(0);
FillWithProperties(item.bsdfDataType, debugViewEngineStrings, debugViewEngineValues, item.className, ref index);
FillWithProperties(item.bsdfDataType, ref debugViewEngineStringsList, ref debugViewEngineValuesList, item.className);
// For the following, no need to reserve the 0 case as it is handled in the Enum
var varyingNames = Enum.GetNames(typeof(Attributes.DebugViewVarying));
debugViewMaterialVaryingStrings = new GUIContent[varyingNames.Length];
debugViewMaterialVaryingValues = new int[varyingNames.Length];
index = 0;
FillWithPropertiesEnum(typeof(Attributes.DebugViewVarying), debugViewMaterialVaryingStrings, debugViewMaterialVaryingValues, "", ref index);
FillWithPropertiesEnum(typeof(Attributes.DebugViewVarying), ref debugViewMaterialVaryingStringsList, ref debugViewMaterialVaryingValuesList, "");
var propertiesNames = Enum.GetNames(typeof(Attributes.DebugViewProperties));
debugViewMaterialPropertiesStrings = new GUIContent[propertiesNames.Length];
debugViewMaterialPropertiesValues = new int[propertiesNames.Length];
index = 0;
FillWithPropertiesEnum(typeof(Attributes.DebugViewProperties), debugViewMaterialPropertiesStrings, debugViewMaterialPropertiesValues, "", ref index);
FillWithPropertiesEnum(typeof(Attributes.DebugViewProperties), ref debugViewMaterialPropertiesStringsList, ref debugViewMaterialPropertiesValuesList, "");
var gbufferNames = Enum.GetNames(typeof(Attributes.DebugViewGbuffer));
debugViewMaterialGBufferStrings = new GUIContent[gbufferNames.Length + bsdfDataDeferredType.GetFields().Length];
debugViewMaterialGBufferValues = new int[gbufferNames.Length + bsdfDataDeferredType.GetFields().Length];
index = 0;
FillWithPropertiesEnum(typeof(Attributes.DebugViewGbuffer), debugViewMaterialGBufferStrings, debugViewMaterialGBufferValues, "", ref index);
FillWithProperties(typeof(Lit.BSDFData), debugViewMaterialGBufferStrings, debugViewMaterialGBufferValues, "", ref index);
FillWithPropertiesEnum(typeof(Attributes.DebugViewGbuffer), ref debugViewMaterialGBufferStringsList, ref debugViewMaterialGBufferValuesList, "");
FillWithProperties(typeof(Lit.BSDFData), ref debugViewMaterialGBufferStringsList, ref debugViewMaterialGBufferValuesList, "");
// Convert to array for UI
debugViewMaterialStrings = debugViewMaterialStringsList.ToArray();
debugViewMaterialValues = debugViewMaterialValuesList.ToArray();
debugViewEngineStrings = debugViewEngineStringsList.ToArray();
debugViewEngineValues = debugViewEngineValuesList.ToArray();
debugViewMaterialVaryingStrings = debugViewMaterialVaryingStringsList.ToArray();
debugViewMaterialVaryingValues = debugViewMaterialVaryingValuesList.ToArray();
debugViewMaterialPropertiesStrings = debugViewMaterialPropertiesStringsList.ToArray();
debugViewMaterialPropertiesValues = debugViewMaterialPropertiesValuesList.ToArray();
debugViewMaterialTextureStrings = debugViewMaterialTextureStringsList.ToArray();
debugViewMaterialTextureValues = debugViewMaterialTextureValuesList.ToArray();
debugViewMaterialGBufferStrings = debugViewMaterialGBufferStringsList.ToArray();
debugViewMaterialGBufferValues = debugViewMaterialGBufferValuesList.ToArray();
isDebugViewMaterialInit = true;
}

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalProjectorComponent.cs


public class DecalProjectorComponent : MonoBehaviour
{
public Material m_Material = null;
public float m_DrawDistance = 1000.0f;
public float m_FadeScale = 0.9f;
private Material m_OldMaterial = null;
public const int kInvalidIndex = -1;
private int m_CullIndex = kInvalidIndex;

{
DrawGizmo(true);
// if this object is selected there is a chance the transform was changed so update culling info
DecalSystem.instance.UpdateBoundingSphere(this);
DecalSystem.instance.UpdateCachedData(this);
}
public void OnDrawGizmos()

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


}
}
private const int kDefaultDrawDistance = 1000;
static public int DrawDistance
{
get
{
HDRenderPipelineAsset hdrp = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;
if (hdrp != null)
{
return hdrp.renderPipelineSettings.decalSettings.drawDistance;
}
return kDefaultDrawDistance;
}
}
private static readonly int m_NormalToWorldID = Shader.PropertyToID("normalToWorld");
private static MaterialPropertyBlock m_PropertyBlock = new MaterialPropertyBlock();

static public Mesh m_DecalMesh = null;
static public Matrix4x4[] m_InstanceMatrices = new Matrix4x4[kDrawIndexedBatchSize];
static public Matrix4x4[] m_InstanceNormalToWorld = new Matrix4x4[kDrawIndexedBatchSize];
static public float[] m_BoundingDistances = new float[1];
private Dictionary<int, DecalSet> m_DecalSets = new Dictionary<int, DecalSet>();

return res;
}
public void UpdateBoundingSphere(DecalProjectorComponent decal)
public void UpdateCachedData(DecalProjectorComponent decal)
{
m_CachedTransforms[decal.CullIndex] = decal.transform.localToWorldMatrix;

decalRotation.m22 = y2;
m_CachedNormalToWorld[decal.CullIndex] = decalRotation;
// draw distance can't be more than global draw distance
m_CachedDrawDistances[decal.CullIndex].x = decal.m_DrawDistance < DrawDistance ? decal.m_DrawDistance : DrawDistance;
m_CachedDrawDistances[decal.CullIndex].y = decal.m_FadeScale;
m_BoundingSpheres[decal.CullIndex] = GetDecalProjectBoundingSphere(m_CachedTransforms[decal.CullIndex]);
}

BoundingSphere[] newSpheres = new BoundingSphere[m_DecalsCount + kDecalBlockSize];
Matrix4x4[] newCachedTransforms = new Matrix4x4[m_DecalsCount + kDecalBlockSize];
Matrix4x4[] newCachedNormalToWorld = new Matrix4x4[m_DecalsCount + kDecalBlockSize];
Vector2[] newCachedDrawDistances = new Vector2[m_DecalsCount + kDecalBlockSize];
m_ResultIndices = new int[m_DecalsCount + kDecalBlockSize];
m_Decals.CopyTo(newDecals, 0);

m_CachedDrawDistances.CopyTo(newCachedDrawDistances, 0);
m_CachedDrawDistances = newCachedDrawDistances;
UpdateBoundingSphere(m_Decals[m_DecalsCount]);
UpdateCachedData(m_Decals[m_DecalsCount]);
m_DecalsCount++;
}

m_BoundingSpheres[removeAtIndex] = m_BoundingSpheres[m_DecalsCount - 1];
m_CachedTransforms[removeAtIndex] = m_CachedTransforms[m_DecalsCount - 1];
m_CachedNormalToWorld[removeAtIndex] = m_CachedNormalToWorld[m_DecalsCount - 1];
m_CachedDrawDistances[removeAtIndex] = m_CachedDrawDistances[m_DecalsCount - 1];
m_DecalsCount--;
decal.CullIndex = DecalProjectorComponent.kInvalidIndex;
}

{
Debug.LogError("Begin/EndCull() called out of sequence for decal projectors.");
}
// let the culling group code do some of the heavy lifting for global draw distance
m_BoundingDistances[0] = DrawDistance;
m_CullingGroup.SetDistanceReferencePoint(camera.transform.position);
m_CullingGroup.SetBoundingDistances(m_BoundingDistances);
m_CullingGroup.SetBoundingSpheres(m_BoundingSpheres);
m_CullingGroup.SetBoundingSphereCount(m_DecalsCount);
}

public void Render(ScriptableRenderContext renderContext, HDCamera camera, CommandBuffer cmd)
{
int instanceCount = 0;
Vector3 cameraPos = camera.cameraPos;
m_InstanceMatrices[instanceCount] = m_CachedTransforms[decalIndex];
m_InstanceNormalToWorld[instanceCount] = m_CachedNormalToWorld[decalIndex];
instanceCount++;
if (instanceCount == kDrawIndexedBatchSize)
{
m_PropertyBlock.SetMatrixArray(m_NormalToWorldID, m_InstanceNormalToWorld);
cmd.DrawMeshInstanced(m_DecalMesh, 0, KeyMaterial, 0, m_InstanceMatrices, kDrawIndexedBatchSize, m_PropertyBlock);
instanceCount = 0;
}
// do additional culling based on individual decal draw distances
float distanceToDecal = (cameraPos - m_BoundingSpheres[decalIndex].position).magnitude;
float cullDistance = m_CachedDrawDistances[decalIndex].x + m_BoundingSpheres[decalIndex].radius;
if (distanceToDecal < cullDistance)
{
m_InstanceMatrices[instanceCount] = m_CachedTransforms[decalIndex];
m_InstanceNormalToWorld[instanceCount] = m_CachedNormalToWorld[decalIndex];
float fadeFactor = (cullDistance - distanceToDecal) / (cullDistance * (1.0f - m_CachedDrawDistances[decalIndex].y));
m_InstanceNormalToWorld[instanceCount].m03 = fadeFactor; // rotation only matrix so 3rd column can be used to pass some values
instanceCount++;
if (instanceCount == kDrawIndexedBatchSize)
{
m_PropertyBlock.SetMatrixArray(m_NormalToWorldID, m_InstanceNormalToWorld);
cmd.DrawMeshInstanced(m_DecalMesh, 0, KeyMaterial, 0, m_InstanceMatrices, kDrawIndexedBatchSize, m_PropertyBlock);
instanceCount = 0;
}
}
}
if (instanceCount > 0)
{

private int m_DecalsCount = 0;
private Matrix4x4[] m_CachedTransforms = new Matrix4x4[kDecalBlockSize];
private Matrix4x4[] m_CachedNormalToWorld = new Matrix4x4[kDecalBlockSize];
private Vector2[] m_CachedDrawDistances = new Vector2[kDecalBlockSize]; // x - draw distance, y - fade scale
private Material m_Material;
}

}
}
public void UpdateBoundingSphere(DecalProjectorComponent decal)
public void UpdateCachedData(DecalProjectorComponent decal)
{
if (decal.CullIndex == DecalProjectorComponent.kInvalidIndex) // check if we have this decal
return;

if (m_DecalSets.TryGetValue(key, out decalSet))
{
decalSet.UpdateBoundingSphere(decal);
decalSet.UpdateCachedData(decal);
}
}

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


if (m_PreviewTexture != null)
m_PreviewTexture.Release();
var baseDesc = m_PreviewHDCamera.renderTextureDesc;
baseDesc.width = width;
baseDesc.height = height;
CoreUtils.UpdateRenderTextureDescriptor(ref baseDesc, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear, 1, true);
m_PreviewTexture = new RenderTexture(baseDesc);
m_PreviewTexture = new RenderTexture(width, height, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
m_PreviewTexture.enableRandomWrite = true;
m_PreviewTexture.Create();
}
return m_PreviewTexture;
}

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraUI.cs


public static readonly CED.IDrawer SectionCaptureSettings = CED.FoldoutGroup(
"Capture Settings",
(s, p, o) => s.isSectionExpandedCaptureSettings,
true,
FoldoutOption.Indent,
CED.Action(Drawer_FieldOcclusionCulling),
CED.Action(Drawer_FieldNormalizedViewPort));

true,
FoldoutOption.Indent,
#if ENABLE_MULTIPLE_DISPLAYS
CED.Action(Drawer_SectionMultiDisplay),
#endif

public static readonly CED.IDrawer SectionXRSettings = CED.FadeGroup(
(s, d, o, i) => s.isSectionAvailableXRSettings,
false,
FadeOption.Animate,
true,
FoldoutOption.Indent,
false,
FadeOption.Animate,
CED.Select(
(s, d, o) => s.frameSettingsUI,
(s, d, o) => d.frameSettings,

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Decal/DecalMenuItems.cs


{
public class DecalMenuItems
{
[MenuItem("GameObject/Render Pipeline/High Definition/DecalProjector", priority = CoreUtils.gameObjectMenuPriority)]
[MenuItem("GameObject/Rendering/DecalProjector", priority = CoreUtils.gameObjectMenuPriority)]
static void CreateDecal(MenuCommand menuCommand)
{
// Create a custom game object

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


// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'
Shader "Debug/ReflectionProbePreview"
Shader "Debug/ReflectionProbePreview"
{
Properties
{

SubShader
{
Tags{ "RenderType" = "Opaque" "Queue" = "Transparent" }
LOD 100
LOD 100
{
Name "ForwardUnlit"
Tags{ "LightMode" = "Forward" }
{
Name "ForwardUnlit"
Tags{ "LightMode" = "Forward" }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "HDRP/ShaderVariables.hlsl"
struct appdata
{
float4 positionOS : POSITION;
float3 normalOS : NORMAL;
};
struct appdata
{
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct v2f
{
float4 positionCS : SV_POSITION;
float3 normalWS : NORMAL;
float3 positionWS : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
float3 normal : NORMAL;
float3 worldpos : TEXCOORD0;
};
TEXTURECUBE(_Cubemap);
SAMPLER(sampler_Cubemap);
samplerCUBE _Cubemap;
float3 _CameraWorldPosition;
float _MipLevel;
float _Exposure;
float3 _CameraWorldPosition;
float _MipLevel;
float _Exposure;
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.worldpos = mul(unity_ObjectToWorld, v.vertex);
o.normal = mul(unity_ObjectToWorld, float4(v.normal, 0)).xyz;
return o;
}
v2f vert(appdata v)
{
v2f o;
// Transform local to world before custom vertex code
o.positionWS = TransformObjectToWorld(v.positionOS.xyz);
o.positionWS = GetCameraRelativePositionWS(o.positionWS);
o.positionCS = TransformWorldToHClip(o.positionWS);
o.normalWS = TransformObjectToWorldNormal(v.normalOS);
return o;
}
float4 frag(v2f i) : SV_Target
{
//float3 view = normalize(i.worldpos - _CameraWorldPosition);
float3 V = normalize(i.positionWS - GetPrimaryCameraPosition());
float3 R = reflect(V, i.normalWS);
float4 color = SAMPLE_TEXTURECUBE_LOD(_Cubemap, sampler_Cubemap, R, _MipLevel).rgba;
color = color * exp2(_Exposure);
float4 frag(v2f i) : SV_Target
{
//float3 view = normalize(i.worldpos - _CameraWorldPosition);
float3 view = normalize(i.worldpos - _WorldSpaceCameraPos);
float3 reflected = reflect(view, i.normal);
float4 col = texCUBElod(_Cubemap,float4(reflected,_MipLevel));
col = col*exp2(_Exposure);
return col;
}
ENDCG
}
return float4(color);
}
ENDHLSL
}
}
}

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


}
}
[MenuItem("Assets/Create/Render Pipeline/High Definition/Render Pipeline", priority = CoreUtils.assetCreateMenuPriority1)]
[MenuItem("Assets/Create/Rendering/High Definition Render Pipeline Asset", priority = CoreUtils.assetCreateMenuPriority1)]
static void CreateHDRenderPipeline()
{
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");

// Load default renderPipelineResources / Material / Shader
string HDRenderPipelinePath = HDEditorUtils.GetHDRenderPipelinePath();
string PostProcessingPath = HDEditorUtils.GetPostProcessingPath();
string CorePath = HDEditorUtils.GetCorePath();
newAsset.defaultDiffuseMaterial = Load<Material>(HDRenderPipelinePath + "RenderPipelineResources/DefaultHDMaterial.mat");

newAsset.debugColorPickerShader = Load<Shader>(HDRenderPipelinePath + "Debug/DebugColorPicker.Shader");
newAsset.deferredShader = Load<Shader>(HDRenderPipelinePath + "Lighting/Deferred.Shader");
newAsset.gaussianPyramidCS = Load<ComputeShader>(PostProcessingPath + "Shaders/Builtins/GaussianDownsample.compute");
newAsset.depthPyramidCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/DepthDownsample.compute");
newAsset.gaussianPyramidCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/ColorPyramid.compute");
newAsset.depthPyramidCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/DepthPyramid.compute");
newAsset.copyChannelCS = Load<ComputeShader>(CorePath + "Resources/GPUCopy.compute");
newAsset.applyDistortionCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/ApplyDistorsion.compute");

// General
newAsset.cameraMotionVectors = Load<Shader>(HDRenderPipelinePath + "RenderPipelineResources/CameraMotionVectors.shader");
newAsset.copyStencilBuffer = Load<Shader>(HDRenderPipelinePath + "RenderPipelineResources/CopyStencilBuffer.shader");
newAsset.copyDepthBuffer = Load<Shader>(HDRenderPipelinePath + "RenderPipelineResources/CopyDepthBuffer.shader");
newAsset.blit = Load<Shader>(HDRenderPipelinePath + "RenderPipelineResources/Blit.shader");
// Sky

}
}
[MenuItem("Assets/Create/Render Pipeline/High Definition/Render Pipeline Resources", priority = CoreUtils.assetCreateMenuPriority1)]
[MenuItem("Assets/Create/Rendering/High Definition Render Pipeline Resources", priority = CoreUtils.assetCreateMenuPriority1)]
static void CreateRenderPipelineResources()
{
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");

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


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

}
}
[MenuItem("Edit/Render Pipeline/Upgrade/High Definition/Reset All Material Asset's Keywords (Materials in Project)", priority = CoreUtils.editMenuPriority2)]
// Don't expose, ResetAllMaterialKeywordsInProjectAndScenes include it anyway
//[MenuItem("Edit/Render Pipeline/Reset All Material Asset's Keywords (Materials in Project)", priority = CoreUtils.editMenuPriority3)]
static void ResetAllMaterialAssetsKeywords()
{
try

}
}
[MenuItem("Edit/Render Pipeline/Upgrade/High Definition/Reset All Materials Keywords (Materials in Project and scenes)", priority = CoreUtils.editMenuPriority2)]
[MenuItem("Edit/Render Pipeline/Reset All Project and Scene High Definition Materials Keywords", priority = CoreUtils.editMenuPriority3)]
static void ResetAllMaterialKeywordsInProjectAndScenes()
{
var openedScenes = new string[EditorSceneManager.loadedSceneCount];

}
}
[MenuItem("Internal/HDRenderPipeline/Update/Update material for subsurface")]
static void UpdateMaterialForSubsurface()
{
try
{
var matIds = AssetDatabase.FindAssets("t:Material");
for (int i = 0, length = matIds.Length; i < length; i++)
{
var path = AssetDatabase.GUIDToAssetPath(matIds[i]);
var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
EditorUtility.DisplayProgressBar(
"Setup materials Keywords...",
string.Format("{0} / {1} materials subsurface updated.", i, length),
i / (float)(length - 1));
bool VSCEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
if (mat.shader.name == "HDRenderPipeline/LitTessellation" ||
mat.shader.name == "HDRenderPipeline/Lit" ||
mat.shader.name == "HDRenderPipeline/LayeredLit" ||
mat.shader.name == "HDRenderPipeline/LayeredLitTessellation")
{
float materialID = mat.GetInt("_MaterialID");
if (materialID != 0.0)
continue;
if (mat.HasProperty("_SSSAndTransmissionType"))
{
CheckOutFile(VSCEnabled, mat);
int materialSSSAndTransmissionID = mat.GetInt("_SSSAndTransmissionType");
// Both;, SSS only, Transmission only
if (materialSSSAndTransmissionID == 2.0)
{
mat.SetInt("_MaterialID", 5);
}
else
{
if (materialSSSAndTransmissionID == 0.0)
mat.SetFloat("_TransmissionEnable", 1.0f);
else
mat.SetFloat("_TransmissionEnable", 0.0f);
}
EditorUtility.SetDirty(mat);
}
}
}
}
finally
{
EditorUtility.ClearProgressBar();
}
}
//
[MenuItem("Internal/HDRenderPipeline/Update/Update Height Maps parametrization")]
static void UpdateHeightMapParametrization()

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

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

class DoCreateNewAssetDiffusionProfileSettings : DoCreateNewAsset<DiffusionProfileSettings> {}
[MenuItem("Assets/Create/Render Pipeline/High Definition/Diffusion profile Settings", priority = CoreUtils.assetCreateMenuPriority2)]
[MenuItem("Assets/Create/Rendering/Diffusion profile Settings", priority = CoreUtils.assetCreateMenuPriority2)]
static void MenuCreateDiffusionProfile()
{
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");

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


if (m_LightShape != LightShape.Directional)
settings.DrawRange(false);
EditorGUI.BeginChangeCheck(); // For GI we need to detect any change on additional data and call SetLightDirty
// 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
switch (m_LightShape)

default:
Debug.Assert(false, "Not implemented light type");
break;
}
if (EditorGUI.EndChangeCheck())
{
((Light)target).SetLightDirty(); // Should be apply only to parameter that's affect GI, but make the code cleaner
}
}

settings.DrawLightmapping();
EditorGUI.BeginChangeCheck(); // For GI we need to detect any change on additional data and call SetLightDirty
// No cookie with area light (maybe in future textured area light ?)
if (m_LightShape != LightShape.Rectangle && m_LightShape != LightShape.Line)
{

EditorGUILayout.PropertyField(m_AdditionalLightData.lightDimmer, s_Styles.lightDimmer);
EditorGUILayout.PropertyField(m_AdditionalLightData.applyRangeAttenuation, s_Styles.applyRangeAttenuation);
EditorGUI.indentLevel--;
}
if (EditorGUI.EndChangeCheck())
{
((Light)target).SetLightDirty(); // Should be apply only to parameter that's affect GI, but make the code cleaner
}
}

16
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.Drawers.cs


CED.Action(Drawer_ReflectionProbeMode),
CED.FadeGroup((s, p, o, i) => s.IsSectionExpandedMode((ReflectionProbeMode)i),
true,
FadeOption.Indent | FadeOption.Animate,
CED.noop, // Baked
CED.Action(Drawer_ModeSettingsRealtime), // Realtime
CED.Action(Drawer_ModeSettingsCustom) // Custom

public static readonly CED.IDrawer SectionInfluenceVolumeSettings = CED.FoldoutGroup(
"Influence volume settings",
(s, p, o) => s.isSectionExpandedInfluenceVolume,
true,
FoldoutOption.Indent,
false,
FadeOption.Animate,
CED.Action(Drawer_InfluenceBoxSettings), // Box
CED.Action(Drawer_InfluenceSphereSettings) // Sphere
)/*,

public static readonly CED.IDrawer SectionSeparateProjectionVolumeSettings = CED.FadeGroup(
(s, p, o, i) => s.isSectionExpandedSeparateProjection,
false,
FadeOption.Animate,
true,
FoldoutOption.Indent,
false,
FadeOption.Animate,
CED.Action(Drawer_ProjectionBoxSettings), // Box
CED.Action(Drawer_ProjectionSphereSettings) // Sphere
)

public static readonly CED.IDrawer SectionCaptureSettings = CED.FoldoutGroup(
"Capture settings",
(s, p, o) => s.isSectionExpandedCaptureSettings,
true,
FoldoutOption.Indent,
CED.Action(Drawer_CaptureSettings)
);

true,
FoldoutOption.Indent,
CED.Action(Drawer_AdditionalSettings)
);

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Drawers.cs


public static readonly CED.IDrawer SectionFoldoutInfluenceSettings = CED.FoldoutGroup(
"Influence Settings",
(s, d, o) => s.isSectionExpandedInfluenceSettings,
true,
FoldoutOption.Indent,
CED.Action(Drawer_SectionInfluenceSettings)
);

SectionFoldoutCaptureSettings = CED.FoldoutGroup(
"Capture Settings",
(s, d, o) => s.isSectionExpandedCaptureSettings,
true,
FoldoutOption.Indent,
CED.Action(Drawer_SectionCaptureSettings),
CED.FadeGroup(
(s, d, o, i) =>

case 1: return s.isSectionExpandedCaptureStaticSettings;
}
},
false,
FadeOption.Animate,
SectionCaptureMirrorSettings,
SectionCaptureStaticSettings)
);

CED.FadeGroup(
(s, d, o, i) => s.IsSectionExpandedReflectionProbeMode((ReflectionProbeMode)i),
true,
FadeOption.Animate | FadeOption.Indent,
SectionProbeModeBakedSettings,
SectionProbeModeRealtimeSettings,
SectionProbeModeCustomSettings

20
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Handles.cs


{
partial class PlanarReflectionProbeUI
{
#if false
#endif
static readonly Color k_GizmoMirrorPlaneCamera = new Color(128f / 255f, 128f / 255f, 233f / 255f, 128f / 255f);
public static void DrawHandles(PlanarReflectionProbeUI s, PlanarReflectionProbe d, Editor o)

{
case EditBaseShape:
InfluenceVolumeUI.DrawGizmos(
s.influenceVolume,
d.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.Base,
s.influenceVolume,
d.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.Base,
s.influenceVolume,
d.influenceVolume,
s.influenceVolume,
d.influenceVolume,
InfluenceVolumeUI.HandleType.Influence,
InfluenceVolumeUI.HandleType.Influence,
s.influenceVolume,
s.influenceVolume,
InfluenceVolumeUI.HandleType.InfluenceNormal,
InfluenceVolumeUI.HandleType.InfluenceNormal,
InfluenceVolumeUI.HandleType.All);
break;
default:

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Drawers.cs


CED.Action(Drawer_FieldShapeType),
CED.FadeGroup(
(s, d, o, i) => s.IsSectionExpanded_Shape((ShapeType)i),
true,
FadeOption.Animate | FadeOption.Indent,
SectionShapeBox,
SectionShapeSphere
)

CED.FoldoutGroup(
"Influence Volume",
(s, d, o) => s.isSectionExpandedShape,
true,
FoldoutOption.Indent,
false,
FadeOption.Animate,
SectionShapeBox,
SectionShapeSphere
)

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/Reflection/Volume/ProxyVolumeUI.cs


CED.Action(Drawer_FieldShapeType),
CED.FadeGroup(
(s, d, o, i) => s.IsSectionExpanded_Shape((ShapeType)i),
true,
FadeOption.Animate | FadeOption.Indent,
SectionShapeBox,
SectionShapeSphere
)

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Decal/DecalProjectorComponentEditor.cs


{
private MaterialEditor m_MaterialEditor = null;
private DecalProjectorComponent m_DecalProjectorComponent = null;
private SerializedProperty m_MaterialProperty;
private SerializedProperty m_DrawDistanceProperty;
private SerializedProperty m_FadeScaleProperty;
private void OnEnable()
{

m_DecalProjectorComponent.OnMaterialChange += OnMaterialChange;
m_MaterialProperty = serializedObject.FindProperty("m_Material");
m_DrawDistanceProperty = serializedObject.FindProperty("m_DrawDistance");
m_FadeScaleProperty = serializedObject.FindProperty("m_FadeScale");
}
private void OnDisable()

{
EditorGUI.BeginChangeCheck();
base.OnInspectorGUI();
EditorGUILayout.PropertyField(m_MaterialProperty);
EditorGUILayout.PropertyField(m_DrawDistanceProperty);
EditorGUILayout.Slider(m_FadeScaleProperty, 0.0f, 1.0f, new GUIContent("Fade scale"));
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();

69
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/LayeredLit/LayeredLitUI.cs


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 readonly GUIContent heightOffset = new GUIContent("Height Offset", "Offset applied to the height before layering.");
public readonly GUIContent heightTransition = new GUIContent("Height Transition", "Size in world units of the smooth transition between layers.");
public readonly GUIContent perPixelDisplacementLayersWarning = new GUIContent("For pixel displacement to work correctly, all layers with a heightmap must use the same UV mapping");

const string kInheritBaseColor = "_InheritBaseColor";
// Height blend
MaterialProperty[] heightBlendOffset = new MaterialProperty[kMaxLayerCount];
const string kHeightBlendOffset = "_HeightOffset";
MaterialProperty heightTransition = null;
const string kHeightTransition = "_HeightTransition";

{
// Density/opacity mode
opacityAsDensity[i] = FindProperty(string.Format("{0}{1}", kOpacityAsDensity, i), props);
heightBlendOffset[i] = FindProperty(string.Format("{0}{1}", kHeightBlendOffset, i), props);
showLayer[i] = FindProperty(string.Format("{0}{1}", kShowLayer, i), props);
if (i != 0)

Material material = m_MaterialEditor.target as Material;
bool mainLayerInfluenceEnable = useMainLayerInfluence.floatValue > 0.0f;
bool heightBasedBlend = useHeightBasedBlend.floatValue > 0.0f;
EditorGUILayout.LabelField(styles.layeringOptionText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
// Main layer does not have any options but height base blend.
if (layerIndex > 0)
if(mainLayerInfluenceEnable) // This is the only case where we need this sub category.
int paramIndex = layerIndex - 1;
EditorGUILayout.LabelField(styles.layeringOptionText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(opacityAsDensity[layerIndex], styles.opacityAsDensityText);
// Main layer does not have any options but height base blend.
if (layerIndex > 0)
{
int paramIndex = layerIndex - 1;
if (mainLayerInfluenceEnable)
{
m_MaterialEditor.ShaderProperty(inheritBaseColor[paramIndex], styles.inheritBaseColorText);
m_MaterialEditor.ShaderProperty(inheritBaseNormal[paramIndex], styles.inheritBaseNormalText);
// Main height influence is only available if the shader use the heightmap for displacement (per vertex or per level)
// We always display it as it can be tricky to know when per pixel displacement is enabled or not
m_MaterialEditor.ShaderProperty(inheritBaseHeight[paramIndex], styles.inheritBaseHeightText);
m_MaterialEditor.ShaderProperty(opacityAsDensity[layerIndex], styles.opacityAsDensityText);
if (mainLayerInfluenceEnable)
{
m_MaterialEditor.ShaderProperty(inheritBaseColor[paramIndex], styles.inheritBaseColorText);
m_MaterialEditor.ShaderProperty(inheritBaseNormal[paramIndex], styles.inheritBaseNormalText);
// Main height influence is only available if the shader use the heightmap for displacement (per vertex or per level)
// We always display it as it can be tricky to know when per pixel displacement is enabled or not
m_MaterialEditor.ShaderProperty(inheritBaseHeight[paramIndex], styles.inheritBaseHeightText);
}
}
else
{
if (!useMainLayerInfluence.hasMixedValue && useMainLayerInfluence.floatValue != 0.0f)
else
m_MaterialEditor.TexturePropertySingleLine(styles.layerInfluenceMapMaskText, layerInfluenceMaskMap);
if (!useMainLayerInfluence.hasMixedValue && useMainLayerInfluence.floatValue != 0.0f)
{
m_MaterialEditor.TexturePropertySingleLine(styles.layerInfluenceMapMaskText, layerInfluenceMaskMap);
}
}
if (heightBasedBlend)
{
m_MaterialEditor.ShaderProperty(heightBlendOffset[layerIndex], styles.heightOffset);
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUI.indentLevel--;
EditorGUILayout.Space();
DoLayerGUI(material, layerIndex, true);

CoreUtils.SetKeyword(material, "_DENSITY_MODE", useDensityModeEnable);
BaseLitGUI.MaterialId materialId = (BaseLitGUI.MaterialId)material.GetFloat(kMaterialID);
BaseLitGUI.SSSAndTransmissionType sssAndTransmissionType = (BaseLitGUI.SSSAndTransmissionType)material.GetFloat(kSSSAndTransmissionType);
if (materialId == BaseLitGUI.MaterialId.LitSSSAndTransmission)
{
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SUBSURFACE_SCATTERING", sssAndTransmissionType == BaseLitGUI.SSSAndTransmissionType.LitSSSAndTransmission || sssAndTransmissionType == BaseLitGUI.SSSAndTransmissionType.LitSSSOnly);
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_TRANSMISSION", sssAndTransmissionType == BaseLitGUI.SSSAndTransmissionType.LitSSSAndTransmission || sssAndTransmissionType == BaseLitGUI.SSSAndTransmissionType.LitTransmissionOnly);
}
else
{
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SUBSURFACE_SCATTERING", false);
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_TRANSMISSION", false);
}
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SUBSURFACE_SCATTERING", materialId == BaseLitGUI.MaterialId.LitSSS);
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_TRANSMISSION", materialId == BaseLitGUI.MaterialId.LitTranslucent || (materialId == BaseLitGUI.MaterialId.LitSSS && material.GetFloat(kTransmissionEnable) > 0.0f));
}
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props)

43
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/BaseLitUI.cs


// Material ID
public static GUIContent materialIDText = new GUIContent("Material type", "Select a material feature to enable on top of regular material");
public static GUIContent SSSAndTransmissionTypeText = new GUIContent("SSS and Transmission type", "Subsurface Scattering for translucent materials such as skin, vegetation, fruit, marble, wax and milk., Transmission for back lighting");
public static GUIContent transmissionEnableText = new GUIContent("Enable Transmission", "Enable Transmission for getting back lighting");
// Per pixel displacement
public static GUIContent ppdMinSamplesText = new GUIContent("Minimum steps", "Minimum steps (texture sample) to use with per pixel displacement mapping");

public enum DoubleSidedNormalMode
{
Flip,
Mirror
Mirror,
None
}
public enum TessellationMode

public enum MaterialId
{
LitSSSAndTransmission = 0,
LitSSS = 0,
LitSpecular = 4
};
public enum SSSAndTransmissionType
{
LitSSSAndTransmission = 0,
LitSSSOnly = 1,
LitTransmissionOnly = 2,
LitSpecular = 4,
LitTranslucent = 5
};
public enum HeightmapParametrization

// Material ID
protected MaterialProperty materialID = null;
protected const string kMaterialID = "_MaterialID";
protected MaterialProperty sssAndTransmissionType = null;
protected const string kSSSAndTransmissionType = "_SSSAndTransmissionType";
protected MaterialProperty transmissionEnable = null;
protected const string kTransmissionEnable = "_TransmissionEnable";
protected const string kStencilRef = "_StencilRef";
protected const string kStencilWriteMask = "_StencilWriteMask";

// MaterialID
materialID = FindProperty(kMaterialID, props);
sssAndTransmissionType = FindProperty(kSSSAndTransmissionType, props);
transmissionEnable = FindProperty(kTransmissionEnable, props);
displacementMode = FindProperty(kDisplacementMode, props);
displacementLockObjectScale = FindProperty(kDisplacementLockObjectScale, props);

m_MaterialEditor.ShaderProperty(materialID, StylesBaseLit.materialIDText);
if ((int)materialID.floatValue == (int)BaseLitGUI.MaterialId.LitSSSAndTransmission)
if ((int)materialID.floatValue == (int)BaseLitGUI.MaterialId.LitSSS)
m_MaterialEditor.ShaderProperty(sssAndTransmissionType, StylesBaseLit.SSSAndTransmissionTypeText);
}
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(transmissionEnable, StylesBaseLit.transmissionEnableText);
EditorGUI.indentLevel--;
}
m_MaterialEditor.ShaderProperty(supportDBuffer, StylesBaseLit.supportDBufferText);

case DoubleSidedNormalMode.Flip: // Flip mode (in tangent space)
material.SetVector("_DoubleSidedConstants", new Vector4(-1.0f, -1.0f, -1.0f, 0.0f));
break;
case DoubleSidedNormalMode.None: // None mode (in tangent space)
material.SetVector("_DoubleSidedConstants", new Vector4(1.0f, 1.0f, 1.0f, 0.0f));
break;
if ((int)material.GetFloat(kMaterialID) == (int)BaseLitGUI.MaterialId.LitSSSAndTransmission)
if ((int)material.GetFloat(kMaterialID) == (int)BaseLitGUI.MaterialId.LitSSS)
if ((int)material.GetFloat(kSSSAndTransmissionType) == (int)BaseLitGUI.SSSAndTransmissionType.LitSSSAndTransmission ||
(int)material.GetFloat(kSSSAndTransmissionType) == (int)BaseLitGUI.SSSAndTransmissionType.LitSSSOnly)
{
stencilRef = (int)StencilLightingUsage.SplitLighting;
}
stencilRef = (int)StencilLightingUsage.SplitLighting;
}
// As we tag both during velocity pass and Gbuffer pass we need a separate state and we need to use the write mask
material.SetInt(kStencilRef, stencilRef);

123
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/LitUI.cs


// clear coat
coatMask = FindProperty(kCoatMask, props);
coatMaskMap = FindProperty(kCoatMaskMap, props);
coatMaskMap = FindProperty(kCoatMaskMap, props);
// Transparency
refractionMode = FindProperty(kRefractionMode, props, false);

diffusionProfileID[layerIndex].floatValue = profileID;
}
if ((int)sssAndTransmissionType.floatValue == (int)BaseLitGUI.SSSAndTransmissionType.LitSSSAndTransmission || (int)sssAndTransmissionType.floatValue == (int)BaseLitGUI.SSSAndTransmissionType.LitSSSOnly)
if ((int)materialID.floatValue == (int)BaseLitGUI.MaterialId.LitSSS)
if ((int)sssAndTransmissionType.floatValue == (int)BaseLitGUI.SSSAndTransmissionType.LitSSSAndTransmission || (int)sssAndTransmissionType.floatValue == (int)BaseLitGUI.SSSAndTransmissionType.LitTransmissionOnly)
if ((int)materialID.floatValue == (int)BaseLitGUI.MaterialId.LitTranslucent ||
((int)materialID.floatValue == (int)BaseLitGUI.MaterialId.LitSSS && transmissionEnable.floatValue > 0.0f))
{
m_MaterialEditor.TexturePropertySingleLine(Styles.thicknessMapText, thicknessMap[layerIndex]);
if (thicknessMap[layerIndex].textureValue != null)

switch ((BaseLitGUI.MaterialId)materialID.floatValue)
{
case BaseLitGUI.MaterialId.LitSSSAndTransmission:
case BaseLitGUI.MaterialId.LitSSS:
case BaseLitGUI.MaterialId.LitTranslucent:
ShaderSSSAndTransmissionInputGUI(material, layerIndex);
break;
case BaseLitGUI.MaterialId.LitStandard:

if (!isLayeredLit)
{
ShaderClearCoatInputGUI();
}
}
EditorGUILayout.Space();

EditorGUI.indentLevel++;
m_MaterialEditor.TexturePropertySingleLine(Styles.detailMapNormalText, detailMap[layerIndex]);
// When Planar or Triplanar is enable the UVDetail use the same mode, so we disable the choice on UVDetail
if (uvBaseMapping == UVBaseMapping.Planar)
if (material.GetTexture(isLayeredLit ? kDetailMap + layerIndex : kDetailMap))
EditorGUILayout.LabelField(Styles.UVDetailMappingText.text + ": Planar");
}
else if (uvBaseMapping == UVBaseMapping.Triplanar)
{
EditorGUILayout.LabelField(Styles.UVDetailMappingText.text + ": Triplanar");
}
else
{
m_MaterialEditor.ShaderProperty(UVDetail[layerIndex], Styles.UVDetailMappingText);
}
EditorGUI.indentLevel++;
// When Planar or Triplanar is enable the UVDetail use the same mode, so we disable the choice on UVDetail
if (uvBaseMapping == UVBaseMapping.Planar)
{
EditorGUILayout.LabelField(Styles.UVDetailMappingText.text + ": Planar");
}
else if (uvBaseMapping == UVBaseMapping.Triplanar)
{
EditorGUILayout.LabelField(Styles.UVDetailMappingText.text + ": Triplanar");
}
else
{
m_MaterialEditor.ShaderProperty(UVDetail[layerIndex], Styles.UVDetailMappingText);
}
// Setup the UVSet for detail, if planar/triplanar is use for base, it will override the mapping of detail (See shader code)
X = ((UVDetailMapping)UVDetail[layerIndex].floatValue == UVDetailMapping.UV0) ? 1.0f : 0.0f;
Y = ((UVDetailMapping)UVDetail[layerIndex].floatValue == UVDetailMapping.UV1) ? 1.0f : 0.0f;
Z = ((UVDetailMapping)UVDetail[layerIndex].floatValue == UVDetailMapping.UV2) ? 1.0f : 0.0f;
W = ((UVDetailMapping)UVDetail[layerIndex].floatValue == UVDetailMapping.UV3) ? 1.0f : 0.0f;
UVDetailsMappingMask[layerIndex].colorValue = new Color(X, Y, Z, W);
// Setup the UVSet for detail, if planar/triplanar is use for base, it will override the mapping of detail (See shader code)
X = ((UVDetailMapping)UVDetail[layerIndex].floatValue == UVDetailMapping.UV0) ? 1.0f : 0.0f;
Y = ((UVDetailMapping)UVDetail[layerIndex].floatValue == UVDetailMapping.UV1) ? 1.0f : 0.0f;
Z = ((UVDetailMapping)UVDetail[layerIndex].floatValue == UVDetailMapping.UV2) ? 1.0f : 0.0f;
W = ((UVDetailMapping)UVDetail[layerIndex].floatValue == UVDetailMapping.UV3) ? 1.0f : 0.0f;
UVDetailsMappingMask[layerIndex].colorValue = new Color(X, Y, Z, W);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(linkDetailsWithBase[layerIndex], Styles.linkDetailsWithBaseText);
EditorGUI.indentLevel--;
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(linkDetailsWithBase[layerIndex], Styles.linkDetailsWithBaseText);
EditorGUI.indentLevel--;
m_MaterialEditor.TextureScaleOffsetProperty(detailMap[layerIndex]);
if ((DisplacementMode)displacementMode.floatValue == DisplacementMode.Pixel && (UVDetail[layerIndex].floatValue != UVBase[layerIndex].floatValue))
{
if (material.GetTexture(kDetailMap + m_PropertySuffixes[layerIndex]))
EditorGUILayout.HelpBox(Styles.perPixelDisplacementDetailsWarning.text, MessageType.Warning);
m_MaterialEditor.TextureScaleOffsetProperty(detailMap[layerIndex]);
if ((DisplacementMode)displacementMode.floatValue == DisplacementMode.Pixel && (UVDetail[layerIndex].floatValue != UVBase[layerIndex].floatValue))
{
if (material.GetTexture(kDetailMap + m_PropertySuffixes[layerIndex]))
EditorGUILayout.HelpBox(Styles.perPixelDisplacementDetailsWarning.text, MessageType.Warning);
}
m_MaterialEditor.ShaderProperty(detailAlbedoScale[layerIndex], Styles.detailAlbedoScaleText);
m_MaterialEditor.ShaderProperty(detailNormalScale[layerIndex], Styles.detailNormalScaleText);
m_MaterialEditor.ShaderProperty(detailSmoothnessScale[layerIndex], Styles.detailSmoothnessScaleText);
EditorGUI.indentLevel--;
m_MaterialEditor.ShaderProperty(detailAlbedoScale[layerIndex], Styles.detailAlbedoScaleText);
m_MaterialEditor.ShaderProperty(detailNormalScale[layerIndex], Styles.detailNormalScaleText);
m_MaterialEditor.ShaderProperty(detailSmoothnessScale[layerIndex], Styles.detailSmoothnessScaleText);
EditorGUI.indentLevel--;
var surfaceTypeValue = (SurfaceType)surfaceType.floatValue;

}
m_MaterialEditor.TexturePropertySingleLine(Styles.emissiveText, emissiveColorMap, emissiveColor);
m_MaterialEditor.ShaderProperty(UVEmissive, Styles.UVBaseMappingText);
UVBaseMapping uvEmissiveMapping = (UVBaseMapping)UVEmissive.floatValue;
if (material.GetTexture(kEmissiveColorMap))
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(UVEmissive, Styles.UVBaseMappingText);
UVBaseMapping uvEmissiveMapping = (UVBaseMapping)UVEmissive.floatValue;
float X, Y, Z, W;
X = (uvEmissiveMapping == UVBaseMapping.UV0) ? 1.0f : 0.0f;
Y = (uvEmissiveMapping == UVBaseMapping.UV1) ? 1.0f : 0.0f;
Z = (uvEmissiveMapping == UVBaseMapping.UV2) ? 1.0f : 0.0f;
W = (uvEmissiveMapping == UVBaseMapping.UV3) ? 1.0f : 0.0f;
float X, Y, Z, W;
X = (uvEmissiveMapping == UVBaseMapping.UV0) ? 1.0f : 0.0f;
Y = (uvEmissiveMapping == UVBaseMapping.UV1) ? 1.0f : 0.0f;
Z = (uvEmissiveMapping == UVBaseMapping.UV2) ? 1.0f : 0.0f;
W = (uvEmissiveMapping == UVBaseMapping.UV3) ? 1.0f : 0.0f;
UVMappingMaskEmissive.colorValue = new Color(X, Y, Z, W);
UVMappingMaskEmissive.colorValue = new Color(X, Y, Z, W);
if ((uvEmissiveMapping == UVBaseMapping.Planar) || (uvEmissiveMapping == UVBaseMapping.Triplanar))
{
m_MaterialEditor.ShaderProperty(TexWorldScaleEmissive, Styles.texWorldScaleText);
}
if ((uvEmissiveMapping == UVBaseMapping.Planar) || (uvEmissiveMapping == UVBaseMapping.Triplanar))
{
m_MaterialEditor.ShaderProperty(TexWorldScaleEmissive, Styles.texWorldScaleText);
m_MaterialEditor.TextureScaleOffsetProperty(emissiveColorMap);
EditorGUI.indentLevel--;
m_MaterialEditor.TextureScaleOffsetProperty(emissiveColorMap);
m_MaterialEditor.ShaderProperty(emissiveIntensity, Styles.emissiveIntensityText);
m_MaterialEditor.ShaderProperty(albedoAffectEmissive, Styles.albedoAffectEmissiveText);

}
BaseLitGUI.MaterialId materialId = (BaseLitGUI.MaterialId)material.GetFloat(kMaterialID);
BaseLitGUI.SSSAndTransmissionType sssAndTransmissionType = (BaseLitGUI.SSSAndTransmissionType)material.GetFloat(kSSSAndTransmissionType);
if (materialId == BaseLitGUI.MaterialId.LitSSSAndTransmission)
{
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SUBSURFACE_SCATTERING", sssAndTransmissionType == BaseLitGUI.SSSAndTransmissionType.LitSSSAndTransmission || sssAndTransmissionType == BaseLitGUI.SSSAndTransmissionType.LitSSSOnly);
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_TRANSMISSION", sssAndTransmissionType == BaseLitGUI.SSSAndTransmissionType.LitSSSAndTransmission || sssAndTransmissionType == BaseLitGUI.SSSAndTransmissionType.LitTransmissionOnly);
}
else
{
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SUBSURFACE_SCATTERING", false);
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_TRANSMISSION", false);
}
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SUBSURFACE_SCATTERING", materialId == BaseLitGUI.MaterialId.LitSSS);
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_TRANSMISSION", materialId == BaseLitGUI.MaterialId.LitTranslucent || (materialId == BaseLitGUI.MaterialId.LitSSS && material.GetFloat(kTransmissionEnable) > 0.0f));
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_ANISOTROPY", materialId == BaseLitGUI.MaterialId.LitAniso);
// No material Id for clear coat, just test the attribute

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Unlit/BaseUnlitUI.cs


// 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_ForwardOnlyDebugDisplayStr, true);
material.SetShaderPassEnabled(HDShaderPassNames.s_GBufferDebugDisplayStr, true);
material.SetShaderPassEnabled(HDShaderPassNames.s_TransparentBackfaceDebugDisplayStr, enablePass);
material.SetShaderPassEnabled(HDShaderPassNames.s_TransparentDepthPostpassStr, enablePass);
material.SetShaderPassEnabled(HDShaderPassNames.s_MetaStr, enablePass);
material.SetShaderPassEnabled(HDShaderPassNames.s_ShadowCasterStr, enablePass);

if (backFaceEnable)
{
material.SetShaderPassEnabled(HDShaderPassNames.s_TransparentBackfaceStr, true);
material.SetShaderPassEnabled(HDShaderPassNames.s_TransparentBackfaceDebugDisplayStr, true);
material.SetShaderPassEnabled(HDShaderPassNames.s_TransparentBackfaceDebugDisplayStr, false);
}
}

14
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/FrameSettingsUI.cs


public static CED.IDrawer SectionRenderingPasses = CED.FoldoutGroup(
"Rendering Passes",
(s, p, o) => s.isSectionExpandedRenderingPasses,
true,
FoldoutOption.Indent,
CED.LabelWidth(200, CED.Action(Drawer_SectionRenderingPasses))
);

true,
FoldoutOption.Indent,
false,
FadeOption.Animate,
true,
FadeOption.Animate | FadeOption.Indent,
CED.Action(Drawer_FieldRenderAlphaTestOnlyInDeferredPrepass))),
CED.Action(Drawer_SectionOtherRenderingSettings)
)

(s, d, o, i) => s.isSectionExpandedXRSupported,
false,
FadeOption.Animate,
true,
FoldoutOption.Indent,
true,
FoldoutOption.Indent,
CED.LabelWidth(250, CED.Action(Drawer_SectionLightingSettings)));
public AnimBool isSectionExpandedRenderingPasses { get { return m_AnimBools[0]; } }

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/LightLoopSettingsUI.cs


public static CED.IDrawer SectionLightLoopSettings = CED.FoldoutGroup(
"Light Loop Settings",
(s, p, o) => s.isSectionExpandedLightLoopSettings,
true,
FoldoutOption.Indent,
CED.LabelWidth(250, CED.Action(Drawer_SectionLightLoopSettings)));
public AnimBool isSectionExpandedLightLoopSettings { get { return m_AnimBools[0]; } }

if (EditorGUILayout.BeginFadeGroup(s.isSectionExpandedEnableTileAndCluster.faded))
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(p.isFptlEnabled, _.GetContent("Enable FPTL"));
EditorGUILayout.PropertyField(p.enableFptlForForwardOpaque, _.GetContent("Enable FPTL For Forward Opaque"));
EditorGUILayout.PropertyField(p.enableBigTilePrepass, _.GetContent("Enable Big Tile Prepass"));
EditorGUILayout.PropertyField(p.enableComputeLightEvaluation, _.GetContent("Enable Compute Light Evaluation"));

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


(s, d, o) => s.shadowInitParams,
(s, d, o) => d.shadowInitParams,
ShadowInitParametersUI.SectionAtlas
),
CED.space,
CED.Select(
(s, d, o) => s.decalSettings,
(s, d, o) => d.decalSettings,
GlobalDecalSettingsUI.Inspector
);
}

);
GlobalLightLoopSettingsUI lightLoopSettings = new GlobalLightLoopSettingsUI();
GlobalDecalSettingsUI decalSettings = new GlobalDecalSettingsUI();
ShadowInitParametersUI shadowInitParams = new ShadowInitParametersUI();
public RenderPipelineSettingsUI()

{
lightLoopSettings.Reset(data.lightLoopSettings, repaint);
shadowInitParams.Reset(data.shadowInitParams, repaint);
decalSettings.Reset(data.decalSettings, repaint);
base.Reset(data, repaint);
}

shadowInitParams.Update();
decalSettings.Update();
base.Update();
}

EditorGUILayout.PropertyField(d.supportSSR, _.GetContent("Support SSR"));
EditorGUILayout.PropertyField(d.supportSSAO, _.GetContent("Support SSAO"));
EditorGUILayout.PropertyField(d.supportDBuffer, _.GetContent("Support Decal Buffer"));
EditorGUILayout.PropertyField(d.supportMSAA, _.GetContent("Support MSAA"));
EditorGUILayout.PropertyField(d.supportMSAA, _.GetContent("Support Multi Sampling Anti-Aliasing"));
EditorGUILayout.PropertyField(d.MSAASampleCount, _.GetContent("MSAA Sample Count"));
EditorGUILayout.PropertyField(d.supportForwardOnly, _.GetContent("Support Forward Only"));
EditorGUILayout.PropertyField(d.supportMotionVectors, _.GetContent("Support Motion Vectors"));
EditorGUILayout.PropertyField(d.supportStereo, _.GetContent("Support Stereo Rendering"));
--EditorGUI.indentLevel;
}
}

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/RenderLoopSettings/SerializedRenderPipelineSettings.cs


public SerializedProperty supportSSAO;
public SerializedProperty supportDBuffer;
public SerializedProperty supportMSAA;
public SerializedProperty MSAASampleCount;
public SerializedProperty supportForwardOnly;
public SerializedProperty supportMotionVectors;
public SerializedProperty supportStereo;
public SerializedGlobalDecalSettings decalSettings;
public SerializedRenderPipelineSettings(SerializedProperty root)
{

supportSSAO = root.Find((RenderPipelineSettings s) => s.supportSSAO);
supportDBuffer = root.Find((RenderPipelineSettings s) => s.supportDBuffer);
supportMSAA = root.Find((RenderPipelineSettings s) => s.supportMSAA);
MSAASampleCount = root.Find((RenderPipelineSettings s) => s.msaaSampleCount);
supportForwardOnly = root.Find((RenderPipelineSettings s) => s.supportForwardOnly);
supportMotionVectors = root.Find((RenderPipelineSettings s) => s.supportMotionVectors);
supportStereo = root.Find((RenderPipelineSettings s) => s.supportStereo);
decalSettings = new SerializedGlobalDecalSettings(root.Find((RenderPipelineSettings s) => s.decalSettings));
}
}
}

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/UpgradeStandardShaderMaterials.cs


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

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDCustomSamplerId.cs


PyramidDepth,
PostProcessing,
RenderDebug,
InitAndClearBuffer,
InitGBuffersAndClearDepthStencil,
ClearBuffers,
ClearDepthStencil,
ClearSSSDiffuseTarget,
ClearSSSFilteringTarget,
ClearAndCopyStencilTexture,

HDRenderPipelineRender,
CullResultsCull,
CopyDepthForSceneView,
// Profile sampler for tile pass
TPPrepareLightsForGPU,

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

13
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipelineAsset.asset


--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1

enableBigTilePrepass: 1
isFptlEnabled: 1
renderPipelineSettings:
supportShadowMask: 1
supportShadowMask: 0
supportsForwardOnly: 0
supportMSAA: 0
supportMSAAAntiAliasing: 0
msaaSampleCount: 1
supportsMotionVectors: 1
supportsStereo: 0
lightLoopSettings:
spotCookieSize: 128
cookieTexArraySize: 16

shadowInitParams:
shadowAtlasWidth: 4096
shadowAtlasHeight: 4096
decalSettings:
drawDistance: 1000
atlasSize: 8192
diffusionProfileSettings: {fileID: 11400000, guid: 404820c4cf36ad944862fa59c56064f0,
type: 2}

19
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipelineAsset.cs


m_FrameSettings.CopyTo(m_FrameSettingsRuntime);
m_frameSettingsIsDirty = false;
// In Editor we can have plenty of camera that are not render at the same time as SceneView.
// It is really tricky to keep in sync with them. To have a coherent state. When a change is done
// on HDRenderPipelineAsset, we tag all camera as dirty so we are sure that they will get the
// correct default FrameSettings when the camera will be in the HDRenderPipeline.Render() call
// otherwise, as SceneView and Game camera are not in the same call Render(), Game camera that use default
// will not be update correctly.
#if UNITY_EDITOR
Camera[] cameras = Camera.allCameras;
foreach (Camera camera in cameras)
{
var additionalCameraData = camera.GetComponent<HDAdditionalCameraData>();
if (additionalCameraData)
{
// Call OnAfterDeserialize that set dirty on FrameSettings
additionalCameraData.OnAfterDeserialize();
}
}
#endif
}
}

57
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs


// 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_ForwardOnlyDebugDisplayStr = "ForwardOnlyDebugDisplay";
public static readonly string s_GBufferDebugDisplayStr = "GBufferDebugDisplay";
public static readonly string s_TransparentBackfaceDebugDisplayStr = "TransparentBackfaceDebugDisplay";
public static readonly string s_TransparentDepthPostpassStr = "TransparentDepthPostpass";
public static readonly string s_MetaStr = "Meta";
public static readonly string s_ShadowCasterStr = "ShadowCaster";

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_ForwardOnlyDebugDisplayName = new ShaderPassName(s_ForwardOnlyDebugDisplayStr);
public static readonly ShaderPassName s_GBufferDebugDisplayName = new ShaderPassName(s_GBufferDebugDisplayStr);
public static readonly ShaderPassName s_TransparentBackfaceDebugDisplayName = new ShaderPassName(s_TransparentBackfaceDebugDisplayStr);
public static readonly ShaderPassName s_TransparentDepthPostpassName = new ShaderPassName(s_TransparentDepthPostpassStr);
// Legacy name

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_screenSize = Shader.PropertyToID("g_screenSize");
public static readonly int g_iNumSamplesMSAA = Shader.PropertyToID("g_iNumSamplesMSAA");
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 _StencilRef = Shader.PropertyToID("_StencilRef");
public static readonly int _StencilCmp = Shader.PropertyToID("_StencilCmp");
public static readonly int _InputDepth = Shader.PropertyToID("_InputDepthTexture");
public static readonly int _SrcBlend = Shader.PropertyToID("_SrcBlend");
public static readonly int _DstBlend = Shader.PropertyToID("_DstBlend");

public static readonly int _DecalHTileTexture = Shader.PropertyToID("_DecalHTileTexture");
public static readonly int _ViewMatrix = Shader.PropertyToID("_ViewMatrix");
public static readonly int _InvViewMatrix = Shader.PropertyToID("_InvViewMatrix");

public static readonly int _ViewParam = Shader.PropertyToID("_ViewParam");
public static readonly int _InvProjParam = Shader.PropertyToID("_InvProjParam");
public static readonly int _ScreenSize = Shader.PropertyToID("_ScreenSize");
public static readonly int _ScreenToTargetScale = Shader.PropertyToID("_ScreenToTargetScale");
public static readonly int _InvProjMatrixStereo = Shader.PropertyToID("_InvProjMatrixStereo");
public static readonly int _InvViewProjMatrixStereo = Shader.PropertyToID("_InvViewProjMatrixStereo");
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 _GaussianPyramidColorTexture = Shader.PropertyToID("_GaussianPyramidColorTexture");
public static readonly int _PyramidDepthTexture = 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[] _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 _DebugColorPickerTexture = Shader.PropertyToID("_DebugColorPickerTexture");
public static readonly int _ColorPickerParam = Shader.PropertyToID("_ColorPickerParam");

public static readonly int _DebugFullScreenTexture = Shader.PropertyToID("_DebugFullScreenTexture");
public static readonly int _BlitTexture = Shader.PropertyToID("_BlitTexture");
public static readonly int _BlitScaleBias = Shader.PropertyToID("_BlitScaleBias");
public static readonly int _BlitMipLevel = Shader.PropertyToID("_BlitMipLevel");
public static readonly int _WorldScales = Shader.PropertyToID("_WorldScales");
public static readonly int _FilterKernels = Shader.PropertyToID("_FilterKernels");

public static readonly int _Source4 = Shader.PropertyToID("_Source4");
public static readonly int _Result1 = Shader.PropertyToID("_Result1");
public static readonly int _AmbientProbeCoeffs = Shader.PropertyToID("_AmbientProbeCoeffs");
public static readonly int _CornetteShanksConstant = Shader.PropertyToID("_CornetteShanksConstant");
public static readonly int _VBufferResolution = Shader.PropertyToID("_VBufferResolution");
public static readonly int _VBufferScaleAndSliceCount = Shader.PropertyToID("_VBufferScaleAndSliceCount");
public static readonly int _VBufferDepthEncodingParams = Shader.PropertyToID("_VBufferDepthEncodingParams");

197
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs


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

public const RendererConfiguration k_RendererConfigurationBakedLightingWithShadowMask = k_RendererConfigurationBakedLighting | RendererConfiguration.PerObjectOcclusionProbe | RendererConfiguration.PerObjectOcclusionProbeProxyVolume | RendererConfiguration.PerObjectShadowMask;
static public HDAdditionalReflectionData s_DefaultHDAdditionalReflectionData { get { return ComponentSingleton<HDAdditionalReflectionData>.instance; } }
static public HDAdditionalLightData s_DefaultHDAdditionalLightData { get { return ComponentSingleton<HDAdditionalLightData>.instance; } }
static public HDAdditionalCameraData s_DefaultHDAdditionalCameraData { get { return ComponentSingleton<HDAdditionalCameraData>.instance; } }
public static Material GetBlitMaterial()
{
HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
if (hdPipeline != null)
{
return hdPipeline.GetBlitMaterial();
}
return null;
}
public static RenderPipelineSettings hdrpSettings
{
get
{
HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
if (hdPipeline != null)
{
return hdPipeline.renderPipelineSettings;
}
return null;
}
}
static MaterialPropertyBlock s_PropertyBlock = new MaterialPropertyBlock();
public static List<RenderPipelineMaterial> GetRenderPipelineMaterialList()
{

// Transpose for HLSL.
return Matrix4x4.Transpose(worldToViewMatrix.transpose * viewSpaceRasterTransform);
}
// This set of RenderTarget management methods is supposed to be used when rendering into a camera dependent render texture.
// This will automatically set the viewport based on the camera size and the RTHandle scaling info.
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RTHandle buffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
{
cmd.SetRenderTarget(buffer, miplevel, cubemapFace, depthSlice);
SetViewport(cmd, camera, buffer);
CoreUtils.ClearRenderTarget(cmd, clearFlag, clearColor);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RTHandle buffer, ClearFlag clearFlag = ClearFlag.None, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
{
SetRenderTarget(cmd, camera, buffer, clearFlag, CoreUtils.clearColorAllBlack, miplevel, cubemapFace, depthSlice);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RTHandle colorBuffer, RTHandle depthBuffer, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
{
SetRenderTarget(cmd, camera, colorBuffer, depthBuffer, ClearFlag.None, CoreUtils.clearColorAllBlack, miplevel, cubemapFace, depthSlice);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RTHandle colorBuffer, RTHandle depthBuffer, ClearFlag clearFlag, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
{
SetRenderTarget(cmd, camera, colorBuffer, depthBuffer, clearFlag, CoreUtils.clearColorAllBlack, miplevel, cubemapFace, depthSlice);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RTHandle colorBuffer, RTHandle depthBuffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
{
CoreUtils.SetRenderTarget(cmd, colorBuffer, depthBuffer, miplevel, cubemapFace, depthSlice);
SetViewport(cmd, camera, colorBuffer);
CoreUtils.ClearRenderTarget(cmd, clearFlag, clearColor);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RenderTargetIdentifier[] colorBuffers, RTHandle depthBuffer)
{
CoreUtils.SetRenderTarget(cmd, colorBuffers, depthBuffer, ClearFlag.None, CoreUtils.clearColorAllBlack);
SetViewport(cmd, camera, depthBuffer);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RenderTargetIdentifier[] colorBuffers, RTHandle depthBuffer, ClearFlag clearFlag = ClearFlag.None)
{
CoreUtils.SetRenderTarget(cmd, colorBuffers, depthBuffer); // Don't clear here, viewport needs to be set before we do.
SetViewport(cmd, camera, depthBuffer);
CoreUtils.ClearRenderTarget(cmd, clearFlag, CoreUtils.clearColorAllBlack);
}
public static void SetRenderTarget(CommandBuffer cmd, HDCamera camera, RenderTargetIdentifier[] colorBuffers, RTHandle depthBuffer, ClearFlag clearFlag, Color clearColor)
{
cmd.SetRenderTarget(colorBuffers, depthBuffer);
SetViewport(cmd, camera, depthBuffer);
CoreUtils.ClearRenderTarget(cmd, clearFlag, clearColor);
}
// Scaling viewport is done for auto-scaling render targets.
// In the context of HDRP, every auto-scaled RT is scaled against the maximum RTHandles reference size (that can only grow).
// When we render using a camera whose viewport is smaller than the RTHandles reference size (and thus smaller than the RT actual size), we need to set it explicitly (otherwise, native code will set the viewport at the size of the RT)
// For auto-scaled RTs (like for example a half-resolution RT), we need to scale this viewport accordingly.
// For non scaled RTs we just do nothing, the native code will set the viewport at the size of the RT anyway.
public static void SetViewport(CommandBuffer cmd, HDCamera camera, RTHandle target)
{
if (target.useScaling)
{
Debug.Assert(camera != null, "Missing HDCamera when setting up Render Target with auto-scale and Viewport.");
Vector2Int scaledViewportSize = target.GetScaledSize(new Vector2Int(camera.actualWidth, camera.actualHeight));
cmd.SetViewport(new Rect(0.0f, 0.0f, scaledViewportSize.x, scaledViewportSize.y));
}
}
public static void BlitTexture(CommandBuffer cmd, RTHandle source, RTHandle destination, Vector4 scaleBias, float mipLevel, bool bilinear)
{
s_PropertyBlock.SetTexture(HDShaderIDs._BlitTexture, source);
s_PropertyBlock.SetVector(HDShaderIDs._BlitScaleBias, scaleBias);
s_PropertyBlock.SetFloat(HDShaderIDs._BlitMipLevel, mipLevel);
cmd.DrawProcedural(Matrix4x4.identity, GetBlitMaterial(), bilinear ? 1 : 0, MeshTopology.Triangles, 3, 1, s_PropertyBlock);
}
// In the context of HDRP, the internal render targets used during the render loop are the same for all cameras, no matter the size of the camera.
// It means that we can end up rendering inside a partial viewport for one of these "camera space" rendering.
// In this case, we need to make sure than when we blit from one such camera texture to another, we only blit the necessary portion corresponding to the camera viewport.
// Here, both source and destination are camera-scaled.
public static void BlitCameraTexture(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination, float mipLevel = 0.0f, bool bilinear = false)
{
// Will set the correct camera viewport as well.
SetRenderTarget(cmd, camera, destination);
BlitTexture(cmd, source, destination, camera.scaleBias, mipLevel, bilinear);
}
// This case, both source and destination are camera-scaled but we want to override the scale/bias parameter.
public static void BlitCameraTexture(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination, Vector4 scaleBias, float mipLevel = 0.0f, bool bilinear = false)
{
// Will set the correct camera viewport as well.
SetRenderTarget(cmd, camera, destination);
BlitTexture(cmd, source, destination, scaleBias, mipLevel, bilinear);
}
public static void BlitCameraTexture(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination, Rect destViewport, float mipLevel = 0.0f, bool bilinear = false)
{
SetRenderTarget(cmd, camera, destination);
cmd.SetViewport(destViewport);
BlitTexture(cmd, source, destination, camera.scaleBias, mipLevel, bilinear);
}
// This particular case is for blitting a camera-scaled texture into a non scaling texture. So we setup the full viewport (implicit in cmd.Blit) but have to scale the input UVs.
public static void BlitCameraTexture(CommandBuffer cmd, HDCamera camera, RTHandle source, RenderTargetIdentifier destination)
{
cmd.Blit(source, destination, new Vector2(camera.scaleBias.x, camera.scaleBias.y), Vector2.zero);
}
// This particular case is for blitting a camera-scaled texture into a non scaling texture. So we setup the full viewport (implicit in cmd.Blit) but have to scale the input UVs.
public static void BlitCameraTexture(CommandBuffer cmd, HDCamera camera, RenderTargetIdentifier source, RTHandle destination)
{
// Will set the correct camera viewport as well.
SetRenderTarget(cmd, camera, destination);
cmd.SetGlobalTexture(HDShaderIDs._BlitTexture, source);
cmd.SetGlobalVector(HDShaderIDs._BlitScaleBias, new Vector4(1.0f, 1.0f, 0.0f, 0.0f));
cmd.SetGlobalFloat(HDShaderIDs._BlitMipLevel, 0.0f);
// Wanted to make things clean and not use SetGlobalXXX APIs but can't use MaterialPropertyBlock with RenderTargetIdentifier so YEY
//s_PropertyBlock.SetTexture(HDShaderIDs._BlitTexture, source);
//s_PropertyBlock.SetVector(HDShaderIDs._BlitScaleBias, camera.scaleBias);
cmd.DrawProcedural(Matrix4x4.identity, GetBlitMaterial(), 0, MeshTopology.Triangles, 3, 1);
}
// These method should be used to render full screen triangles sampling auto-scaling RTs.
// This will set the proper viewport and UV scale.
public static void DrawFullScreen( CommandBuffer commandBuffer, HDCamera camera, Material material,
RTHandle colorBuffer,
MaterialPropertyBlock properties = null, int shaderPassId = 0)
{
HDUtils.SetRenderTarget(commandBuffer, camera, colorBuffer);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.scaleBias);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties);
}
public static void DrawFullScreen( CommandBuffer commandBuffer, HDCamera camera, Material material,
RTHandle colorBuffer, RTHandle depthStencilBuffer,
MaterialPropertyBlock properties = null, int shaderPassId = 0)
{
HDUtils.SetRenderTarget(commandBuffer, camera, colorBuffer, depthStencilBuffer);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.scaleBias);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties);
}
public static void DrawFullScreen( CommandBuffer commandBuffer, HDCamera camera, Material material,
RenderTargetIdentifier[] colorBuffers, RTHandle depthStencilBuffer,
MaterialPropertyBlock properties = null, int shaderPassId = 0)
{
HDUtils.SetRenderTarget(commandBuffer, camera, colorBuffers, depthStencilBuffer);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.scaleBias);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties);
}
public static void DrawFullScreen( CommandBuffer commandBuffer, HDCamera camera, Material material,
RenderTargetIdentifier colorBuffer,
MaterialPropertyBlock properties = null, int shaderPassId = 0)
{
CoreUtils.SetRenderTarget(commandBuffer, colorBuffer);
commandBuffer.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, camera.scaleBias);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties);
}
// Returns mouse coordinates: (x,y) in pixels and (z,w) normalized inside the render target (not the viewport)
public static Vector4 GetMouseCoordinates(HDCamera camera)
{
Vector2 mousePixelCoord = MousePositionDebug.instance.GetMousePosition(camera.screenSize.y);
return new Vector4(mousePixelCoord.x, mousePixelCoord.y, camera.scaleBias.x * mousePixelCoord.x / camera.screenSize.x, camera.scaleBias.y * mousePixelCoord.y / camera.screenSize.y);
}
}
}

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


// the deferred shader will require to use multicompile.
#define UNITY_MATERIAL_LIT // Need to be define before including Material.hlsl
#include "../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#endif
#include "../Lighting/Lighting.hlsl" // This include Material.hlsl
//-------------------------------------------------------------------------------------

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/DeferredDirectionalShadow.compute


float _DirectionalShadowIndex;
float3 _LightDirection;
float4 _ScreenSpaceShadowsParameters;
uint _SampleCount;
int _SampleCount;
CBUFFER_END
#define _ContactShadowLength _ScreenSpaceShadowsParameters.x

float sampleStep = ((i + 1) * step + step * dither);
// UVs for the current sample
float2 sampleUV = startUV + rayUV * sampleStep;
float2 sampleUV = (startUV + rayUV * sampleStep) * _ScreenToTargetScale.xy;
// Ray depth for this sample
float raySampleDepth = startDepth + rayDepth * sampleStep;

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/GlobalLightLoopSettings.cs


public int pointCookieSize = 512;
public int cubeCookieTexArraySize = 16;
public int reflectionProbeCacheSize = 128;
public int planarReflectionProbeCacheSize = 128;
public int reflectionProbeCacheSize = 4;
public int planarReflectionProbeCacheSize = 1024;
public int reflectionCubemapSize = 128;
public int planarReflectionTextureSize = 128;
public bool reflectionCacheCompressed = false;

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


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

[GenerateHLSL]
public class LightDefinitions
{
public static int s_MaxNrLightsPerCamera = 1024;
// enable unity's original left-hand shader camera space (right-hand internally in unity).
public static int s_UseLeftHandCameraSpace = 1;
public static int s_TileSizeFptl = 16;

static Texture2DArray s_DefaultTexture2DArray;
static Cubemap s_DefaultTextureCube;
static HDAdditionalReflectionData defaultHDAdditionalReflectionData { get { return ComponentSingleton<HDAdditionalReflectionData>.instance; } }
static HDAdditionalLightData defaultHDAdditionalLightData { get { return ComponentSingleton<HDAdditionalLightData>.instance; } }
static HDAdditionalCameraData defaultHDAdditionalCameraData { get { return ComponentSingleton<HDAdditionalCameraData>.instance; } }
PlanarReflectionProbeCache m_ReflectionPlanarProbeCache;
ReflectionProbeCache m_ReflectionProbeCache;
TextureCache2D m_CookieTexArray;

}
}
int GetNumTileFtplX(Camera camera)
int GetNumTileFtplX(HDCamera hdCamera)
return (camera.pixelWidth + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
return (hdCamera.actualWidth + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
int GetNumTileFtplY(Camera camera)
int GetNumTileFtplY(HDCamera hdCamera)
return (camera.pixelHeight + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
return (hdCamera.actualHeight + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
int GetNumTileClusteredX(Camera camera)
int GetNumTileClusteredX(HDCamera hdCamera)
return (camera.pixelWidth + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
return (hdCamera.actualWidth + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
int GetNumTileClusteredY(Camera camera)
int GetNumTileClusteredY(HDCamera hdCamera)
return (camera.pixelHeight + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
return (hdCamera.actualHeight + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
}
public bool GetFeatureVariantsEnabled()

directionalLightData.positionWS = light.light.transform.position;
directionalLightData.color = GetLightColor(light);
// Caution: This is bad but if additionalData == defaultHDAdditionalLightData it mean we are trying to promote legacy lights, which is the case for the preview for example, so we need to multiply by PI as legacy Unity do implicit divide by PI for direct intensity.
// So we expect that all light with additionalData == defaultHDAdditionalLightData are currently the one from the preview, light in scene MUST have additionalData
directionalLightData.color *= (defaultHDAdditionalLightData == additionalData) ? Mathf.PI : 1.0f;
// Caution: This is bad but if additionalData == HDUtils.s_DefaultHDAdditionalLightData it mean we are trying to promote legacy lights, which is the case for the preview for example, so we need to multiply by PI as legacy Unity do implicit divide by PI for direct intensity.
// So we expect that all light with additionalData == HDUtils.s_DefaultHDAdditionalLightData are currently the one from the preview, light in scene MUST have additionalData
directionalLightData.color *= (HDUtils.s_DefaultHDAdditionalLightData == additionalData) ? Mathf.PI : 1.0f;
directionalLightData.diffuseScale = additionalData.affectDiffuse ? diffuseDimmer : 0.0f;
directionalLightData.specularScale = additionalData.affectSpecular ? specularDimmer : 0.0f;

Vector3 camPosWS = camera.transform.position;
// We need to properly reset this here otherwise if we go from 1 light to no visible light we would keep the old reference active.
m_CurrentSunLight = null;
m_CurrentSunLightShadowIndex = -1;
// Note: Light with null intensity/Color are culled by the C++, no need to test it here
if (cullResults.visibleLights.Count != 0 || cullResults.visibleReflectionProbes.Count != 0)
{

{
var light = cullResults.visibleLights[lightIndex];
// Light should always have additional data, however preview light right don't have, so we must handle the case by assigning defaultHDAdditionalLightData
// Light should always have additional data, however preview light right don't have, so we must handle the case by assigning HDUtils.s_DefaultHDAdditionalLightData
var additionalData = GetHDAdditionalLightData(light);
LightCategory lightCategory = LightCategory.Count;

// will be use...)
// The lightLoop is in charge, not the shadow pass.
// For now we will still apply the maximum of shadow here but we don't apply the sorting by priority + slot allocation yet
m_CurrentSunLight = null;
m_CurrentSunLightShadowIndex = -1;
// 2. Go through all lights, convert them to GPU format.
// Create simultaneously data for culling (LigthVolumeData and rendering)

m_enableBakeShadowMask = m_enableBakeShadowMask || IsBakedShadowMaskLight(light.light);
// Light should always have additional data, however preview light right don't have, so we must handle the case by assigning defaultHDAdditionalLightData
// Light should always have additional data, however preview light right don't have, so we must handle the case by assigning HDUtils.s_DefaultHDAdditionalLightData
var additionalLightData = GetHDAdditionalLightData(light);
var additionalShadowData = light.light.GetComponent<AdditionalShadowData>(); // Can be null

return (uint)logVolume << 20 | (uint)lightVolumeType << 17 | listType << 16 | ((uint)probeIndex & 0xFFFF);
}
void VoxelLightListGeneration(CommandBuffer cmd, Camera camera, Matrix4x4 projscr, Matrix4x4 invProjscr, RenderTargetIdentifier cameraDepthBufferRT)
void VoxelLightListGeneration(CommandBuffer cmd, HDCamera hdCamera, Matrix4x4 projscr, Matrix4x4 invProjscr, RenderTargetIdentifier cameraDepthBufferRT)
Camera camera = hdCamera.camera;
// clear atomic offset index
cmd.SetComputeBufferParam(buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, s_GlobalLightListAtomic);
cmd.DispatchCompute(buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, 1, 1, 1);

cmd.SetComputeIntParam(buildPerVoxelLightListShader, HDShaderIDs.g_iLog2NumClusters, k_Log2NumClusters);
cmd.SetComputeVectorParam(buildPerVoxelLightListShader, HDShaderIDs.g_screenSize, hdCamera.screenSize);
cmd.SetComputeIntParam(buildPerVoxelLightListShader, HDShaderIDs.g_iNumSamplesMSAA, (int)hdCamera.msaaSamples);
//Vector4 v2_near = invProjscr * new Vector4(0.0f, 0.0f, 0.0f, 1.0f);
//Vector4 v2_far = invProjscr * new Vector4(0.0f, 0.0f, 1.0f, 1.0f);
//float nearPlane2 = -(v2_near.z/v2_near.w);

cmd.SetComputeBufferParam(buildPerVoxelLightListShader, s_GenListPerVoxelKernel, HDShaderIDs._LightVolumeData, s_LightVolumeDataBuffer);
cmd.SetComputeBufferParam(buildPerVoxelLightListShader, s_GenListPerVoxelKernel, HDShaderIDs.g_data, s_ConvexBoundsBuffer);
var numTilesX = GetNumTileClusteredX(camera);
var numTilesY = GetNumTileClusteredY(camera);
var numTilesX = GetNumTileClusteredX(hdCamera);
var numTilesY = GetNumTileClusteredY(hdCamera);
cmd.DispatchCompute(buildPerVoxelLightListShader, s_GenListPerVoxelKernel, numTilesX, numTilesY, 1);
}

cmd.DispatchCompute(buildPerBigTileLightListShader, s_GenListPerBigTileKernel, numBigTilesX, numBigTilesY, 1);
}
var numTilesX = GetNumTileFtplX(camera);
var numTilesY = GetNumTileFtplY(camera);
var numTilesX = GetNumTileFtplX(hdCamera);
var numTilesY = GetNumTileFtplY(hdCamera);
var numTiles = numTilesX * numTilesY;
bool enableFeatureVariants = GetFeatureVariantsEnabled();

}
// Cluster
VoxelLightListGeneration(cmd, camera, projscr, invProjscr, cameraDepthBufferRT);
VoxelLightListGeneration(cmd, hdCamera, projscr, invProjscr, cameraDepthBufferRT);
if (enableFeatureVariants)
{

cmd.SetRenderTarget(BuiltinRenderTextureType.None);
BuildGPULightListsCommon(hdCamera, cmd, cameraDepthBufferRT, stencilTextureRT, skyEnabled);
PushGlobalParams(hdCamera.camera, cmd);
PushGlobalParams(hdCamera, cmd);
}
public GPUFence BuildGPULightListsAsyncBegin(HDCamera hdCamera, ScriptableRenderContext renderContext, RenderTargetIdentifier cameraDepthBufferRT, RenderTargetIdentifier stencilTextureRT, GPUFence startFence, bool skyEnabled)

return completeFence;
}
public void BuildGPULightListAsyncEnd(Camera camera, CommandBuffer cmd, GPUFence doneFence)
public void BuildGPULightListAsyncEnd(HDCamera hdCamera, CommandBuffer cmd, GPUFence doneFence)
PushGlobalParams(camera, cmd);
PushGlobalParams(hdCamera, cmd);
}
private void UpdateDataBuffers()

var add = probe.probe.GetComponent<HDAdditionalReflectionData>();
if (add == null)
{
add = defaultHDAdditionalReflectionData;
add = HDUtils.s_DefaultHDAdditionalReflectionData;
add.blendDistancePositive = Vector3.one * probe.blendDistance;
add.blendDistanceNegative = add.blendDistancePositive;
add.influenceShape = ShapeType.Box;

var add = light.light.GetComponent<HDAdditionalLightData>();
if (add == null)
{
add = defaultHDAdditionalLightData;
add = HDUtils.s_DefaultHDAdditionalLightData;
void PushGlobalParams(Camera camera, CommandBuffer cmd)
void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd)
Camera camera = hdCamera.camera;
// Shadows
m_ShadowMgr.SyncData();
m_ShadowMgr.BindResources(cmd, null, 0);

cmd.SetGlobalInt(HDShaderIDs._EnvLightCount, m_lightList.envLights.Count);
cmd.SetGlobalBuffer(HDShaderIDs._ShadowDatas, s_shadowDatas);
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplX, GetNumTileFtplX(camera));
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplY, GetNumTileFtplY(camera));
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplX, GetNumTileFtplX(hdCamera));
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplY, GetNumTileFtplY(hdCamera));
cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredX, GetNumTileClusteredX(camera));
cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredY, GetNumTileClusteredY(camera));
cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredX, GetNumTileClusteredX(hdCamera));
cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredY, GetNumTileClusteredY(hdCamera));
if (m_FrameSettings.lightLoopSettings.enableBigTilePrepass)
cmd.SetGlobalBuffer(HDShaderIDs.g_vBigTileLightList, s_BigTileLightList);

cmd.SetGlobalFloat(HDShaderIDs.g_fNearPlane, camera.nearClipPlane);
cmd.SetGlobalFloat(HDShaderIDs.g_fFarPlane, camera.farClipPlane);
cmd.SetGlobalInt(HDShaderIDs.g_iLog2NumClusters, k_Log2NumClusters);
cmd.SetGlobalInt(HDShaderIDs.g_isLogBaseBufferEnabled, k_UseDepthBuffer ? 1 : 0);
cmd.SetGlobalBuffer(HDShaderIDs.g_vLayeredOffsetsBuffer, s_PerVoxelOffset);

public bool outputSplitLighting;
}
public void RenderDeferredDirectionalShadow(HDCamera hdCamera, RenderTargetIdentifier deferredShadowRT, RenderTargetIdentifier depthTexture, CommandBuffer cmd)
public void RenderDeferredDirectionalShadow(HDCamera hdCamera, RTHandle deferredShadowRT, RenderTargetIdentifier depthTexture, CommandBuffer cmd)
{
cmd.SetGlobalTexture(HDShaderIDs._DeferredShadowTexture, RuntimeUtilities.blackTexture);
}
using (new ProfilingSample(cmd, "Deferred Directional Shadow", CustomSamplerId.TPDeferredDirectionalShadow.GetSampler()))
{

cmd.SetComputeTextureParam(deferredDirectionalShadowComputeShader, kernel, HDShaderIDs._MainDepthTexture, depthTexture);
int deferredShadowTileSize = 16; // Must match DeferreDirectionalShadow.compute
int numTilesX = (hdCamera.camera.pixelWidth + (deferredShadowTileSize - 1)) / deferredShadowTileSize;
int numTilesY = (hdCamera.camera.pixelHeight + (deferredShadowTileSize - 1)) / deferredShadowTileSize;
int numTilesX = (hdCamera.actualWidth + (deferredShadowTileSize - 1)) / deferredShadowTileSize;
int numTilesY = (hdCamera.actualHeight + (deferredShadowTileSize - 1)) / deferredShadowTileSize;
cmd.SetGlobalTexture(HDShaderIDs._DeferredShadowTexture, deferredShadowRT);
}
}

// The CS is always in the MRT mode. Do not execute the same shader twice.
return;
}
// Predeclared to reduce GC pressure
string tilePassName = "TilePass - Deferred Lighting Pass";

if (enableFeatureVariants)
numVariants = LightDefinitions.s_NumFeatureVariants;
hdCamera.SetupComputeShader(deferredComputeShader, cmd);
for (int variant = 0; variant < numVariants; variant++)
{
int kernel;

}
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._MainDepthTexture, depthTexture);
// TODO: Should remove this setting but can't remove it else get error: Property (_AmbientOcclusionTexture) at kernel index (32) is not set. Check why
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._AmbientOcclusionTexture, HDShaderIDs._AmbientOcclusionTexture);
// TODO: Is it possible to setup this outside the loop ? Can figure out how, get this: Property (specularLightingUAV) at kernel index (21) is not set
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs.specularLightingUAV, colorBuffers[0]);

if (lightingDebug.tileClusterDebug != LightLoop.TileClusterDebug.None)
{
int w = hdCamera.camera.pixelWidth;
int h = hdCamera.camera.pixelHeight;
int w = hdCamera.actualWidth;
int h = hdCamera.actualHeight;
Vector2 mousePixelCoord = MousePositionDebug.instance.GetMousePosition(hdCamera.screenSize.y);
// Debug tiles
if (lightingDebug.tileClusterDebug == LightLoop.TileClusterDebug.MaterialFeatureVariants)

// featureVariants
m_DebugViewTilesMaterial.SetInt(HDShaderIDs._NumTiles, numTiles);
m_DebugViewTilesMaterial.SetInt(HDShaderIDs._ViewTilesFlags, (int)lightingDebug.tileClusterDebugByCategory);
m_DebugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, mousePixelCoord);
m_DebugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(hdCamera));
m_DebugViewTilesMaterial.SetBuffer(HDShaderIDs.g_TileList, s_TileList);
m_DebugViewTilesMaterial.SetBuffer(HDShaderIDs.g_DispatchIndirectBuffer, s_DispatchIndirectBuffer);
m_DebugViewTilesMaterial.EnableKeyword("USE_FPTL_LIGHTLIST");

// lightCategories
m_DebugViewTilesMaterial.SetInt(HDShaderIDs._ViewTilesFlags, (int)lightingDebug.tileClusterDebugByCategory);
m_DebugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, mousePixelCoord);
m_DebugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(hdCamera));
m_DebugViewTilesMaterial.SetBuffer(HDShaderIDs.g_vLightListGlobal, bUseClustered ? s_PerVoxelLightLists : s_LightList);
m_DebugViewTilesMaterial.EnableKeyword(bUseClustered ? "USE_CLUSTERED_LIGHTLIST" : "USE_FPTL_LIGHTLIST");
m_DebugViewTilesMaterial.DisableKeyword(!bUseClustered ? "USE_CLUSTERED_LIGHTLIST" : "USE_FPTL_LIGHTLIST");

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

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

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs.hlsl


//
// UnityEngine.Experimental.Rendering.HDPipeline.LightDefinitions: static fields
//
#define MAX_NR_LIGHTS_PER_CAMERA (1024)
#define MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE (512)
#define VIEWPORT_SCALE_Z (1)
#define USE_LEFT_HAND_CAMERA_SPACE (1)

24
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopDef.hlsl


uint cacheType = index & 1;
index = index >> 1;
float4 color = float4(0.0, 0.0, 0.0, 1.0);
// This code will be inlined as lightLoopContext is hardcoded in the light loop
if (lightLoopContext.sampleReflection == SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES)
{

float4 ndc = ComputeClipSpaceCoordinates(texCoord, _Env2DCaptureVP[index]);
ndc *= rcp(ndc.w);
ndc.xy = ndc.xy * 0.5 + 0.5;
float3 ndc = ComputeNormalizedDeviceCoordinatesWithZ(texCoord, _Env2DCaptureVP[index]);
float4 color = SAMPLE_TEXTURE2D_ARRAY_LOD(_Env2DTextures, s_trilinear_clamp_sampler, ndc.xy, index, 0);
color.a = any(ndc.xyz < 0) || any(ndc.xyz > 1) ? 0 : 1;
color.rgb = SAMPLE_TEXTURE2D_ARRAY_LOD(_Env2DTextures, s_trilinear_clamp_sampler, ndc.xy, index, 0).rgb;
color.a = any(ndc.xyz < 0) || any(ndc.xyz > 1) ? 0.0 : 1.0;
return float4(ndc.xy, 0, color.a);
color = float4(ndc.xy, 0, color.a);
return color;
float4 color = SAMPLE_TEXTURECUBE_ARRAY_LOD_ABSTRACT(_EnvCubemapTextures, s_trilinear_clamp_sampler, texCoord, index, lod);
color.a = 1;
color.rgb = SAMPLE_TEXTURECUBE_ARRAY_LOD_ABSTRACT(_EnvCubemapTextures, s_trilinear_clamp_sampler, texCoord, index, lod).rgb;
return float4(texCoord.xyz * 0.5 + 0.5, color.a);
color = float4(texCoord.xyz * 0.5 + 0.5, color.a);
return color;
return float4(0, 0, 0, 0);
return SampleSkyTexture(texCoord, lod);
color.rgb = SampleSkyTexture(texCoord, lod).rgb;
return color;
}
//-----------------------------------------------------------------------------

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoopSettings.cs


[Serializable]
public class LightLoopSettings
{
public static string kEnableFptlForForwardOpaque = "Enable Fptl for Forward Opaque";
public static string kEnableTileCluster = "Enable Tile/Cluster";
public static string kEnableBigTile = "Enable Big Tile";
public static string kEnableComputeLighting = "Enable Compute Lighting";

// When MSAA is enabled we disable Fptl as it become expensive compare to cluster
// In HD, MSAA is only supported for forward only rendering, no MSAA in deferred mode (for code complexity reasons)
aggregate.enableFptlForForwardOpaque = aggregate.enableFptlForForwardOpaque && !aggregateFrameSettings.enableMSAA;
// disable FPTL for stereo for now
aggregate.enableFptlForForwardOpaque = aggregate.enableFptlForForwardOpaque && !aggregateFrameSettings.enableStereo;
// If Deferred, enable Fptl. If we are forward renderer only and not using Fptl for forward opaque, disable Fptl
aggregate.isFptlEnabled = !aggregateFrameSettings.enableForwardRenderingOnly || aggregate.enableFptlForForwardOpaque;
}

DebugMenuManager.instance.AddDebugItem<bool>(menuName, kEnableFptlForForwardOpaque, () => lightLoopSettings.enableFptlForForwardOpaque, (value) => lightLoopSettings.enableFptlForForwardOpaque = (bool)value);
DebugMenuManager.instance.AddDebugItem<bool>(menuName, kEnableTileCluster, () => lightLoopSettings.enableTileAndCluster, (value) => lightLoopSettings.enableTileAndCluster = (bool)value);
DebugMenuManager.instance.AddDebugItem<bool>(menuName, kEnableBigTile, () => lightLoopSettings.enableBigTilePrepass, (value) => lightLoopSettings.enableBigTilePrepass = (bool)value);
DebugMenuManager.instance.AddDebugItem<bool>(menuName, kEnableComputeLighting, () => lightLoopSettings.enableComputeLightEvaluation, (value) => lightLoopSettings.enableComputeLightEvaluation = (bool)value);

28
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-clustered.compute


float g_fNearPlane;
float g_fFarPlane;
int g_iLog2NumClusters; // numClusters = (1<<g_iLog2NumClusters)
float4 g_screenSize;
int g_iNumSamplesMSAA;
CBUFFER_END
#include "ClusteredUtils.hlsl"

uint2 tileIDX = u3GroupID.xy;
uint t=threadID;
uint iWidth;
uint iHeight;
#ifdef MSAA_ENABLED
uint iNumSamplesMSAA;
g_depth_tex.GetDimensions(iWidth, iHeight, iNumSamplesMSAA);
#else
g_depth_tex.GetDimensions(iWidth, iHeight);
#endif
uint nrTilesX = (iWidth+(TILE_SIZE_CLUSTERED-1))>>log2TileSize;
uint nrTilesY = (iHeight+(TILE_SIZE_CLUSTERED-1))>>log2TileSize;
uint nrTilesX = ((uint)g_screenSize.x +(TILE_SIZE_CLUSTERED-1))>>log2TileSize;
uint nrTilesY = ((uint)g_screenSize.y +(TILE_SIZE_CLUSTERED-1))>>log2TileSize;
uint2 viTilUR = min( viTilLL+uint2(TILE_SIZE_CLUSTERED,TILE_SIZE_CLUSTERED), uint2(iWidth, iHeight) ); // not width and height minus 1 since viTilUR represents the end of the tile corner.
uint2 viTilUR = min( viTilLL+uint2(TILE_SIZE_CLUSTERED,TILE_SIZE_CLUSTERED), uint2(g_screenSize.x, g_screenSize.y) ); // not width and height minus 1 since viTilUR represents the end of the tile corner.
if(t==0)
{

for(int idx=t; idx<(TILE_SIZE_CLUSTERED*TILE_SIZE_CLUSTERED); idx+=NR_THREADS)
{
uint2 uPixCrd = min( uint2(viTilLL.x+(idx&(TILE_SIZE_CLUSTERED-1)), viTilLL.y+(idx>>log2TileSize)), uint2(iWidth-1, iHeight-1) );
uint2 uPixCrd = min( uint2(viTilLL.x+(idx&(TILE_SIZE_CLUSTERED-1)), viTilLL.y+(idx>>log2TileSize)), uint2(g_screenSize.x-1, g_screenSize.y-1) );
for(uint i=0; i<iNumSamplesMSAA; i++)
for(int i=0; i<g_iNumSamplesMSAA; i++)
{
const float fDpth = FetchDepthMSAA(g_depth_tex, uPixCrd, i);
#else

if(dpt_ma<=0.0) dpt_ma = VIEWPORT_SCALE_Z; // assume sky pixel
#endif
float2 vTileLL = float2(viTilLL.x/(float) iWidth, viTilLL.y/(float) iHeight);
float2 vTileUR = float2(viTilUR.x/(float) iWidth, viTilUR.y/(float) iHeight);
float2 vTileLL = float2(viTilLL.x/g_screenSize.x, viTilLL.y/g_screenSize.y);
float2 vTileUR = float2(viTilUR.x/g_screenSize.x, viTilUR.y/g_screenSize.y);
// build coarse list using AABB
#ifdef USE_TWO_PASS_TILED_LIGHTING

int iNrCoarseLights = min(lightOffs,MAX_NR_COARSE_ENTRIES);
#ifdef PERFORM_SPHERICAL_INTERSECTION_TESTS
iNrCoarseLights = SphericalIntersectionTests( t, iNrCoarseLights, float2(min(viTilLL.xy+uint2(TILE_SIZE_CLUSTERED/2,TILE_SIZE_CLUSTERED/2), uint2(iWidth-1, iHeight-1))) );
iNrCoarseLights = SphericalIntersectionTests( t, iNrCoarseLights, float2(min(viTilLL.xy+uint2(TILE_SIZE_CLUSTERED/2,TILE_SIZE_CLUSTERED/2), uint2(g_screenSize.x-1, g_screenSize.y-1))) );
#endif
#ifdef ENABLE_DEPTH_TEXTURE_BACKPLANE

19
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/PlanarReflectionProbeCache.cs


void Initialize()
{
if(m_TempRenderTexture == null)
if (m_TempRenderTexture == null)
m_TempRenderTexture.hideFlags = HideFlags.HideAndDontSave;
m_TempRenderTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, RenderTextureFormat.ARGBHalf, "PlanarReflection", mips : true);
m_ConvolutionTargetTexture.hideFlags = HideFlags.HideAndDontSave;
m_ConvolutionTargetTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, RenderTextureFormat.ARGBHalf, "PlanarReflectionConvolution", mips: true);
m_ConvolutionTargetTexture.Create();
m_ConvertTextureMaterial = CoreUtils.CreateEngineMaterial("Hidden/SRP/BlitCubeTextureFace");

public void Release()
{
if(m_TextureCache != null)
if (m_TextureCache != null)
if(m_TempRenderTexture != null)
if (m_TempRenderTexture != null)
if (m_ConvolutionTargetTexture != null)
{
m_ConvolutionTargetTexture.Release();
m_ConvolutionTargetTexture = null;
}
m_ProbeBakingState = null;
}

RenderTexture convolutionSourceTexture = null;
if (texture2D != null)
{
// if the size if different from the cache probe size or if the input texture format is compressed, we need to convert it
// 1) to a format for which we can generate mip maps
// if the size if different from the cache probe size or if the input texture format is compressed, we need to convert it
// 1) to a format for which we can generate mip maps
// 2) to the proper reflection probe cache size
var sizeMismatch = texture2D.width != m_ProbeSize || texture2D.height != m_ProbeSize;
var formatMismatch = texture2D.format != TextureFormat.RGBAHalf; // Temporary RT for convolution is always FP16

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ProbeWrapper.cs


class VisibleReflectionProbeWrapper : ProbeWrapper
{
static HDAdditionalReflectionData defaultHDAdditionalReflectionData { get { return ComponentSingleton<HDAdditionalReflectionData>.instance; } }
VisibleReflectionProbe probe;
HDAdditionalReflectionData additional;

var add = probe.probe.GetComponent<HDAdditionalReflectionData>();
if (add == null)
{
add = defaultHDAdditionalReflectionData;
add = HDUtils.s_DefaultHDAdditionalReflectionData;
add.blendDistancePositive = Vector3.one * probe.blendDistance;
add.blendDistanceNegative = add.blendDistancePositive;
add.influenceShape = ShapeType.Box;

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


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

{
// Temporary RT used for convolution and compression
m_TempRenderTexture = new RenderTexture(m_ProbeSize, m_ProbeSize, 1, RenderTextureFormat.ARGBHalf);
m_TempRenderTexture.hideFlags = HideFlags.HideAndDontSave;
m_TempRenderTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, RenderTextureFormat.ARGBHalf, "PlanarReflection", mips : true);
m_ConvolutionTargetTexture.hideFlags = HideFlags.HideAndDontSave;
m_ConvolutionTargetTexture.name = CoreUtils.GetRenderTargetAutoName(m_ProbeSize, m_ProbeSize, RenderTextureFormat.ARGBHalf, "PlanarReflection", mips : true);
m_ConvolutionTargetTexture.Create();
m_ConvertTextureMaterial = CoreUtils.CreateEngineMaterial("Hidden/SRP/BlitCubeTextureFace");

public void Release()
{
if(m_TextureCache != null)
if (m_TextureCache != null)
if(m_TempRenderTexture != null)
if (m_TempRenderTexture != null)
}
if (m_ConvolutionTargetTexture != null)
{
m_ConvolutionTargetTexture.Release();
m_ConvolutionTargetTexture = null;
}
m_ProbeBakingState = null;
}

RenderTexture convolutionSourceTexture = null;
if (cubeTexture != null)
{
// if the size if different from the cache probe size or if the input texture format is compressed, we need to convert it
// 1) to a format for which we can generate mip maps
// if the size if different from the cache probe size or if the input texture format is compressed, we need to convert it
// 1) to a format for which we can generate mip maps
// 2) to the proper reflection probe cache size
bool sizeMismatch = cubeTexture.width != m_ProbeSize || cubeTexture.height != m_ProbeSize;
bool formatMismatch = cubeTexture.format != TextureFormat.RGBAHalf; // Temporary RT for convolution is always FP16

16
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Reflection/ReflectionSystemInternal.cs


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

public RenderTexture NewRenderTarget(PlanarReflectionProbe probe)
{
var desc = GetRenderHDCamera(probe).renderTextureDesc;
desc.width = m_Parameters.planarReflectionProbeSize;
desc.height = m_Parameters.planarReflectionProbeSize;
desc.colorFormat = RenderTextureFormat.ARGBHalf;
desc.useMipMap = true;
var rt = new RenderTexture(desc);
rt.name = "PlanarProbeRT " + probe.name;
var rt = new RenderTexture(m_Parameters.planarReflectionProbeSize, m_Parameters.planarReflectionProbeSize, 0, RenderTextureFormat.ARGBHalf);
// No hide and don't save for this one
rt.useMipMap = true;
rt.autoGenerateMips = false;
rt.name = CoreUtils.GetRenderTargetAutoName(m_Parameters.planarReflectionProbeSize, m_Parameters.planarReflectionProbeSize, RenderTextureFormat.ARGBHalf, "PlanarProbeRT");
rt.Create();
return rt;
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/HomogeneousFog.cs


namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[ExecuteInEditMode]
[AddComponentMenu("RenderPipeline/High Definition/Homogenous Fog", -1)]
[AddComponentMenu("Rendering/Homogenous Fog", 1100)]
public class HomogeneousFog : MonoBehaviour
{
public VolumeParameters volumeParameters = new VolumeParameters();

72
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/Resources/VolumetricLighting.compute


#if (SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET == 1)
// E.g. for 1080p: (1920/8)x(1080/8)x(128) = 4,147,200 voxels
#define VBUFFER_TILE_SIZE 8
#define VBUFFER_SLICE_COUNT 128
#define VBUFFER_SLICE_COUNT 64
#define VBUFFER_SLICE_COUNT 256
#define VBUFFER_SLICE_COUNT 128
#define SUPPORT_ASYMMETRY 1 // Support asymmetric phase functions
#define SUPPORT_ASYMMETRY 1 // Support asymmetric phase functions
#define SUPPORT_PUNCTUAL_LIGHTS 1 // Punctual lights contribute to fog lighting
#if (SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET != 0) // Switch between the full and the empty shader
//--------------------------------------------------------------------------------------------------
// Included headers

CBUFFER_START(UnityVolumetricLighting)
float4 _VBufferSampleOffset; // {x, y, z}, w = rendered frame count
float4x4 _VBufferCoordToViewDirWS; // Actually just 3x3, but Unity can only set 4x4
float _CornetteShanksConstant; // CornetteShanksPhasePartConstant(_GlobalFog_Asymmetry)
CBUFFER_END
//--------------------------------------------------------------------------------------------------

lighting.radianceComplete += phase * intensity * color;
}
}
#if (SUPPORT_PUNCTUAL_LIGHTS == 0)
return lighting;
#endif
#ifdef LIGHTLOOP_TILE_PASS
// Loop over 1 or 2 light clusters.

float t0 = ray.strataDirInvViewZ * z0; // Convert view space Z to distance along the stratified ray
float de = rcp(VBUFFER_SLICE_COUNT); // Log-encoded distance between slices
// The contribution of the ambient probe does not depend on the position,
// only on the direction and the length of the interval.
// SampleSH9() evaluates the 3-band SH in a given direction.
float3 probeInScatteredRadiance = SampleSH9(_AmbientProbeCoeffs, ray.centerDirWS);
uint sliceCountHack = max(VBUFFER_SLICE_COUNT, (uint)_VBufferDepthEncodingParams.w); // Prevent unrolling...
#ifdef LIGHTLOOP_TILE_PASS
// Our voxel is not necessarily completely inside a single light cluster.

clusterIndices[0] = GetLightClusterIndex(posInput.tileCoord, z0);
clusterDepths[0] = GetLightClusterMinLinearDepth(posInput.tileCoord, clusterIndices[0]);
#endif // LIGHTLOOP_TILE_PASS
#if defined(SHADER_API_METAL)
[fastopt]
for (uint slice = 0; slice < VBUFFER_SLICE_COUNT; slice++)
#else
uint sliceCountHack = max(VBUFFER_SLICE_COUNT, (uint)_VBufferDepthEncodingParams.w); // Prevent unrolling...
#endif
#if defined(SHADER_API_METAL)
float z1 = DecodeLogarithmicDepth(e1, _VBufferDepthDecodingParams);
#else
#endif
float t1 = ray.strataDirInvViewZ * z1; // Convert view space Z to distance along the stratified ray
float dt = t1 - t0;

// We consider it to be constant along the interval [t0, t1] (within the voxel).
// TODO: piecewise linear.
float3 scattering = _GlobalFog_Scattering;
float extinction = _GlobalFog_Extinction;
float extinction = max(_GlobalFog_Extinction, FLT_MIN); // Avoid NaNs
float asymmetry = _GlobalFog_Asymmetry;
// TODO: define a function ComputeGlobalFogCoefficients(float3 centerWS),

#else
);
#endif
#if (SUPPORT_ASYMMETRY == 0)
lighting.radianceComplete = lighting.radianceNoPhase;
#endif
#if ENABLE_REPROJECTION
// Reproject the history at 'centerWS'.
float2 reprojPosNDC = ComputeNormalizedDeviceCoordinates(centerWS, _PrevViewProjMatrix);

// to prevent ghosting.
_VBufferLightingFeedback[uint3(posInput.positionSS, slice)] = float4(blendedRadiance, dt);
#if SUPPORT_ASYMMETRY
// TODO: how to ensure we do not divide by 0?
float3 phaseCurrFrame = lighting.radianceComplete / lighting.radianceNoPhase;
// Use max() to prevent division by 0.
float3 phaseCurrFrame = lighting.radianceComplete * rcp(max(lighting.radianceNoPhase, FLT_MIN));
#else
#endif // SUPPORT_ASYMMETRY
#else // ENABLE_REPROJECTION
#if SUPPORT_ASYMMETRY
#else // SUPPORT_ASYMMETRY
float3 blendedRadiance = lighting.radianceNoPhase;
#endif // SUPPORT_ASYMMETRY
#endif // ENABLE_REPROJECTION
// Compute the transmittance from the camera to 't0'.

float phase = CornetteShanksPhasePartConstant(asymmetry);
float phase = _CornetteShanksConstant;
// Integrate the contribution of the probe over the interval.
totalRadiance += (transmittance * phase) * scattering * blendedRadiance;
float3 probeRadiance = probeInScatteredRadiance * TransmittanceIntegralHomogeneousMedium(extinction, dt);
totalRadiance += transmittance * scattering * (phase * blendedRadiance + probeRadiance);
// Compute the optical depth up to the center of the interval.
opticalDepth += 0.5 * extinction * dt;

FillVolumetricLightingBuffer(context, featureFlags, posInput, ray);
}
#else
[numthreads(GROUP_SIZE_2D, 1, 1)]
void VolumetricLighting(uint2 groupId : SV_GroupID,
uint groupThreadId : SV_GroupThreadID)
{
// Reduce compile times if the feature is disabled.
}
#endif // SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VBuffer.hlsl


[branch] if (clampToEdge || isInBounds)
{
#if 0
// We could ignore non-linearity at the cost of accuracy.
// TODO: visually test this option (especially in motion).
#if 1
// Ignore non-linearity (for performance reasons) at the cost of accuracy.
// The results are exact for a stationary camera, but can potentially cause some judder in motion.
float w = d;
#else
// Adjust the texture coordinate for HW trilinear sampling.

float z = linearDepth;
float d = EncodeLogarithmicDepthGeneralized(z, VBufferDepthEncodingParams);
#if 0
// Ignore non-linearity (for performance reasons) at the cost of accuracy.
// The results are exact for a stationary camera, but can potentially cause some judder in motion.
float w = d;
#else
#endif
float2 weights[2], offsets[2];
BiquadraticFilter(1 - fc, weights, offsets); // Inverse-translate the filter centered around 0.5

51
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/VolumetricLighting.cs


}
class VBuffer
{
public int viewID = -1; // -1 is invalid; positive for Game Views, 0 otherwise
public long viewID = -1; // -1 is invalid; positive for Game Views, 0 otherwise
public RenderTexture[] lightingRTEX = null;
public RenderTargetIdentifier[] lightingRTID = null;

return lightingRTID[1 + ((Time.renderedFrameCount + 1) & 1)];
}
public void Create(int viewID, int w, int h, int d)
public void Create(long viewID, int w, int h, int d)
{
Debug.Assert(viewID >= 0);
Debug.Assert(w > 0 && h > 0 && d > 0);

for (int i = 0; i < n; i++)
{
this.lightingRTEX[i] = new RenderTexture(w, h, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
this.lightingRTEX[i].hideFlags = HideFlags.HideAndDontSave;
this.lightingRTEX[i].name = CoreUtils.GetRenderTargetAutoName(w, h, RenderTextureFormat.ARGBHalf, String.Format("Volumetric{0}", i));
this.lightingRTID[i] = new RenderTargetIdentifier(this.lightingRTEX[i]);
}
}

{
for (int i = 0, n = this.lightingRTEX.Length; i < n; i++)
{
this.lightingRTEX[i].Release();
if (this.lightingRTEX[i] != null)
{
this.lightingRTEX[i].Release();
}
}
}

if (preset == VolumetricLightingPreset.Off) return;
m_VolumetricLightingCS = asset.renderPipelineResources.volumetricLightingCS;
m_VBuffers = new List<VBuffer>(1);
m_VBuffers = new List<VBuffer>(0);
}
public void Cleanup()

{
if (preset == VolumetricLightingPreset.Off) return;
int viewID = camera.GetViewID();
long viewID = camera.GetViewID();
Debug.Assert(viewID >= 0);

vBuffer.Create(viewID, w, h, d);
}
VBuffer FindVBuffer(int viewID)
VBuffer FindVBuffer(long viewID)
{
Debug.Assert(viewID >= 0);

for (int i = 0; i < n; i++)
{
if (viewID == m_VBuffers[i].viewID)
// Check whether domain reload killed it...
if (viewID == m_VBuffers[i].viewID && m_VBuffers[i].lightingRTEX != null && m_VBuffers[i].lightingRTEX[0] != null)
{
vBuffer = m_VBuffers[i];
}

switch (preset)
{
case VolumetricLightingPreset.Normal:
return 128;
return 64;
return 256;
return 128;
case VolumetricLightingPreset.Off:
return 0;
default:

return depthParams;
}
void SetPreconvolvedAmbientLightProbe(CommandBuffer cmd, float asymmetry)
{
SphericalHarmonicsL2 probeSH = SphericalHarmonicMath.UndoCosineRescaling(RenderSettings.ambientProbe);
ZonalHarmonicsL2 phaseZH = ZonalHarmonicsL2.GetCornetteShanksPhaseFunction(asymmetry);
SphericalHarmonicsL2 finalSH = SphericalHarmonicMath.PremultiplyCoefficients(SphericalHarmonicMath.Convolve(probeSH, phaseZH));
cmd.SetGlobalVectorArray(HDShaderIDs._AmbientProbeCoeffs, SphericalHarmonicMath.PackCoefficients(finalSH));
}
float CornetteShanksPhasePartConstant(float asymmetry)
{
float g = asymmetry;
return (1.0f / (4.0f * Mathf.PI)) * 1.5f * (1.0f - g * g) / (2.0f + g * g);
}
public void PushGlobalParams(HDCamera camera, CommandBuffer cmd)
{
if (preset == VolumetricLightingPreset.Off) return;

VolumeProperties globalFogProperties = (globalFogComponent != null) ? globalFogComponent.volumeParameters.GetProperties()
: VolumeProperties.GetNeutralVolumeProperties();
float asymmetry = globalFogComponent != null ? globalFogComponent.volumeParameters.asymmetry : 0;
cmd.SetGlobalFloat( HDShaderIDs._GlobalFog_Asymmetry, globalFogComponent != null ? globalFogComponent.volumeParameters.asymmetry : 0);
cmd.SetGlobalFloat( HDShaderIDs._GlobalFog_Asymmetry, asymmetry);
int w = 0, h = 0, d = 0;
Vector2 scale = ComputeVBufferResolutionAndScale(preset, (int)camera.screenSize.x, (int)camera.screenSize.y, ref w, ref h, ref d);

SetPreconvolvedAmbientLightProbe(cmd, asymmetry);
cmd.SetGlobalVector( HDShaderIDs._VBufferResolution, new Vector4(w, h, 1.0f / w, 1.0f / h));
cmd.SetGlobalVector( HDShaderIDs._VBufferScaleAndSliceCount, new Vector4(scale.x, scale.y, d, 1.0f / d));
cmd.SetGlobalVector( HDShaderIDs._VBufferDepthEncodingParams, ComputeLogarithmicDepthEncodingParams(m_VBufferNearPlane, m_VBufferFarPlane, k_LogScale));

VBuffer vBuffer = FindVBuffer(camera.GetViewID());
Debug.Assert(vBuffer != null);
if (HomogeneousFog.GetGlobalFogComponent() == null)
HomogeneousFog globalFogComponent = HomogeneousFog.GetGlobalFogComponent();
float asymmetry = globalFogComponent != null ? globalFogComponent.volumeParameters.asymmetry : 0;
if (globalFogComponent == null)
{
// Clear the render target instead of running the shader.
// CoreUtils.SetRenderTarget(cmd, GetVBufferLightingIntegral(viewOffset), ClearFlag.Color, CoreUtils.clearColorAllBlack);

Vector4 offset = new Vector4(xySeq[sampleIndex].x, xySeq[sampleIndex].y, zSeq[sampleIndex], rfc);
// TODO: set 'm_VolumetricLightingPreset'.
cmd.SetComputeFloatParam( m_VolumetricLightingCS, HDShaderIDs._CornetteShanksConstant, CornetteShanksPhasePartConstant(asymmetry));
cmd.SetComputeVectorParam( m_VolumetricLightingCS, HDShaderIDs._VBufferSampleOffset, offset);
cmd.SetComputeMatrixParam( m_VolumetricLightingCS, HDShaderIDs._VBufferCoordToViewDirWS, transform);
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLightingIntegral, vBuffer.GetLightingIntegralBuffer()); // Write

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Builtin/BuiltinData.cs


return RenderTextureFormat.ARGB32;
}
public static RenderTextureReadWrite GetShadowMaskBufferReadWrite()
public static bool GetShadowMaskSRGBFlag()
return RenderTextureReadWrite.Linear;
return false;
}
public static RenderTextureFormat GetVelocityBufferFormat()

public static RenderTextureReadWrite GetVelocityBufferReadWrite()
public static bool GetVelocityBufferSRGBFlag()
return RenderTextureReadWrite.Linear;
return false;
}
public static RenderTextureFormat GetDistortionBufferFormat()

}
public static RenderTextureReadWrite GetDistortionBufferReadWrite()
public static bool GetDistortionBufferSRGBFlag()
return RenderTextureReadWrite.Linear;
return false;
}
}
}

16
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Builtin/BuiltinData.cs.hlsl


//
#define DEBUGVIEW_BUILTIN_BUILTINDATA_OPACITY (100)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_BAKE_DIFFUSE_LIGHTING (101)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK0 (102)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK1 (103)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK2 (104)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK3 (105)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK_0 (102)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK_1 (103)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK_2 (104)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK_3 (105)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_COLOR (106)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_INTENSITY (107)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_VELOCITY (108)

result = builtindata.bakeDiffuseLighting;
needLinearToSRGB = true;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK0:
case DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK_0:
case DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK1:
case DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK_1:
case DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK2:
case DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK_2:
case DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK3:
case DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK_3:
result = builtindata.shadowMask3.xxx;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_COLOR:

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs


[SurfaceDataAttributes("Normal", true)]
public Vector4 normalWS;
[SurfaceDataAttributes("Mask", true)]
public Vector4 mask;
public Vector4 mask;
[SurfaceDataAttributes("HTileMask")]
public uint HTileMask;
};
[GenerateHLSL(PackingRules.Exact)]

static public int GetMaterialDBufferCount() { return (int)DBufferMaterial.Count; }
static RenderTextureFormat[] m_RTFormat = { RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32 };
static RenderTextureReadWrite[] m_RTReadWrite = { RenderTextureReadWrite.sRGB, RenderTextureReadWrite.Linear, RenderTextureReadWrite.Linear };
static bool[] m_sRGBFlags= { true, false, false };
static public void GetMaterialDBufferDescription(out RenderTextureFormat[] RTFormat, out RenderTextureReadWrite[] RTReadWrite)
static public void GetMaterialDBufferDescription(out RenderTextureFormat[] RTFormat, out bool[] sRGBFlags)
RTReadWrite = m_RTReadWrite;
sRGBFlags = m_sRGBFlags;
}
}
}

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


// UnityEngine.Experimental.Rendering.HDPipeline.Decal+DecalSurfaceData: static fields
//
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_BASE_COLOR (10000)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_NORMAL_WS (10001)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_NORMAL (10001)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_HTILE_MASK (10003)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Decal+DBufferMaterial: static fields

float4 baseColor;
float4 normalWS;
float4 mask;
uint HTileMask;
};
//

result = decalsurfacedata.baseColor.xyz;
needLinearToSRGB = true;
break;
case DEBUGVIEW_DECAL_DECALSURFACEDATA_NORMAL_WS:
case DEBUGVIEW_DECAL_DECALSURFACEDATA_NORMAL:
break;
case DEBUGVIEW_DECAL_DECALSURFACEDATA_HTILE_MASK:
result = GetIndexColor(decalsurfacedata.HTileMask);
break;
}
}

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.hlsl


#include "Decal.cs.hlsl"
#include "CoreRP/ShaderLibrary/Debug.hlsl"
#include "Decal.cs.hlsl"
#define DBufferType0 float4
#define DBufferType1 float4

UNITY_INSTANCING_BUFFER_END(matrix)
RW_TEXTURE2D(float, _DecalHTile); // DXGI_FORMAT_R8_UINT is not supported by Unity
TEXTURE2D(_DecalHTileTexture);
// Must be in sync with RT declared in HDRenderPipeline.cs ::Rebuild
void EncodeIntoDBuffer( DecalSurfaceData surfaceData,

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalData.hlsl


#include "CoreRP/ShaderLibrary/Packing.hlsl"
#include "CoreRP/ShaderLibrary/Sampling/SampleUVMapping.hlsl"
void GetSurfaceData(float2 texCoordDS, float3x3 decalToWorld, out DecalSurfaceData surfaceData)
void GetSurfaceData(float2 texCoordDS, float4x4 decalToWorld, out DecalSurfaceData surfaceData)
float totalBlend = _DecalBlend;
surfaceData.HTileMask = 0;
float totalBlend = _DecalBlend * clamp(decalToWorld[0][3], 0.0f, 1.0f);
surfaceData.HTileMask |= DBUFFERHTILEBIT_DIFFUSE;
surfaceData.normalWS.xyz = mul(decalToWorld, SAMPLE_UVMAPPING_NORMALMAP(_NormalMap, sampler_NormalMap, texCoord, 1)) * 0.5f + 0.5f;
surfaceData.normalWS.xyz = mul((float3x3)decalToWorld, SAMPLE_UVMAPPING_NORMALMAP(_NormalMap, sampler_NormalMap, texCoord, 1)) * 0.5f + 0.5f;
surfaceData.HTileMask |= DBUFFERHTILEBIT_NORMAL;
surfaceData.HTileMask |= DBUFFERHTILEBIT_MASK;
}

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


#include "Decal.hlsl"
DECLARE_DBUFFER_TEXTURE(_DBufferTexture);
DECLARE_DBUFFER_TEXTURE(_DBufferTexture);
void AddDecalContribution(uint2 unPositionSS, inout SurfaceData surfaceData)
{

FETCH_DBUFFER(DBuffer, _DBufferTexture, unPositionSS);
DecalSurfaceData decalSurfaceData;
DECODE_FROM_DBUFFER(DBuffer, decalSurfaceData);
uint mask = UnpackByte(_DecalHTile[unPositionSS / 8]);
uint mask = UnpackByte(LOAD_TEXTURE2D(_DecalHTileTexture, unPositionSS / 8).x);
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
if(mask & DBUFFERHTILEBIT_DIFFUSE)

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/RuntimeFilterIBL.cs


m_GgxIblSampleData.autoGenerateMips = false;
m_GgxIblSampleData.enableRandomWrite = true;
m_GgxIblSampleData.filterMode = FilterMode.Point;
m_GgxIblSampleData.name = CoreUtils.GetRenderTargetAutoName(m_GgxIblMaxSampleCount, k_GgxIblMipCountMinusOne, RenderTextureFormat.ARGBHalf, "GGXIblSampleData");
m_GgxIblSampleData.Create();
m_ComputeGgxIblSampleDataCS.SetTexture(m_ComputeGgxIblSampleDataKernel, "output", m_GgxIblSampleData);

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


_LayerInfluenceMaskMap("LayerInfluenceMaskMap", 2D) = "white" {}
[ToggleUI] _UseHeightBasedBlend("UseHeightBasedBlend", Float) = 0.0
_HeightOffset0("Height Offset0", Float) = 0
_HeightOffset1("Height Offset1", Float) = 0
_HeightOffset2("Height Offset2", Float) = 0
_HeightOffset3("Height Offset3", Float) = 0
_HeightTransition("Height Transition", Range(0, 1.0)) = 0.0
[ToggleUI] _UseDensityMode("Use Density mode", Float) = 0.0

[ToggleUI] _EnableBlendModePreserveSpecularLighting("Enable Blend Mode Preserve Specular Lighting", Float) = 1.0
[ToggleUI] _DoubleSidedEnable("Double sided enable", Float) = 0.0
[Enum(Flip, 0, Mirror, 1)] _DoubleSidedNormalMode("Double sided normal mode", Float) = 1
[Enum(Flip, 0, Mirror, 1, None, 2)] _DoubleSidedNormalMode("Double sided normal mode", Float) = 1
[Enum(Subsurface Scattering and Transmissison, 0, Standard, 1)] _MaterialID("MaterialId", Int) = 1 // MaterialId.Standard
[Enum(Both, 0, SSS only, 1, Transmission only, 2)] _SSSAndTransmissionType("SSSandTransmissionType", Int) = 0 // SSSandTransmissionType.Both
[Enum(Subsurface Scattering, 0, Standard, 1, Translucent, 5)] _MaterialID("MaterialId", Int) = 1 // MaterialId.Standard
[ToggleUI] _TransmissionEnable("_TransmissionEnable", Float) = 1.0
[Enum(None, 0, Vertex displacement, 1, Pixel displacement, 2)] _DisplacementMode("DisplacementMode", Int) = 0
[ToggleUI] _DisplacementLockObjectScale("displacement lock object scale", Float) = 1.0

HLSLPROGRAM
#pragma multi_compile _ DEBUG_DISPLAY
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ DYNAMICLIGHTMAP_ON

#include "../../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#include "../../Debug/DebugDisplay.hlsl"
#endif
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "LayeredLitData.hlsl"

HLSLPROGRAM
#pragma multi_compile _ DEBUG_DISPLAY
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ DYNAMICLIGHTMAP_ON

#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "GBufferDebugDisplay" // Name is not used
Tags{ "LightMode" = "GBufferDebugDisplay" } // This will be only for opaque object based on the RenderQueue index
Cull [_CullMode]
Stencil
{
WriteMask [_StencilWriteMask]
Ref [_StencilRef]
Comp Always
Pass Replace
}
HLSLPROGRAM
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define DEBUG_DISPLAY
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#endif
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "LayeredLitData.hlsl"

HLSLPROGRAM
#pragma multi_compile _ DEBUG_DISPLAY
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ DYNAMICLIGHTMAP_ON

#define SHADERPASS SHADERPASS_FORWARD
#include "../../ShaderVariables.hlsl"
#include "../../Lighting/Lighting.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassForward.hlsl"
ENDHLSL
}
Pass
{
Name "ForwardDebugDisplay" // Name is not used
Tags{ "LightMode" = "ForwardDebugDisplay" } // This will be only for transparent object based on the RenderQueue index
Stencil
{
WriteMask [_StencilWriteMask]
Ref [_StencilRef]
Comp Always
Pass Replace
}
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]
Cull[_CullMode]
HLSLPROGRAM
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
// #include "../../Lighting/Forward.hlsl"
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST
#define DEBUG_DISPLAY
#define SHADERPASS SHADERPASS_FORWARD
#include "../../ShaderVariables.hlsl"
#ifdef DEBUG_DISPLAY
#endif
#include "../../Lighting/Lighting.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "LayeredLitData.hlsl"

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitData.hlsl


// Returns layering blend mask after application of height based blend.
float4 ApplyHeightBlend(float4 heights, float4 blendMask)
{
// Add offsets for all the layers.
heights = heights + float4(_HeightOffset0, _HeightOffset1, _HeightOffset2, _HeightOffset3);
// We need to mask out inactive layers so that their height does not impact the result.
float4 maskedHeights = heights * blendMask.argb;

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitDataDisplacement.hlsl


// Since the result is used as a 'depthOffsetVS', it needs to be positive, so we flip the sign. { height = -height + 1 }.
float verticalDisplacement = maxHeight - height * maxHeight;
return verticalDisplacement / max(NdotV, 0.001);
return verticalDisplacement / ClampNdotV(NdotV);
#else
return 0.0;
#endif

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

正在加载...
取消
保存