浏览代码

Resolve merge conflicts

/main
egomeh 6 年前
当前提交
e7c59a70
共有 217 个文件被更改,包括 2202 次插入3453 次删除
  1. 2
      README.md
  2. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2203_PlanarProbes.png
  3. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2207_ReflectionProbeVFace.png
  4. 18
      TestProjects/HDRP_Tests/ProjectSettings/EditorBuildSettings.asset
  5. 15
      com.unity.render-pipelines.core/CoreRP/CoreResources/TexturePadding.cs
  6. 29
      com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorUtils.cs
  7. 10
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/BSDF.hlsl
  8. 34
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/CommonLighting.hlsl
  9. 24
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/CommonMaterial.hlsl
  10. 10
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/ImageBasedLighting.hlsl
  11. 65
      com.unity.render-pipelines.core/CoreRP/Shadow/AdditionalShadowData.cs
  12. 2
      com.unity.render-pipelines.core/CoreRP/Textures/RTHandleSystem.cs
  13. 3
      com.unity.render-pipelines.core/CoreRP/Utilities/CoreUtils.cs
  14. 21
      com.unity.render-pipelines.high-definition/CHANGELOG.md
  15. 8
      com.unity.render-pipelines.high-definition/HDRP/Camera/HDCamera.cs
  16. 2
      com.unity.render-pipelines.high-definition/HDRP/Debug/DebugDisplay.cs
  17. 2
      com.unity.render-pipelines.high-definition/HDRP/Debug/LightingDebug.cs
  18. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/AssetProcessors/NormalMapFilteringTexturePostprocessor.cs.meta
  19. 66
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDAdditionalLightDataEditor.cs
  20. 25
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightEditor.cs
  21. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightExplorerExtension.cs
  22. 3
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/EditorReflectionSystem.cs
  23. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Gizmos.cs
  24. 34
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Preview.cs
  25. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.ProbeUtility.cs
  26. 133
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs
  27. 532
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.Drawers.cs
  28. 102
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.cs
  29. 89
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeEditor.cs
  30. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeEditor.cs.meta
  31. 212
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Handles.cs
  32. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Handles.cs.meta
  33. 121
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.cs
  34. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.cs.meta
  35. 109
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/SerializedHDReflectionProbe.cs
  36. 81
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/SerializedPlanarReflectionProbe.cs
  37. 163
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Drawers.cs
  38. 311
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Handles.cs
  39. 20
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.cs
  40. 135
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/ProxyVolumeUI.cs
  41. 9
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/ReflectionProxyVolumeComponentUI.cs
  42. 29
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/SerializedInfluenceVolume.cs
  43. 6
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Volumetric/DensityVolumeTextureTool.cs
  44. 14
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/BaseLitUI.cs
  45. 4
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Unlit/BaseUnlitUI.cs
  46. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDAssetFactory.cs
  47. 1
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDEditorUtils.cs
  48. 3
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/SharedCode.template.hlsl
  49. 1
      com.unity.render-pipelines.high-definition/HDRP/Editor/Upgraders/UpgradeMenuItem.cs
  50. 154
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Light/HDAdditionalLightData.cs
  51. 3
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightEvaluation.hlsl
  52. 332
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoop.cs
  53. 61
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/HDAdditionalReflectionData.cs
  54. 26
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/HDProbe.cs
  55. 19
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/PlanarReflectionProbe.cs
  56. 29
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ProbeWrapper.cs
  57. 10
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ReflectionSystem.cs
  58. 167
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ReflectionSystemInternal.cs
  59. 14
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ReflectionSystemParameters.cs
  60. 16
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/Volumes/InfluenceVolume.cs
  61. 8
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumetricLighting.cs
  62. 6
      com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLitData.hlsl
  63. 10
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.hlsl
  64. 20
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitData.hlsl
  65. 16
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitDataIndividualLayer.hlsl
  66. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/Material.hlsl
  67. 40
      com.unity.render-pipelines.high-definition/HDRP/Material/MaterialEvaluation.hlsl
  68. 12
      com.unity.render-pipelines.high-definition/HDRP/Material/PreIntegratedFGD/PreIntegratedFGD.cs
  69. 10
      com.unity.render-pipelines.high-definition/HDRP/Material/PreIntegratedFGD/PreIntegratedFGD.hlsl
  70. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/PreIntegratedFGD/preIntegratedFGD_CharlieFabricLambert.shader
  71. 45
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDRenderPipeline.cs
  72. 4
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDRenderPipelineAsset.cs
  73. 3
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDStringConstants.cs
  74. 8
      com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset
  75. 8
      com.unity.render-pipelines.high-definition/HDRP/RenderPipelineResources/RenderPipelineResources.cs
  76. 3
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/VaryingMesh.hlsl
  77. 1
      com.unity.render-pipelines.high-definition/HDRP/ShaderVariables.hlsl
  78. 10
      com.unity.render-pipelines.lightweight/CHANGELOG.md
  79. 20
      com.unity.render-pipelines.lightweight/LWRP/DefaultRendererSetup.cs
  80. 2
      com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGUI/LightweightShaderGUI.cs
  81. 4
      com.unity.render-pipelines.lightweight/LWRP/IRendererSetup.cs
  82. 80
      com.unity.render-pipelines.lightweight/LWRP/LightweightPipeline.cs
  83. 4
      com.unity.render-pipelines.lightweight/LWRP/Passes/BeginXRRenderingPass.cs
  84. 4
      com.unity.render-pipelines.lightweight/LWRP/Passes/CopyColorPass.cs
  85. 4
      com.unity.render-pipelines.lightweight/LWRP/Passes/CopyDepthPass.cs
  86. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/CreateLightweightRenderTexturesPass.cs
  87. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/DepthOnlyPass.cs
  88. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/DirectionalShadowsPass.cs
  89. 4
      com.unity.render-pipelines.lightweight/LWRP/Passes/DrawSkyboxPass.cs
  90. 4
      com.unity.render-pipelines.lightweight/LWRP/Passes/EndXRRenderingPass.cs
  91. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/FinalBlitPass.cs
  92. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/LightweightForwardPass.cs
  93. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/LocalShadowsPass.cs
  94. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/OpaquePostProcessPass.cs
  95. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/RenderOpaqueForwardPass.cs
  96. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/RenderTransparentForwardPass.cs
  97. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/SceneViewDepthCopy.cs
  98. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/ScreenSpaceShadowResolvePass.cs
  99. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/ScriptableRenderPass.cs
  100. 2
      com.unity.render-pipelines.lightweight/LWRP/Passes/SetupForwardRenderingPass.cs

2
README.md


[High Definition Pipeline Blogpost](https://blogs.unity3d.com/2018/03/16/the-high-definition-render-pipeline-focused-on-visual-quality/)
## How to use the latest version
__Note: The Master branch is our current development branch and may not work on the latest publicly available version of Unity. You should always use the latest release tag and latest Unity beta version for testing purposes.__
__Note: The Master branch is our current development branch and may not work on the latest publicly available version of Unity. To determine which version of SRP you should use with your version of Unity, go to Package Manager (Window > Package Manager) to see what versions of SRP are available for your version of Unity Editor. Then you can search the Tags tab of the Branch dropdown in the SRP GitHub for that tag number.__
To use the latest version of the SRP, follow the instructions below:
This repository consists of a folder that should be cloned outside the Assets\ folder of your Unity project. We recommend creating a new project to test SRP. Do not clone this repo into an existing project unless you want to break it, or unless you are updating to a newer version of the SRP repo.

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

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

18
TestProjects/HDRP_Tests/ProjectSettings/EditorBuildSettings.asset


path: Assets/GraphicTests/Scenes/1x_Materials/1401_StackLit.unity
guid: 695dac9017b946a49a338d466a6d50ff
- enabled: 1
path: Assets/GraphicTests/Scenes/1x_Materials/1501_Fabric.unity
guid: ce2b258da0df8d245b659390b6c2ac51
- enabled: 1
path: Assets/GraphicTests/Scenes/2x_Lighting/2001_Dynamic_Directional.unity
guid: 09baf18a7e1f6584f86675e6a2141c66
- enabled: 1

path: Assets/GraphicTests/Scenes/2x_Lighting/2202_ReflectionProbes_Volume.unity
guid: 9b3132db666b3ae48aa17349ab100118
- enabled: 1
path: Assets/GraphicTests/Scenes/2x_Lighting/2203_PlanarProbes.unity
guid: b8fa5b1235e91884799163adaf34e5d6
- enabled: 1
path: Assets/GraphicTests/Scenes/2x_Lighting/2204_ReflectionProbes_Lights.unity
guid: 21d198bbbf9143d40b227ad2fe71706f
- enabled: 1
path: Assets/GraphicTests/Scenes/2x_Lighting/2206_PlanarReflectionVFace.unity
guid: d4d352e2cbfbfac4686e77b69fe84ec0
- enabled: 1
path: Assets/GraphicTests/Scenes/2x_Lighting/2207_ReflectionProbeVFace.unity
guid: 4814073d6e6ec404bba1f26bec73307a
- enabled: 1
- enabled: 1
path: Assets/GraphicTests/Scenes/2x_Lighting/2401_Light_on_Tesselation.unity
guid: 3f6529c22f7d2ca46814b2e7afd04ef9
- enabled: 1
path: Assets/GraphicTests/Scenes/2x_Lighting/2501_Instancing_Lighting.unity
guid: d841ad64fdc2ae14ba996e30fe86b901

15
com.unity.render-pipelines.core/CoreRP/CoreResources/TexturePadding.cs


int m_KMainTop;
int m_KMainRight;
// Avoid garbage generated by .SetComputeIntParams methods (using params int[] will generate an array on the fly)
int[] m_IntParams = new int[2];
public TexturePadding(ComputeShader cs)
{
m_CS = cs;

{
if (from.width < to.width)
{
cmd.SetComputeIntParams(m_CS, _RectOffset, from.width, 0);
m_IntParams[0] = from.width;
m_IntParams[1] = 0;
cmd.SetComputeIntParams(m_CS, _RectOffset, m_IntParams);
cmd.SetComputeIntParams(m_CS, _RectOffset, 0, from.height);
m_IntParams[0] = 0;
m_IntParams[1] = from.height;
cmd.SetComputeIntParams(m_CS, _RectOffset, m_IntParams);
cmd.SetComputeIntParams(m_CS, _RectOffset, from.width, from.height);
m_IntParams[0] = from.width;
m_IntParams[1] = from.height;
cmd.SetComputeIntParams(m_CS, _RectOffset, m_IntParams);
cmd.SetComputeTextureParam(m_CS, m_KMainTopRight, _InOutTexture, inOutTexture);
cmd.DispatchCompute(m_CS, m_KMainTopRight, to.width - from.width, to.height - from.height, 1);
}

29
com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorUtils.cs


throw new System.ArgumentException("Colors must be a 2x3 array.");
GUILayout.BeginVertical();
if(label != GUIContent.none)
EditorGUILayout.LabelField(label);
++EditorGUI.indentLevel;
var rect = GUILayoutUtility.GetRect(0, float.MaxValue, EditorGUIUtility.singleLineHeight, EditorGUIUtility.singleLineHeight);
Rect rect = EditorGUI.IndentedRect(GUILayoutUtility.GetRect(0, float.MaxValue, EditorGUIUtility.singleLineHeight, EditorGUIUtility.singleLineHeight));
if (label != GUIContent.none)
{
var labelRect = rect;
labelRect.x -= 12f;
labelRect.width = EditorGUIUtility.labelWidth;
EditorGUI.LabelField(labelRect, label);
rect.x += EditorGUIUtility.labelWidth - 12f;
rect.width -= EditorGUIUtility.labelWidth - 12f;
}
var v = positive.vector3Value;
EditorGUI.BeginChangeCheck();
v = DrawVector3(rect, k_DrawVector6_Label, v, min, max, false, colors == null ? null : colors[0]);

GUILayout.Space(EditorGUIUtility.standardVerticalSpacing);
rect = GUILayoutUtility.GetRect(0, float.MaxValue, EditorGUIUtility.singleLineHeight, EditorGUIUtility.singleLineHeight);
rect = EditorGUI.IndentedRect(GUILayoutUtility.GetRect(0, float.MaxValue, EditorGUIUtility.singleLineHeight, EditorGUIUtility.singleLineHeight));
rect.x += EditorGUIUtility.labelWidth - 12f;
rect.width -= EditorGUIUtility.labelWidth - 12f;
--EditorGUI.indentLevel;
GUILayout.EndVertical();
}

rect = EditorGUI.IndentedRect(rect);
//rect = EditorGUI.IndentedRect(rect);
float fieldWidth = rect.width / 3f;
EditorGUI.BeginChangeCheck();
EditorGUI.MultiFloatField(rect, labels, multifloat);

//Suffix is a hack as sublabel only work with 1 character
if(addMinusPrefix)
{
Rect suffixRect = new Rect(rect.x-33, rect.y, 100, rect.height);
Rect suffixRect = new Rect(rect.x-19, rect.y, 100, rect.height);
suffixRect.x += fieldWidth + .5f;
suffixRect.x += fieldWidth + .66f;
}
}

if (colors.Length != 3)
throw new System.ArgumentException("colors must have 3 elements.");
Rect suffixRect = new Rect(rect.x - 23, rect.y, 100, rect.height);
Rect suffixRect = new Rect(rect.x - 8, rect.y, 100, rect.height);
GUIStyle colorMark = new GUIStyle(EditorStyles.label);
colorMark.normal.textColor = colors[0];
EditorGUI.LabelField(suffixRect, "|", colorMark);

10
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/BSDF.hlsl


}
//-----------------------------------------------------------------------------
// Cloth
// Fabric
//-----------------------------------------------------------------------------
// Ref: https://knarkowicz.wordpress.com/2018/01/04/cloth-shading/

return 1.0 / (4.0 * (NdotL + NdotV - NdotL * NdotV));
}
// A diffuse term use with cloth done by tech artist - empirical
real ClothLambertNoPI(real roughness)
// A diffuse term use with fabric done by tech artist - empirical
real FabricLambertNoPI(real roughness)
real ClothLambert(real roughness)
real FabricLambert(real roughness)
return INV_PI * ClothLambertNoPI(roughness);
return INV_PI * FabricLambertNoPI(roughness);
}

34
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/CommonLighting.hlsl


return area;
}
// ref: Practical Realtime Strategies for Accurate Indirect Occlusion
// http://blog.selfshadow.com/publications/s2016-shading-course/#course_content
// Original Cone-Cone method with cosine weighted assumption (p129 s2016_pbs_activision_occlusion)
real GetSpecularOcclusionFromBentAO(real3 V, real3 bentNormalWS, real3 normalWS, real ambientOcclusion, real roughness)
{
// Retrieve cone angle
// Ambient occlusion is cosine weighted, thus use following equation. See slide 129
real cosAv = sqrt(1.0 - ambientOcclusion);
roughness = max(roughness, 0.01); // Clamp to 0.01 to avoid edge cases
real cosAs = exp2((-log(10.0) / log(2.0)) * Sq(roughness));
real cosB = dot(bentNormalWS, reflect(-V, normalWS));
return SphericalCapIntersectionSolidArea(cosAv, cosAs, cosB) / (TWO_PI * (1.0 - cosAs));
}
// Ref: Steve McAuley - Energy-Conserving Wrapped Diffuse
real ComputeWrappedDiffuseLighting(real NdotL, real w)
{

real3 localY = cross(localZ, localX);
return real3x3(localX, localY, localZ);
}
// Construct a right-handed view-dependent orthogonal basis around the normal:
// b0-b2 is the view-normal aka reflection plane.
real3x3 GetOrthoBasisViewNormal(real3 V, real3 N, real unclampedNdotV, bool testSingularity = false)
{
real3x3 orthoBasisViewNormal;
if (testSingularity && (abs(1.0 - unclampedNdotV) <= FLT_EPS))
{
// In this case N == V, and azimuth orientation around N shouldn't matter for the caller,
// we can use any quaternion-based method, like Frisvad or Reynold's (Pixar):
orthoBasisViewNormal = GetLocalFrame(N);
}
else
{
orthoBasisViewNormal[0] = normalize(V - N * unclampedNdotV);
orthoBasisViewNormal[2] = N;
orthoBasisViewNormal[1] = cross(orthoBasisViewNormal[2], orthoBasisViewNormal[0]);
}
return orthoBasisViewNormal;
}
#endif // UNITY_COMMON_LIGHTING_INCLUDED

24
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/CommonMaterial.hlsl


#define UNITY_COMMON_MATERIAL_INCLUDED
//-----------------------------------------------------------------------------
// Define constants
//-----------------------------------------------------------------------------
#define DEFAULT_SPECULAR_VALUE 0.04
//-----------------------------------------------------------------------------
// Helper functions for roughness
//-----------------------------------------------------------------------------

void ConvertRoughnessToAnisotropy(real roughnessT, real roughnessB, out real anisotropy)
{
anisotropy = ((roughnessT - roughnessB) / (roughnessT + roughnessB + 0.0001));
anisotropy = ((roughnessT - roughnessB) / max(roughnessT + roughnessB, 0.0001));
}
// Same as ConvertAnisotropyToRoughness but

return sqrt(2.0 / (variance + 2.0));
}
// Normal Map Filtering - This must match HDRP\Editor\AssetProcessors\NormalMapFilteringTexturePostprocessor.cs - highestVarianceAllowed (TODO: Move in core)
#define NORMALMAP_HIGHEST_VARIANCE 0.03125
float DecodeVariance(float gradientW)
{
return gradientW * NORMALMAP_HIGHEST_VARIANCE;
}
// Return modified perceptualSmoothness based on provided variance (get from GeometricNormalVariance + TextureNormalVariance)
float NormalFiltering(float perceptualSmoothness, float variance, float threshold)
{

return 1.0 - RoughnessToPerceptualRoughness(sqrt(squaredRoughness));
return RoughnessToPerceptualSmoothness(sqrt(squaredRoughness));
}
// Reference: Error Reduction and Simplification for Shading Anti-Aliasing

// like Toksvig.
float TextureNormalVariance(float avgNormalLength)
{
float variance = 0.0;
if (avgNormalLength < 1.0)
{
float avgNormLen2 = avgNormalLength * avgNormalLength;

// Relationship between gaussian lobe and vMF lobe is 2 * variance = 1 / (2 * kappa) = roughness^2
// (Equation 36 of Normal map filtering based on The Order : 1886 SIGGRAPH course notes implementation).
// So to get variance we must use variance = 1 / (4 * kappa)
return 0.25 * kappa;
variance = 0.25 / kappa;
return 0.0;
return variance;
}
float TextureNormalFiltering(float perceptualSmoothness, float avgNormalLength, float threshold)

10
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/ImageBasedLighting.hlsl


#endif
#if !defined SHADER_API_GLES
real4 IntegrateCharlieAndClothLambertFGD(real3 V, real3 N, real roughness, uint sampleCount = 8192)
real4 IntegrateCharlieAndFabricLambertFGD(real3 V, real3 N, real roughness, uint sampleCount = 8192)
{
real NdotV = ClampNdotV(dot(N, V));
real4 acc = real4(0.0, 0.0, 0.0, 0.0);

acc.y += weightOverPdf;
}
// for cloth Lambert we still use a Cosine importance sampling
// for Fabric Lambert we still use a Cosine importance sampling
real clothLambert = ClothLambertNoPI(roughness);
acc.z += clothLambert * weightOverPdf;
real fabricLambert = FabricLambertNoPI(roughness);
acc.z += fabricLambert * weightOverPdf;
}
}

}
#else
// Not supported due to lack of random library in GLES 2
#define IntegrateCharlieAndClothLambertFGD ERROR_ON_UNSUPPORTED_FUNCTION(IntegrateCharlieAndClothLambertFGD)
#define IntegrateCharlieAndFabricLambertFGD ERROR_ON_UNSUPPORTED_FUNCTION(IntegrateCharlieAndFabricLambertFGD)
#endif
uint GetIBLRuntimeFilterSampleCount(uint mipLevel)

65
com.unity.render-pipelines.core/CoreRP/Shadow/AdditionalShadowData.cs


[Range(0.0f, 1.0f)]
public float shadowDimmer = 1.0f;
public float shadowFadeDistance = 10000.0f;
public bool contactShadows = false;
public bool contactShadows = false;
public float viewBiasMin = 0.5f;
public float viewBiasMax = 10.0f;
public float viewBiasMin = 0.5f;
public float viewBiasMax = 10f;
public float viewBiasScale = 1.0f;
public float normalBiasMin = 0.2f;
public float normalBiasMax = 4.0f;
public float viewBiasScale = 1.0f;
public float normalBiasMin = 0.2f;
public float normalBiasMax = 4.0f;
public float normalBiasScale = 1.0f;
public bool sampleBiasScale = true;
public bool edgeLeakFixup = false; // Causes large banding artifacts
public float normalBiasScale = 1.0f;
public bool sampleBiasScale = true;
public bool edgeLeakFixup = false; // Causes large banding artifacts
public float edgeTolerance = 1.0f;
public float edgeTolerance = 1.0f;
// shadow related parameters

[HideInInspector, SerializeField]
private float[] shadowCascadeBorders = new float[4] { 0.2f, 0.2f, 0.2f, 0.2f };
[HideInInspector, SerializeField]
private int shadowAlgorithm;
private int shadowAlgorithm = 0;
private int shadowVariant;
private int shadowVariant = 0;
private int shadowPrecision;
private int shadowPrecision = 0;
private ShadowData shadowData;
private ShadowData shadowData = new ShadowData();
[HideInInspector, SerializeField]
private ShadowData[] shadowDatas = new ShadowData[0];

}
return -1;
}
public void CopyTo(AdditionalShadowData data)
{
data.shadowResolution = shadowResolution;
data.shadowDimmer = shadowDimmer;
data.shadowFadeDistance = shadowFadeDistance;
data.contactShadows = contactShadows;
data.viewBiasMin = viewBiasMin;
data.viewBiasMax = viewBiasMax;
data.viewBiasScale = viewBiasScale;
data.normalBiasMin = normalBiasMin;
data.normalBiasMax = normalBiasMax;
data.normalBiasScale = normalBiasScale;
data.sampleBiasScale = sampleBiasScale;
data.edgeLeakFixup = edgeLeakFixup;
data.edgeToleranceNormal = edgeToleranceNormal;
data.edgeTolerance = edgeTolerance;
data.shadowCascadeCount = shadowCascadeCount;
data.shadowCascadeRatios = new float[shadowCascadeRatios.Length];
shadowCascadeRatios.CopyTo(data.shadowCascadeRatios, 0);
data.shadowCascadeBorders = new float[shadowCascadeBorders.Length];
shadowCascadeBorders.CopyTo(data.shadowCascadeBorders, 0);
data.shadowAlgorithm = shadowAlgorithm;
data.shadowVariant = shadowVariant;
data.shadowPrecision = shadowPrecision;
data.shadowData = shadowData;
data.shadowDatas = new ShadowData[shadowDatas.Length];
shadowDatas.CopyTo(data.shadowDatas, 0);
}
}
#if UNITY_EDITOR

void OnEnable()
{
m_ShadowAlgorithm = serializedObject.FindProperty("shadowAlgorithm");
m_ShadowVariant = serializedObject.FindProperty("shadowVariant");
m_ShadowData = serializedObject.FindProperty("shadowData");
m_ShadowDatas = serializedObject.FindProperty("shadowDatas");
m_ShadowCascadeCount = serializedObject.FindProperty("shadowCascadeCount");
m_ShadowVariant = serializedObject.FindProperty("shadowVariant");
m_ShadowData = serializedObject.FindProperty("shadowData");
m_ShadowDatas = serializedObject.FindProperty("shadowDatas");
m_ShadowCascadeCount = serializedObject.FindProperty("shadowCascadeCount");
m_ShadowCascadeRatios = serializedObject.FindProperty("shadowCascadeRatios");
m_ShadowCascadeBorders = serializedObject.FindProperty("shadowCascadeBorders");
}

2
com.unity.render-pipelines.core/CoreRP/Textures/RTHandleSystem.cs


public void DemandResize(RTHandle rth)
{
Assert.IsTrue(m_ResizeOnDemandRTs.Contains(rth), string.Format("The RTHandle {0} is not an resize on demand handle in this RTHandleSystem. Please call SwitchToResizeOnDemand(rth, true) before resizing on demand.", rth));
Assert.IsTrue(m_ResizeOnDemandRTs.Contains(rth), "The RTHandle is not an resize on demand handle in this RTHandleSystem. Please call SwitchToResizeOnDemand(rth, true) before resizing on demand.");
for (int i = 0, c = (int)RTCategory.Count; i < c; ++i)
{

3
com.unity.render-pipelines.core/CoreRP/Utilities/CoreUtils.cs


public static class CoreUtils
{
// Keep a reference to default values for Reset purpose
static public AdditionalShadowData s_DefaultAdditionalShadowData { get { return ComponentSingleton<AdditionalShadowData>.instance; } }
// Data useful for various cubemap processes.
// Ref: https://msdn.microsoft.com/en-us/library/windows/desktop/bb204881(v=vs.85).aspx
static public readonly Vector3[] lookAtList =

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


## [3.3.0-preview]
### Added
- Added an error message to say to use Metal or Vulkan when trying to use OpenGL API
- Added a new Fabric shader model that supports Silk and Cotton/Wool
- Added a new HDRP Lighting Debug mode to visualize Light Volumes for Point, Spot, Line, Rectangular and Reflection Probes
### Fixed
- Fix an issue where the screen where darken when rendering camera preview
- Fix display correct target platform when showing message to inform user that a platform is not supported
- Remove workaround for metal and vulkan in normal buffer encoding/decoding
- Fixed an issue with color picker not working in forward
- Fixed an issue where reseting HDLight do not reset all of its parameters
### Changed
- Changed default reflection probe to be 256x256x6 and array size to be 64
- Removed dependence on the NdotL for thickness evaluation for translucency (based on artist's input)
- Increased the precision when comparing Planar or HD reflection probe volumes
- Remove various GC alloc in C#. Slightly better performance
## [3.2.0-preview]
### Added

- Fix planar reflections that were not working with tile/cluster (olbique matrix)
- Fix debug menu at runtime not working after nested prefab PR come to trunk
- Fix scrolling issue in density volume
- Fix an issue where the screen where darken when rendering camera preview
- Fix display correct target platform when showing message to inform user that a platform is not supported
- Remove workaround for metal and vulkan in normal buffer encoding/decoding
### Changed
- Shader code refactor: Split MaterialUtilities file in two parts BuiltinUtilities (independent of FragInputs) and MaterialUtilities (Dependent of FragInputs)

8
com.unity.render-pipelines.high-definition/HDRP/Camera/HDCamera.cs


public Matrix4x4 projMatrix;
public Matrix4x4 nonJitteredProjMatrix;
public Vector4 worldSpaceCameraPos;
public float detViewMatrix;
public Vector4 screenSize;
public Frustum frustum;
public Vector4[] frustumPlaneEquations;

projMatrix = gpuProj;
nonJitteredProjMatrix = gpuNonJitteredProj;
cameraPos = pos;
detViewMatrix = viewMatrix.determinant;
if (ShaderConfig.s_CameraRelativeRendering != 0)
{

// What constants in UnityPerPass need updating for stereo considerations?
// _ViewProjMatrix - It is used directly for generating tesselation factors. This should be the same
// across both eyes for consistency, and to keep shadow-generation eye-independent
// _DetViewMatrix - Used for isFrontFace determination, should be the same for both eyes. There is the scenario
// where there might be multi-eye sets that are divergent enough where this assumption is not valid,
// but that's a future problem
// _InvProjParam - Intention was for generating linear depths, but not currently used. Will need to be stereo-ized if
// actually needed.
// _FrustumPlanes - Also used for generating tesselation factors. Should be fine to use the combined stereo VP

viewMatrix = stereoCombinedViewMatrix;
var stereoCombinedProjMatrix = cullingParams.cullStereoProj;
projMatrix = GL.GetGPUProjectionMatrix(stereoCombinedProjMatrix, true);
detViewMatrix = viewMatrix.determinant;
frustum = Frustum.Create(viewProjMatrix, true, true);

cmd.SetGlobalMatrix(HDShaderIDs._NonJitteredViewProjMatrix, nonJitteredViewProjMatrix);
cmd.SetGlobalMatrix(HDShaderIDs._PrevViewProjMatrix, prevViewProjMatrix);
cmd.SetGlobalVector(HDShaderIDs._WorldSpaceCameraPos, worldSpaceCameraPos);
cmd.SetGlobalFloat(HDShaderIDs._DetViewMatrix, detViewMatrix);
cmd.SetGlobalVector(HDShaderIDs._ScreenSize, screenSize);
cmd.SetGlobalVector(HDShaderIDs._ScreenToTargetScale, doubleBufferedViewportScale);
cmd.SetGlobalVector(HDShaderIDs._ZBufferParams, zBufferParams);

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


});
}
list.Add(new DebugUI.BoolField { displayName = "Display Light Volumes", getter = () => lightingDebugSettings.displayLightVolumes, setter = value => lightingDebugSettings.displayLightVolumes = value, onValueChanged = RefreshLightingDebug });
if (DebugNeedsExposure())
list.Add(new DebugUI.FloatField { displayName = "Debug Exposure", getter = () => lightingDebugSettings.debugExposure, setter = value => lightingDebugSettings.debugExposure = value });

2
com.unity.render-pipelines.high-definition/HDRP/Debug/LightingDebug.cs


public bool displaySkyReflection = false;
public float skyReflectionMipmap = 0.0f;
public bool displayLightVolumes = false;
public float environmentProxyDepthScale = 20;
public float debugExposure = 0.0f;

2
com.unity.render-pipelines.high-definition/HDRP/Editor/AssetProcessors/NormalMapFilteringTexturePostprocessor.cs.meta


fileFormatVersion: 2
guid: 3ceae5765b6bbee4fb4f76acdaae9130
guid: db58d0243609fae48a1a8f3460bdbd4c
MonoImporter:
externalObjects: {}
serializedVersion: 2

66
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDAdditionalLightDataEditor.cs


{
}
}
public class HDAdditionalLightDataGizmoDrawer
{
[DrawGizmo(GizmoType.Selected | GizmoType.Active)]
static void DrawGizmoForHDAdditionalLightData(HDAdditionalLightData src, GizmoType gizmoType)
{
bool selected = (gizmoType & GizmoType.Selected) != 0;
var light = src.gameObject.GetComponent<Light>();
var gizmoColor = light.color;
gizmoColor.a = selected ? 1.0f : 0.3f; // Fade for the gizmo
Gizmos.color = Handles.color = gizmoColor;
if (src.lightTypeExtent == LightTypeExtent.Punctual)
{
switch (light.type)
{
case LightType.Directional:
CoreLightEditorUtilities.DrawDirectionalLightGizmo(light);
break;
case LightType.Point:
CoreLightEditorUtilities.DrawPointlightGizmo(light, selected);
break;
case LightType.Spot:
if (src.spotLightShape == SpotLightShape.Cone)
CoreLightEditorUtilities.DrawSpotlightGizmo(light, src.GetInnerSpotPercent01(), selected);
else if (src.spotLightShape == SpotLightShape.Pyramid)
HDLightEditorUtilities.DrawFrustumlightGizmo(light);
else if (src.spotLightShape == SpotLightShape.Box)
HDLightEditorUtilities.DrawFrustumlightGizmo(light);
break;
}
}
else
{
switch (src.lightTypeExtent)
{
case LightTypeExtent.Rectangle:
CoreLightEditorUtilities.DrawArealightGizmo(light);
break;
case LightTypeExtent.Line:
CoreLightEditorUtilities.DrawArealightGizmo(light);
break;
}
}
if (selected)
{
// Trace a ray down to better locate the light location
Ray ray = new Ray(src.gameObject.transform.position, Vector3.down);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Handles.color = Color.green;
Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual;
Handles.DrawLine(src.gameObject.transform.position, hit.point);
Handles.DrawWireDisc(hit.point, hit.normal, 0.5f);
Handles.color = Color.red;
Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater;
Handles.DrawLine(src.gameObject.transform.position, hit.point);
Handles.DrawWireDisc(hit.point, hit.normal, 0.5f);
}
}
}
}
}

25
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightEditor.cs


[CustomEditorForRenderPipeline(typeof(Light), typeof(HDRenderPipelineAsset))]
sealed partial class HDLightEditor : LightEditor
{
[MenuItem("CONTEXT/Light/Remove HD Light", false, 0)]
[MenuItem("CONTEXT/Light/Remove Component", false, 0)]
static void RemoveLight(MenuCommand menuCommand)
{
GameObject go = ((Light)menuCommand.context).gameObject;

Undo.DestroyObjectImmediate(go.GetComponent<Light>());
Undo.DestroyObjectImmediate(go.GetComponent<HDAdditionalLightData>());
Undo.DestroyObjectImmediate(go.GetComponent<AdditionalShadowData>());
}
[MenuItem("CONTEXT/Light/Reset", false, 0)]
static void ResetLight(MenuCommand menuCommand)
{
GameObject go = ((Light)menuCommand.context).gameObject;
Assert.IsNotNull(go);
Light light = go.GetComponent<Light>();
HDAdditionalLightData lightAdditionalData = go.GetComponent<HDAdditionalLightData>();
AdditionalShadowData shadowAdditionalData = go.GetComponent<AdditionalShadowData>();
Assert.IsNotNull(light);
Assert.IsNotNull(lightAdditionalData);
Assert.IsNotNull(shadowAdditionalData);
Undo.RecordObjects(new UnityEngine.Object[] { light, lightAdditionalData, shadowAdditionalData }, "Reset HD Light");
light.Reset();
// To avoid duplicating init code we copy default settings to Reset additional data
// Note: we can't call this code inside the HDAdditionalLightData, thus why we don't wrap it in a Reset() function
HDUtils.s_DefaultHDAdditionalLightData.CopyTo(lightAdditionalData);
CoreUtils.s_DefaultAdditionalShadowData.CopyTo(shadowAdditionalData);
}
sealed class SerializedLightData

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightExplorerExtension.cs


lightDataPairing[light].hdAdditionalLightData.intensity = intensity;
}
}),
new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.Intensity, "m_Intensity", 60, (r, prop, dep) => // 9: Unit
new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.Unit, "m_Intensity", 60, (r, prop, dep) => // 9: Unit
{
Light light = prop.serializedObject.targetObject as Light;
LightUnit unit = lightDataPairing[light].hdAdditionalLightData.lightUnit;

3
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/EditorReflectionSystem.cs


AssetDatabase.ImportAsset(path);
probe.customTexture = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
EditorUtility.SetDirty(probe);
}
public static void BakeAllPlanarReflectionProbes()

{
bakedTexture = new Texture2D(rt.width, rt.height, TextureFormat.RGBAHalf, true, false);
probe.bakedTexture = bakedTexture;
EditorUtility.SetDirty(probe);
}
ReflectionSystem.Render(probe, rt);

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Gizmos.cs


{
material = new Material(Shader.Find("Debug/ReflectionProbePreview"));
}
material.SetTexture("_Cubemap", p.texture);
material.SetTexture("_Cubemap", e.GetTexture());
material.SetPass(0);
Graphics.DrawMeshNow(sphere, Matrix4x4.TRS(p.transform.position, Quaternion.identity, Vector3.one));
}

34
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Preview.cs


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

return false; // We only handle one preview for reflection probes
// Ensure valid cube map editor (if possible)
Texture texture = GetTexture();
if (m_CubemapEditor != null && m_CubemapEditor.target as Texture != texture)
{
DestroyImmediate(m_CubemapEditor);
m_CubemapEditor = null;
}
CreateCachedEditor(((ReflectionProbe)target).texture, typeof(HDCubemapInspector), ref editor);
CreateCachedEditor(GetTexture(), typeof(HDCubemapInspector), ref editor);
m_CubemapEditor = editor as HDCubemapInspector;
}

GUILayout.EndHorizontal();
return;
}
var p = target as ReflectionProbe;
if (p != null && p.texture != null && targets.Length == 1)
Texture tex = GetTexture();
if (tex != null && targets.Length == 1)
var p = target as ReflectionProbe;
return p != null && p.texture != null;
return GetTexture() != null;
}
Texture GetTexture()
{
HDProbe additional = GetTarget(target);
if (additional != null && additional.mode == UnityEngine.Rendering.ReflectionProbeMode.Realtime)
{
return additional.realtimeTexture;
}
else
{
var p = target as ReflectionProbe;
if (p != null)
return p.texture;
}
return null;
}
private void OnDestroy()

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.ProbeUtility.cs


{
partial class HDReflectionProbeEditor
{
void InitializeAllTargetProbes()
void InitializeTargetProbe()
{
// For an unknown reason, newly created probes sometype have the type "Quad" (value = 1)
// This type of probe is not supported by Unity since 5.4

133
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs


{
[CustomEditorForRenderPipeline(typeof(ReflectionProbe), typeof(HDRenderPipelineAsset))]
[CanEditMultipleObjects]
partial class HDReflectionProbeEditor : Editor
partial class HDReflectionProbeEditor : HDProbeEditor
{
[MenuItem("CONTEXT/ReflectionProbe/Remove Component", false, 0)]
static void RemoveReflectionProbe(MenuCommand menuCommand)

static Dictionary<ReflectionProbe, HDReflectionProbeEditor> s_ReflectionProbeEditors = new Dictionary<ReflectionProbe, HDReflectionProbeEditor>();
internal override HDProbe GetTarget(Object editorTarget)
{
return (HDProbe)s_ReflectionProbeEditors[(ReflectionProbe)editorTarget].m_AdditionalDataSerializedObject.targetObject;
}
protected override void Draw(HDProbeUI s, SerializedHDProbe serialized, Editor owner)
{
HDReflectionProbeUI.Inspector.Draw(s, serialized, owner);
}
static HDReflectionProbeEditor GetEditorFor(ReflectionProbe p)
{
HDReflectionProbeEditor e;

return null;
}
SerializedHDReflectionProbe m_SerializedHdReflectionProbe;
HDReflectionProbeUI m_UIState = new HDReflectionProbeUI();
int m_PositionHash = 0;
internal HDReflectionProbeUI m_UIState = new HDReflectionProbeUI();
get { return IsReflectionProbeEditMode(EditMode.editMode) && EditMode.IsOwner(this); }
get { return HDProbeUI.IsProbeEditMode(EditMode.editMode) && EditMode.IsOwner(this); }
void OnEnable()
protected override void OnEnable()
m_SerializedHdReflectionProbe = new SerializedHDReflectionProbe(serializedObject, m_AdditionalDataSerializedObject);
m_UIState.owner = this;
m_UIState.Reset(m_SerializedHdReflectionProbe, Repaint);
m_SerializedHDProbe = new SerializedHDReflectionProbe(serializedObject, m_AdditionalDataSerializedObject);
foreach (var t in targets)
{

InitializeAllTargetProbes();
base.OnEnable();
m_UIState.owner = this;
m_UIState.Reset(m_SerializedHDProbe, Repaint);
InitializeTargetProbe();
}
public override void OnInspectorGUI()
{
//InspectColorsGUI();
var s = m_UIState;
var p = m_SerializedHdReflectionProbe;
s.Update();
p.Update();
HDReflectionProbeUI.Inspector.Draw(s, p, this);
PerformOperations(s, p, this);
p.Apply();
//HideAdditionalComponents(false);
HDReflectionProbeUI.DoShortcutKey(p, this);
}
public static bool IsReflectionProbeEditMode(EditMode.SceneViewEditMode editMode)
{
return editMode == EditMode.SceneViewEditMode.ReflectionProbeBox || editMode == EditMode.SceneViewEditMode.Collider || editMode == EditMode.SceneViewEditMode.GridBox ||
editMode == EditMode.SceneViewEditMode.ReflectionProbeOrigin;
}
static void PerformOperations(HDReflectionProbeUI s, SerializedHDReflectionProbe p, HDReflectionProbeEditor o)
{
}
void HideAdditionalComponents(bool visible)
{
var adds = CoreEditorUtils.GetAdditionalData<HDAdditionalReflectionData>(targets);
var flags = visible ? HideFlags.None : HideFlags.HideInInspector;
for (var i = 0; i < targets.Length; ++i)
{
var addData = adds[i];
addData.hideFlags = flags;
}
}
void BakeRealtimeProbeIfPositionChanged(HDReflectionProbeUI s, SerializedHDReflectionProbe sp, Editor o)
{
if (Application.isPlaying
|| ((ReflectionProbeMode)sp.mode.intValue) != ReflectionProbeMode.Realtime)
{
m_PositionHash = 0;
return;
}
var hash = 0;
for (var i = 0; i < sp.so.targetObjects.Length; i++)
{
var p = (ReflectionProbe)sp.so.targetObjects[i];
var tr = p.GetComponent<Transform>();
hash ^= tr.position.GetHashCode();
}
if (hash != m_PositionHash)
{
m_PositionHash = hash;
for (var i = 0; i < sp.so.targetObjects.Length; i++)
{
var p = (ReflectionProbe)sp.so.targetObjects[i];
p.RenderProbe();
}
}
}
static void ApplyConstraintsOnTargets(HDReflectionProbeUI s, SerializedHDReflectionProbe sp, Editor o)
{
switch ((InfluenceShape)sp.influenceVolume.shape.enumValueIndex)
{
case InfluenceShape.Box:
{
var maxBlendDistance = sp.influenceVolume.boxSize.vector3Value;
sp.targetData.influenceVolume.boxBlendDistancePositive = Vector3.Min(sp.targetData.influenceVolume.boxBlendDistancePositive, maxBlendDistance);
sp.targetData.influenceVolume.boxBlendDistanceNegative = Vector3.Min(sp.targetData.influenceVolume.boxBlendDistanceNegative, maxBlendDistance);
sp.targetData.influenceVolume.boxBlendNormalDistancePositive = Vector3.Min(sp.targetData.influenceVolume.boxBlendNormalDistancePositive, maxBlendDistance);
sp.targetData.influenceVolume.boxBlendNormalDistanceNegative = Vector3.Min(sp.targetData.influenceVolume.boxBlendNormalDistanceNegative, maxBlendDistance);
break;
}
case InfluenceShape.Sphere:
{
var maxBlendDistance = Vector3.one * sp.influenceVolume.sphereRadius.floatValue;
sp.targetData.influenceVolume.boxBlendDistancePositive = Vector3.Min(sp.targetData.influenceVolume.boxBlendDistancePositive, maxBlendDistance);
sp.targetData.influenceVolume.boxBlendDistanceNegative = Vector3.Min(sp.targetData.influenceVolume.boxBlendDistanceNegative, maxBlendDistance);
sp.targetData.influenceVolume.boxBlendNormalDistancePositive = Vector3.Min(sp.targetData.influenceVolume.boxBlendNormalDistancePositive, maxBlendDistance);
sp.targetData.influenceVolume.boxBlendNormalDistanceNegative = Vector3.Min(sp.targetData.influenceVolume.boxBlendNormalDistanceNegative, maxBlendDistance);
break;
}
}
//unhide previously hidden components
probe.hideFlags = HideFlags.None;
}
}
}

532
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.Drawers.cs


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

using CED = CoreEditorDrawer<HDReflectionProbeUI, SerializedHDReflectionProbe>;
using _ = CoreEditorUtils;
using CED = CoreEditorDrawer<HDProbeUI, SerializedHDProbe>;
public static readonly CED.IDrawer[] Inspector;
SectionProxyVolumeSettings,
ProxyVolumeSettings,
SectionInfluenceProxyMismatch,
CED.Action((s, d, o) => Drawer_DifferentShapeError(s, d, o)),
SectionAdditionalSettings,
ButtonBake
SectionFoldoutAdditionalSettings,
CED.Action((s, d, o) => Drawer_SectionBakeButton(s, d, o))
public static readonly CED.IDrawer[] Inspector;
public static readonly CED.IDrawer SectionPrimarySettings = CED.Group(
CED.Action(Drawer_Toolbar),
static readonly CED.IDrawer SectionPrimarySettings = CED.Group(
CED.Action((s, d, o) => Drawer_Toolbars(s, d, o)),
CED.FadeGroup((s, p, o, i) => s.IsSectionExpandedMode((ReflectionProbeMode)i),
CED.FadeGroup((s, p, o, i) => s.IsSectionExpandedReflectionProbeMode((ReflectionProbeMode)i),
CED.noop, // Baked
CED.Action(Drawer_ModeSettingsRealtime), // Realtime
CED.Action(Drawer_ModeSettingsCustom) // Custom
CED.noop, // Baked
CED.Action((s, d, o) => Drawer_ModeSettingsRealtime(s, d, o)), // Realtime
CED.Action((s, d, o) => Drawer_ModeSettingsCustom(s, d, o)) // Custom
public static readonly CED.IDrawer SectionProxyVolumeSettings = CED.FoldoutGroup(
"Proxy Volume",
(s, p, o) => s.isSectionExpandedProxyVolume,
FoldoutOption.Indent,
CED.Action(Drawer_ProxyVolume),
CED.space,
CED.Action(Drawer_ProjectionSettings)
);
public static readonly CED.IDrawer SectionInfluenceVolumeSettings = CED.FoldoutGroup(
"Influence Volume",
(s, p, o) => s.isSectionExpandedInfluenceVolume,
FoldoutOption.Indent,
CED.Action(Drawer_InfluenceAdvancedSwitch),
CED.space,
CED.Action(Drawer_InfluenceShape),
CED.space,
CED.Action(Drawer_InfluenceAreas)
);
public static readonly CED.IDrawer SectionInfluenceProxyMismatch = CED.Action(Drawer_InfluenceProxyMissmatch);
public static readonly CED.IDrawer SectionCaptureSettings = CED.FoldoutGroup(
"Capture Settings",
static readonly CED.IDrawer SectionCaptureSettings = CED.FoldoutGroup(
captureSettingsHeader,
public static readonly CED.IDrawer SectionAdditionalSettings = CED.FoldoutGroup(
"Artistic Settings",
(s, p, o) => s.isSectionExpandedAdditional,
FoldoutOption.Indent,
CED.Action(Drawer_AdditionalSettings)
);
public static readonly CED.IDrawer ButtonBake = CED.Action(Drawer_BakeActions);
static void Drawer_CaptureSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
static void Drawer_CaptureSettings(HDProbeUI s, SerializedHDProbe p, Editor owner)
EditorGUILayout.LabelField(CoreEditorUtils.GetContent("Resolution"), CoreEditorUtils.GetContent(p.resolution.intValue.ToString()));
EditorGUILayout.PropertyField(p.shadowDistance, CoreEditorUtils.GetContent("Shadow Distance"));
EditorGUILayout.PropertyField(p.cullingMask, CoreEditorUtils.GetContent("Culling Mask"));
EditorGUILayout.PropertyField(p.useOcclusionCulling, CoreEditorUtils.GetContent("Use Occlusion Culling"));
EditorGUILayout.PropertyField(p.nearClip, CoreEditorUtils.GetContent("Near Clip"));
EditorGUILayout.PropertyField(p.farClip, CoreEditorUtils.GetContent("Far Clip"));
}
static void Drawer_AdditionalSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.PropertyField(p.weight, CoreEditorUtils.GetContent("Influence Volume Weight|Blending weight to use while interpolating between influence volume. (Reminder: Sky is an Influence Volume too)."));
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(p.multiplier, CoreEditorUtils.GetContent("Multiplier|Tweeking option to enhance reflection."));
if (EditorGUI.EndChangeCheck())
p.multiplier.floatValue = Mathf.Max(0.0f, p.multiplier.floatValue);
if (p.so.targetObjects.Length == 1)
{
var probe = p.target;
if (probe.mode == ReflectionProbeMode.Custom && probe.customBakedTexture != null)
{
var cubemap = probe.customBakedTexture as Cubemap;
if (cubemap && cubemap.mipmapCount == 1)
EditorGUILayout.HelpBox("No mipmaps in the cubemap, Smoothness value in Standard shader will be ignored.", MessageType.Warning);
}
}
}
static void Drawer_BakeActions(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorReflectionSystemGUI.DrawBakeButton((ReflectionProbeMode)p.mode.intValue, p.target);
}
static void Drawer_ProxyVolume(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.PropertyField(p.proxyVolumeComponent, _.GetContent("Proxy Volume"));
if (p.proxyVolumeComponent.objectReferenceValue == null)
{
EditorGUILayout.HelpBox(
"When no Proxy setted, Influence shape will be used as Proxy shape too.",
MessageType.Info,
true
);
}
}
#region Influence Volume
static void Drawer_InfluenceProxyMissmatch(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
if (p.proxyVolumeComponent.objectReferenceValue != null)
{
var proxy = (ReflectionProxyVolumeComponent)p.proxyVolumeComponent.objectReferenceValue;
if ((int)proxy.proxyVolume.shape != p.influenceVolume.shape.enumValueIndex)
EditorGUILayout.HelpBox(
"Proxy volume and influence volume have different shape types, this is not supported.",
MessageType.Error,
true
);
}
}
static void Drawer_InfluenceBoxSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
bool advanced = p.influenceVolume.editorAdvancedModeEnabled.boolValue;
var maxBlendDistance = p.boxSize.vector3Value * 0.5f;
EditorGUILayout.BeginHorizontal();
Drawer_AdvancedBlendDistance(
p,
false,
maxBlendDistance,
CoreEditorUtils.GetContent("Blend Distance|Area around the probe where it is blended with other probes. Only used in deferred probes.")
);
if (GUILayout.Button(toolbar_Contents[1], GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight((advanced ? 3 : 1) * (EditorGUIUtility.singleLineHeight + 3))))
{
EditMode.ChangeEditMode(k_Toolbar_SceneViewEditModes[1], GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField(resolutionContent, CoreEditorUtils.GetContent(p.resolution.intValue.ToString()));
EditorGUILayout.BeginHorizontal();
Drawer_AdvancedBlendDistance(
p,
true,
maxBlendDistance,
CoreEditorUtils.GetContent("Blend Normal Distance|Area around the probe where the normals influence the probe. Only used in deferred probes.")
);
if (GUILayout.Button(toolbar_Contents[2], GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight((advanced ? 3 : 1) * (EditorGUIUtility.singleLineHeight + 3))))
{
EditMode.ChangeEditMode(k_Toolbar_SceneViewEditModes[2], GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
if (advanced)
{
CoreEditorUtils.DrawVector6(
CoreEditorUtils.GetContent("Face fade|Fade faces of the cubemap."),
p.influenceVolume.boxSideFadePositive, p.influenceVolume.boxSideFadeNegative, Vector3.zero, Vector3.one, HDReflectionProbeEditor.k_handlesColor);
}
EditorGUILayout.PropertyField(p.shadowDistance, shadowDistanceContent);
EditorGUILayout.PropertyField(p.cullingMask, cullingMaskContent);
EditorGUILayout.PropertyField(p.useOcclusionCulling, useOcclusionCullingContent);
EditorGUILayout.PropertyField(p.nearClip, nearClipCullingContent);
EditorGUILayout.PropertyField(p.farClip, farClipCullingContent);
static void Drawer_AdvancedBlendDistance(SerializedHDReflectionProbe p, bool isNormal, Vector3 maxBlendDistance, GUIContent content)
{
SerializedProperty blendDistancePositive = isNormal ? p.influenceVolume.boxBlendNormalDistancePositive : p.influenceVolume.boxBlendDistancePositive;
SerializedProperty blendDistanceNegative = isNormal ? p.influenceVolume.boxBlendNormalDistanceNegative : p.influenceVolume.boxBlendDistanceNegative;
SerializedProperty editorAdvancedModeBlendDistancePositive = isNormal ? p.influenceVolume.editorAdvancedModeBlendNormalDistancePositive : p.influenceVolume.editorAdvancedModeBlendDistancePositive;
SerializedProperty editorAdvancedModeBlendDistanceNegative = isNormal ? p.influenceVolume.editorAdvancedModeBlendNormalDistanceNegative : p.influenceVolume.editorAdvancedModeBlendDistanceNegative;
SerializedProperty editorSimplifiedModeBlendDistance = isNormal ? p.influenceVolume.editorSimplifiedModeBlendNormalDistance : p.influenceVolume.editorSimplifiedModeBlendDistance;
Vector3 bdp = blendDistancePositive.vector3Value;
Vector3 bdn = blendDistanceNegative.vector3Value;
EditorGUILayout.BeginVertical();
if (p.influenceVolume.editorAdvancedModeEnabled.boolValue)
{
EditorGUI.BeginChangeCheck();
CoreEditorUtils.DrawVector6(
content,
editorAdvancedModeBlendDistancePositive, editorAdvancedModeBlendDistanceNegative, Vector3.zero, maxBlendDistance, HDReflectionProbeEditor.k_handlesColor);
if(EditorGUI.EndChangeCheck())
{
blendDistancePositive.vector3Value = editorAdvancedModeBlendDistancePositive.vector3Value;
blendDistanceNegative.vector3Value = editorAdvancedModeBlendDistanceNegative.vector3Value;
p.Apply();
}
}
else
{
float distance = editorSimplifiedModeBlendDistance.floatValue;
EditorGUI.BeginChangeCheck();
distance = EditorGUILayout.FloatField(content, distance);
if (EditorGUI.EndChangeCheck())
{
Vector3 decal = Vector3.one * distance;
bdp.x = Mathf.Clamp(decal.x, 0f, maxBlendDistance.x);
bdp.y = Mathf.Clamp(decal.y, 0f, maxBlendDistance.y);
bdp.z = Mathf.Clamp(decal.z, 0f, maxBlendDistance.z);
bdn.x = Mathf.Clamp(decal.x, 0f, maxBlendDistance.x);
bdn.y = Mathf.Clamp(decal.y, 0f, maxBlendDistance.y);
bdn.z = Mathf.Clamp(decal.z, 0f, maxBlendDistance.z);
blendDistancePositive.vector3Value = bdp;
blendDistanceNegative.vector3Value = bdn;
editorSimplifiedModeBlendDistance.floatValue = distance;
p.Apply();
}
}
GUILayout.EndVertical();
}
static void Drawer_InfluenceSphereSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
var maxBlendDistance = p.influenceVolume.sphereRadius.floatValue;
var blendDistance = p.influenceVolume.boxBlendDistancePositive.vector3Value.x;
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = p.influenceVolume.boxBlendDistancePositive.hasMultipleDifferentValues;
blendDistance = EditorGUILayout.Slider(CoreEditorUtils.GetContent("Blend Distance|Area around the probe where it is blended with other probes. Only used in deferred probes."), blendDistance, 0, maxBlendDistance);
if (EditorGUI.EndChangeCheck())
{
p.influenceVolume.boxBlendDistancePositive.vector3Value = Vector3.one * blendDistance;
p.influenceVolume.boxBlendDistanceNegative.vector3Value = Vector3.one * blendDistance;
}
if (GUILayout.Button(toolbar_Contents[1], GUILayout.Width(28f), GUILayout.Height(EditorGUIUtility.singleLineHeight + 3)))
{
EditMode.ChangeEditMode(k_Toolbar_SceneViewEditModes[1], GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
var blendNormalDistance = p.influenceVolume.boxBlendNormalDistancePositive.vector3Value.x;
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = p.influenceVolume.boxBlendNormalDistancePositive.hasMultipleDifferentValues;
blendNormalDistance = EditorGUILayout.Slider(CoreEditorUtils.GetContent("Blend Normal Distance|Area around the probe where the normals influence the probe. Only used in deferred probes."), blendNormalDistance, 0, maxBlendDistance);
if (EditorGUI.EndChangeCheck())
{
p.influenceVolume.boxBlendNormalDistancePositive.vector3Value = Vector3.one * blendNormalDistance;
p.influenceVolume.boxBlendNormalDistanceNegative.vector3Value = Vector3.one * blendNormalDistance;
}
if (GUILayout.Button(toolbar_Contents[2], GUILayout.Width(28f), GUILayout.Height(EditorGUIUtility.singleLineHeight + 3)))
{
EditMode.ChangeEditMode(k_Toolbar_SceneViewEditModes[2], GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
EditorGUI.showMixedValue = false;
}
#endregion
#region Field Drawers
static void Drawer_ReflectionProbeMode(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
static void Drawer_ReflectionProbeMode(HDProbeUI s, SerializedHDProbe p, Editor owner)
HDReflectionProbeUI ui = ((HDReflectionProbeEditor)owner).m_UIState;
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = p.mode.hasMultipleDifferentValues;
EditorGUILayout.IntPopup(p.mode, k_Content_ReflectionProbeMode, k_Content_ReflectionProbeModeValues, CoreEditorUtils.GetContent("Type|'Baked Cubemap' uses the 'Auto Baking' mode from the Lighting window. If it is enabled then baking is automatic otherwise manual bake is needed (use the bake button below). \n'Custom' can be used if a custom cubemap is wanted. \n'Realtime' can be used to dynamically re-render the cubemap during runtime (via scripting)."));

s.SetModeTarget(p.mode.intValue);
}
}
static void Drawer_InfluenceAdvancedSwitch(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
bool advanced = p.influenceVolume.editorAdvancedModeEnabled.boolValue;
advanced = !GUILayout.Toggle(!advanced, CoreEditorUtils.GetContent("Normal|Normal parameters mode (only change for box shape)."), EditorStyles.miniButtonLeft, GUILayout.Width(60f), GUILayout.ExpandWidth(false));
advanced = GUILayout.Toggle(advanced, CoreEditorUtils.GetContent("Advanced|Advanced parameters mode (only change for box shape)."), EditorStyles.miniButtonRight, GUILayout.Width(60f), GUILayout.ExpandWidth(false));
s.alternativeBoxBlendHandle.allHandleControledByOne = s.alternativeBoxBlendNormalHandle.allHandleControledByOne = !advanced;
if (p.influenceVolume.editorAdvancedModeEnabled.boolValue ^ advanced)
{
p.influenceVolume.editorAdvancedModeEnabled.boolValue = advanced;
if (advanced)
{
p.influenceVolume.boxBlendDistancePositive.vector3Value = p.influenceVolume.editorAdvancedModeBlendDistancePositive.vector3Value;
p.influenceVolume.boxBlendDistanceNegative.vector3Value = p.influenceVolume.editorAdvancedModeBlendDistanceNegative.vector3Value;
p.influenceVolume.boxBlendNormalDistancePositive.vector3Value = p.influenceVolume.editorAdvancedModeBlendNormalDistancePositive.vector3Value;
p.influenceVolume.boxBlendNormalDistanceNegative.vector3Value = p.influenceVolume.editorAdvancedModeBlendNormalDistanceNegative.vector3Value;
}
else
{
p.influenceVolume.boxBlendDistanceNegative.vector3Value = p.influenceVolume.boxBlendDistancePositive.vector3Value = Vector3.one * p.influenceVolume.editorSimplifiedModeBlendDistance.floatValue;
p.influenceVolume.boxBlendNormalDistanceNegative.vector3Value = p.influenceVolume.boxBlendNormalDistancePositive.vector3Value = Vector3.one * p.influenceVolume.editorSimplifiedModeBlendNormalDistance.floatValue;
}
p.Apply();
}
}
}
static void Drawer_InfluenceShape(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = p.influenceVolume.shape.hasMultipleDifferentValues;
EditorGUILayout.PropertyField(p.influenceVolume.shape, CoreEditorUtils.GetContent("Shape"));
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
s.SetShapeTarget(p.influenceVolume.shape.intValue);
switch ((InfluenceShape)p.influenceVolume.shape.enumValueIndex)
{
case InfluenceShape.Box:
Drawer_InfluenceShapeBoxSettings(s, p, owner);
break;
case InfluenceShape.Sphere:
Drawer_InfluenceShapeSphereSettings(s, p, owner);
break;
}
}
static void Drawer_InfluenceShapeBoxSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(p.boxSize, CoreEditorUtils.GetContent("Box Size|The size of the box in which the reflections will be applied to objects. The value is not affected by the Transform of the Game Object."));
if (GUILayout.Button(toolbar_Contents[0], GUILayout.Width(28f), GUILayout.Height(EditorGUIUtility.singleLineHeight + 3)))
{
EditMode.ChangeEditMode(EditMode.SceneViewEditMode.ReflectionProbeBox, GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(p.boxOffset, CoreEditorUtils.GetContent("Box Offset|The center of the box in which the reflections will be applied to objects. The value is relative to the position of the Game Object."));
if (GUILayout.Button(toolbar_Contents[3], GUILayout.Width(28f), GUILayout.Height(EditorGUIUtility.singleLineHeight + 3)))
{
EditMode.ChangeEditMode(EditMode.SceneViewEditMode.ReflectionProbeOrigin, GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
var center = p.boxOffset.vector3Value;
var size = p.boxSize.vector3Value;
if (HDReflectionProbeEditorUtility.ValidateAABB(p.target, ref center, ref size))
{
//clamp to contains object center instead of resizing
Vector3 projector = (center - p.boxOffset.vector3Value).normalized;
p.boxOffset.vector3Value = center + Mathf.Abs(Vector3.Dot((p.boxSize.vector3Value - size) * .5f, projector)) * projector;
}
}
}
static void Drawer_InfluenceShapeSphereSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(p.influenceVolume.sphereRadius, CoreEditorUtils.GetContent("Radius"));
if (GUILayout.Button(toolbar_Contents[0], GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.Height(EditorGUIUtility.singleLineHeight + 3)))
{
EditMode.ChangeEditMode(EditMode.SceneViewEditMode.ReflectionProbeBox, GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(p.boxOffset, CoreEditorUtils.GetContent("Sphere Offset|The center of the sphere in which the reflections will be applied to objects. The value is relative to the position of the Game Object."));
if (GUILayout.Button(toolbar_Contents[3], GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.Height(EditorGUIUtility.singleLineHeight + 3)))
{
EditMode.ChangeEditMode(EditMode.SceneViewEditMode.ReflectionProbeOrigin, GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
}
static void Drawer_InfluenceAreas(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
if (s.IsSectionExpandedShape(InfluenceShape.Box).value)
{
Drawer_InfluenceBoxSettings(s, p, owner);
}
if (s.IsSectionExpandedShape(InfluenceShape.Sphere).value)
{
Drawer_InfluenceSphereSettings(s, p, owner);
}
}
static void Drawer_ProjectionSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.PropertyField(p.boxProjection, CoreEditorUtils.GetContent("Parallax Correction|Parallax Correction causes reflections to appear to change based on the object's position within the probe's box, while still using a single probe as the source of the reflection. This works well for reflections on objects that are moving through enclosed spaces such as corridors and rooms. Setting Parallax Correction to False and the cubemap reflection will be treated as coming from infinitely far away. Note that this feature can be globally disabled from Graphics Settings -> Tier Settings"));
}
static void Drawer_IntensityMultiplier(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.PropertyField(p.intensityMultiplier, CoreEditorUtils.GetContent("Intensity"));
}
#endregion
#region Toolbar
static readonly EditMode.SceneViewEditMode[] k_Toolbar_SceneViewEditModes =
{
EditMode.SceneViewEditMode.ReflectionProbeBox,
EditMode.SceneViewEditMode.GridBox,
EditMode.SceneViewEditMode.Collider,
EditMode.SceneViewEditMode.ReflectionProbeOrigin
};
static GUIContent[] s_Toolbar_Contents = null;
static GUIContent[] toolbar_Contents
{
get
{
return s_Toolbar_Contents ?? (s_Toolbar_Contents = new[]
{
EditorGUIUtility.IconContent("EditCollider", "|Modify the extents of the reflection probe. (SHIFT+1)"),
EditorGUIUtility.IconContent("PreMatCube", "|Modify the influence volume of the reflection probe. (SHIFT+2)"),
EditorGUIUtility.IconContent("SceneViewOrtho", "|Modify the influence normal volume of the reflection probe. (SHIFT+3)"),
EditorGUIUtility.IconContent("MoveTool", "|Move the selected objects.")
});
ui.SetModeTarget(p.mode.intValue);
p.Apply();
static void Drawer_Toolbar(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
if (p.so.targetObjects.Length > 1)
return;
// Show the master tool selector
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.changed = false;
var oldEditMode = EditMode.editMode;
EditMode.DoInspectorToolbar(k_Toolbar_SceneViewEditModes, toolbar_Contents, GetBoundsGetter(p), owner);
//if (GUILayout.Button(EditorGUIUtility.IconContent("Navigation", "|Fit the reflection probe volume to the surrounding colliders.")))
// s.AddOperation(Operation.FitVolumeToSurroundings);
if (oldEditMode != EditMode.editMode)
{
switch (EditMode.editMode)
{
case EditMode.SceneViewEditMode.ReflectionProbeOrigin:
s.UpdateOldLocalSpace(p.target);
break;
}
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
static public void Drawer_ToolBarButton(int buttonIndex, Editor owner, params GUILayoutOption[] styles)
{
if (GUILayout.Button(toolbar_Contents[buttonIndex], styles))
{
EditMode.ChangeEditMode(k_Toolbar_SceneViewEditModes[buttonIndex], GetBoundsGetter(owner)(), owner);
}
}
static Func<Bounds> GetBoundsGetter(SerializedHDReflectionProbe p)
{
return () =>
{
var bounds = new Bounds();
foreach (var targetObject in p.so.targetObjects)
{
var rp = (ReflectionProbe)targetObject;
var b = rp.bounds;
bounds.Encapsulate(b);
}
return bounds;
};
}
static Func<Bounds> GetBoundsGetter(Editor o)
{
return () =>
{
var bounds = new Bounds();
foreach (Component targetObject in o.targets)
{
var rp = targetObject.transform;
var b = rp.position;
bounds.Encapsulate(b);
}
return bounds;
};
}
static readonly KeyCode[] k_ShortCutKeys =
{
KeyCode.Alpha1,
KeyCode.Alpha2,
KeyCode.Alpha3,
};
public static void DoShortcutKey(SerializedHDReflectionProbe p, Editor o)
{
var evt = Event.current;
if (evt.type != EventType.KeyDown || !evt.shift)
return;
for (var i = 0; i < k_ShortCutKeys.Length; ++i)
{
if (evt.keyCode == k_ShortCutKeys[i])
{
var mode = EditMode.editMode == k_Toolbar_SceneViewEditModes[i]
? EditMode.SceneViewEditMode.None
: k_Toolbar_SceneViewEditModes[i];
EditMode.ChangeEditMode(mode, GetBoundsGetter(p)(), o);
evt.Use();
break;
}
}
}
#endregion
static void Drawer_ModeSettingsCustom(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
static void Drawer_ModeSettingsCustom(HDProbeUI s, SerializedHDProbe p, Editor owner)
EditorGUILayout.PropertyField(p.renderDynamicObjects, CoreEditorUtils.GetContent("Dynamic Objects|If enabled dynamic objects are also rendered into the cubemap"));
SerializedHDReflectionProbe probe = (SerializedHDReflectionProbe)p;
EditorGUILayout.PropertyField(probe.renderDynamicObjects, CoreEditorUtils.GetContent("Dynamic Objects|If enabled dynamic objects are also rendered into the cubemap"));
EditorGUI.showMixedValue = p.customBakedTexture.hasMultipleDifferentValues;
EditorGUI.showMixedValue = probe.customBakedTexture.hasMultipleDifferentValues;
var customBakedTexture = EditorGUILayout.ObjectField(CoreEditorUtils.GetContent("Cubemap"), p.customBakedTexture.objectReferenceValue, typeof(Cubemap), false);
var customBakedTexture = EditorGUILayout.ObjectField(CoreEditorUtils.GetContent("Cubemap"), probe.customBakedTexture.objectReferenceValue, typeof(Cubemap), false);
p.customBakedTexture.objectReferenceValue = customBakedTexture;
probe.customBakedTexture.objectReferenceValue = customBakedTexture;
static void Drawer_ModeSettingsRealtime(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
static void Drawer_ModeSettingsRealtime(HDProbeUI s, SerializedHDProbe p, Editor owner)
EditorGUILayout.PropertyField(p.refreshMode, CoreEditorUtils.GetContent("Refresh Mode|Controls how this probe refreshes in the Player"));
EditorGUILayout.PropertyField(p.timeSlicingMode, CoreEditorUtils.GetContent("Time Slicing|If enabled this probe will update over several frames, to help reduce the impact on the frame rate"));
SerializedHDReflectionProbe probe = (SerializedHDReflectionProbe)p;
//EditorGUILayout.PropertyField(p.refreshMode, CoreEditorUtils.GetContent("Refresh Mode|Controls how this probe refreshes in the Player"));
//EditorGUILayout.PropertyField(probe.timeSlicingMode, CoreEditorUtils.GetContent("Time Slicing|If enabled this probe will update over several frames, to help reduce the impact on the frame rate"));
}
#endregion

102
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.cs


namespace UnityEditor.Experimental.Rendering.HDPipeline
{
internal partial class HDReflectionProbeUI : BaseUI<SerializedHDReflectionProbe>
internal partial class HDReflectionProbeUI : HDProbeUI
const int k_AnimBoolSingleFieldCount = 4;
static readonly int k_ReflectionProbeModeCount = Enum.GetValues(typeof(ReflectionProbeMode)).Length;
static readonly int k_ReflectionInfluenceShapeCount = Enum.GetValues(typeof(InfluenceShape)).Length;
static readonly int k_AnimBoolsCount = k_ReflectionProbeModeCount + k_ReflectionInfluenceShapeCount + k_AnimBoolSingleFieldCount;
public InfluenceVolumeUI influenceVolume = new InfluenceVolumeUI();
internal HDReflectionProbeUI()
{
toolBars = new[] { ToolBar.InfluenceShape | ToolBar.Blend | ToolBar.NormalBlend, ToolBar.CapturePosition };
}
[Flags]
public enum Operation

public void ClearOperation(Operation op) { operations &= ~op; }
public void AddOperation(Operation op) { operations |= op; }
public Gizmo6FacesBox alternativeBoxInfluenceHandle;
public Gizmo6FacesBoxContained alternativeBoxBlendHandle;
public Gizmo6FacesBoxContained alternativeBoxBlendNormalHandle;
public SphereBoundsHandle sphereInfluenceHandle = new SphereBoundsHandle();
public SphereBoundsHandle sphereProjectionHandle = new SphereBoundsHandle();
public SphereBoundsHandle sphereBlendHandle = new SphereBoundsHandle();
public SphereBoundsHandle sphereBlendNormalHandle = new SphereBoundsHandle();
public AnimBool isSectionExpandedProxyVolume { get { return m_AnimBools[0]; } }
public AnimBool isSectionExpandedInfluenceVolume { get { return m_AnimBools[1]; } }
public AnimBool isSectionExpandedCaptureSettings { get { return m_AnimBools[2]; } }
public AnimBool isSectionExpandedAdditional { get { return m_AnimBools[3]; } }
public bool HasAndClearOperation(Operation op)
{
var has = HasOperation(op);

public bool sceneViewEditing
{
get { return HDReflectionProbeEditor.IsReflectionProbeEditMode(EditMode.editMode) && EditMode.IsOwner(owner); }
}
public HDReflectionProbeUI()
: base(k_AnimBoolsCount)
{
isSectionExpandedProxyVolume.value = true;
isSectionExpandedCaptureSettings.value = true;
isSectionExpandedInfluenceVolume.value = true;
isSectionExpandedAdditional.value = false;
alternativeBoxInfluenceHandle = new Gizmo6FacesBox(monochromeFace:true, monochromeSelectedFace:true);
alternativeBoxBlendHandle = new Gizmo6FacesBoxContained(alternativeBoxInfluenceHandle, monochromeFace:true, monochromeSelectedFace:true);
alternativeBoxBlendNormalHandle = new Gizmo6FacesBoxContained(alternativeBoxInfluenceHandle, monochromeFace:true, monochromeSelectedFace:true);
Color[] handleColors = new Color[]
{
HDReflectionProbeEditor.k_handlesColor[0][0],
HDReflectionProbeEditor.k_handlesColor[0][1],
HDReflectionProbeEditor.k_handlesColor[0][2],
HDReflectionProbeEditor.k_handlesColor[1][0],
HDReflectionProbeEditor.k_handlesColor[1][1],
HDReflectionProbeEditor.k_handlesColor[1][2]
};
alternativeBoxInfluenceHandle.handleColors = handleColors;
alternativeBoxBlendHandle.handleColors = handleColors;
alternativeBoxBlendNormalHandle.handleColors = handleColors;
alternativeBoxInfluenceHandle.faceColors = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorExtent };
alternativeBoxInfluenceHandle.faceColorsSelected = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorExtentFace };
alternativeBoxBlendHandle.faceColors = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceBlend };
alternativeBoxBlendHandle.faceColorsSelected = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceBlendFace };
alternativeBoxBlendNormalHandle.faceColors = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceNormalBlend };
alternativeBoxBlendNormalHandle.faceColorsSelected = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceNormalBlendFace };
get { return HDProbeUI.IsProbeEditMode(EditMode.editMode) && EditMode.IsOwner(owner); }
SetModeTarget(data.mode.hasMultipleDifferentValues ? -1 : data.mode.intValue);
SetShapeTarget(data.influenceVolume.shape.hasMultipleDifferentValues ? -1 : data.influenceVolume.shape.intValue);
influenceVolume.Update();
public AnimBool IsSectionExpandedMode(ReflectionProbeMode mode)
{
return m_AnimBools[k_AnimBoolSingleFieldCount + (int)mode];
}
public void SetModeTarget(int value)
{
for (var i = 0; i < k_ReflectionProbeModeCount; i++)
GetReflectionProbeModeBool(i).target = i == value;
}
public AnimBool IsSectionExpandedShape(InfluenceShape value)
{
return m_AnimBools[k_AnimBoolSingleFieldCount + k_ReflectionProbeModeCount + (int)value];
}
public void SetShapeTarget(int value)
{
for (var i = 0; i < k_ReflectionInfluenceShapeCount; i++)
GetReflectionInfluenceShapeBool(i).target = i == value;
}
}
AnimBool GetReflectionProbeModeBool(int i)
{
return m_AnimBools[k_AnimBoolSingleFieldCount + i];
}
AnimBool GetReflectionInfluenceShapeBool(int i)
{
return m_AnimBools[k_AnimBoolSingleFieldCount + k_ReflectionProbeModeCount + i];
}
public override void Reset(SerializedHDReflectionProbe data, UnityAction repaint)
{
influenceVolume.Reset(data.influenceVolume, repaint);
base.Reset(data, repaint);
}
}
}

89
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeEditor.cs


using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
using Object = UnityEngine.Object;
using System.Linq;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{

[CanEditMultipleObjects]
class PlanarReflectionProbeEditor : Editor
class PlanarReflectionProbeEditor : HDProbeEditor
static Dictionary<PlanarReflectionProbe, PlanarReflectionProbeUI> s_StateMap = new Dictionary<PlanarReflectionProbe, PlanarReflectionProbeUI>();
const float k_PreviewHeight = 128;
public static bool TryGetUIStateFor(PlanarReflectionProbe p, out PlanarReflectionProbeUI r)
{
return s_StateMap.TryGetValue(p, out r);
}
[DidReloadScripts]
static void DidReloadScripts()
{

}
}
SerializedPlanarReflectionProbe m_SerializedAsset;
PlanarReflectionProbeUI m_UIState = new PlanarReflectionProbeUI();
PlanarReflectionProbeUI[] m_UIHandleState;
PlanarReflectionProbe[] m_TypedTargets;
List<Texture> m_PreviewedTextures = new List<Texture>();
void OnEnable()
internal override HDProbe GetTarget(Object editorTarget)
m_SerializedAsset = new SerializedPlanarReflectionProbe(serializedObject);
m_UIState.Reset(m_SerializedAsset, Repaint);
m_TypedTargets = new PlanarReflectionProbe[targets.Length];
m_UIHandleState = new PlanarReflectionProbeUI[m_TypedTargets.Length];
for (var i = 0; i < m_TypedTargets.Length; i++)
{
m_TypedTargets[i] = (PlanarReflectionProbe)targets[i];
m_UIHandleState[i] = new PlanarReflectionProbeUI();
m_UIHandleState[i].Reset(m_SerializedAsset, null);
s_StateMap[m_TypedTargets[i]] = m_UIHandleState[i];
}
PlanarReflectionProbe probe = (PlanarReflectionProbe)target;
probe.influenceVolume.Init(probe);
return editorTarget as HDProbe;
void OnDisable()
protected override void Draw(HDProbeUI s, SerializedHDProbe serialized, Editor owner)
for (var i = 0; i < m_TypedTargets.Length; i++)
s_StateMap.Remove(m_TypedTargets[i]);
PlanarReflectionProbeUI.Inspector.Draw(s, serialized, owner);
public override void OnInspectorGUI()
protected override void OnEnable()
var s = m_UIState;
var d = m_SerializedAsset;
var o = this;
m_SerializedHDProbe = new SerializedPlanarReflectionProbe(serializedObject);
base.OnEnable();
s.Update();
d.Update();
PlanarReflectionProbeUI.Inspector.Draw(s, d, o);
d.Apply();
PlanarReflectionProbe probe = (PlanarReflectionProbe)target;
probe.influenceVolume.Init(probe);
void OnSceneGUI()
protected override void OnSceneGUI()
for (var i = 0; i < m_TypedTargets.Length; i++)
{
m_UIHandleState[i].Update();
m_UIHandleState[i].influenceVolume.showInfluenceHandles = m_UIState.influenceVolume.isSectionExpandedShape.target;
m_UIHandleState[i].showCaptureHandles = m_UIState.isSectionExpandedCaptureSettings.target;
PlanarReflectionProbeUI.DrawHandles(m_UIHandleState[i], m_TypedTargets[i], this);
}
base.OnSceneGUI();
const float k_PreviewHeight = 128;
List<Texture> m_PreviewedTextures = new List<Texture>();
for (var i = 0; i < m_TypedTargets.Length; i++)
foreach(PlanarReflectionProbe p in m_TypedTargets)
var p = m_TypedTargets[i];
if (p.texture == null)
continue;

if (Event.current.type == EventType.Repaint)
{
var c = new Rect(cameraRect);
for (var i = 0; i < m_TypedTargets.Length; i++)
foreach(PlanarReflectionProbe p in m_TypedTargets)
var p = m_TypedTargets[i];
if (p.texture == null)
continue;

public override bool HasPreviewGUI()
{
for (var i = 0; i < m_TypedTargets.Length; i++)
foreach(PlanarReflectionProbe p in m_TypedTargets)
if (m_TypedTargets[i].texture != null)
if (p.texture != null)
return true;
}
return false;

public override void OnPreviewGUI(Rect r, GUIStyle background)
{
m_PreviewedTextures.Clear();
for (var i = 0; i < m_TypedTargets.Length; i++)
m_PreviewedTextures.Add(m_TypedTargets[i].texture);
foreach (PlanarReflectionProbe p in m_TypedTargets)
{
m_PreviewedTextures.Add(p.texture);
}
for (var i = 0; i < m_TypedTargets.Length; i++)
for (var i = 0; i < m_PreviewedTextures.Count; i++)
{
var row = i / rowSize;
var col = i % rowSize;

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeEditor.cs.meta


fileFormatVersion: 2
guid: 7f189b572cf7bf04d9f1976dcc75c942
guid: 01721b4a922692f4d80ef10751baa70c
MonoImporter:
externalObjects: {}
serializedVersion: 2

212
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Handles.cs


using System;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
#if false
static readonly Color k_GizmoCamera = new Color(233f / 255f, 233f / 255f, 233f / 255f, 128f / 255f);
#endif
public static void DrawHandles(PlanarReflectionProbeUI s, PlanarReflectionProbe d, Editor o)
internal static void DrawHandles(PlanarReflectionProbeUI s, SerializedPlanarReflectionProbe d, Editor o)
var mat = Matrix4x4.TRS(d.transform.position, d.transform.rotation, Vector3.one);
PlanarReflectionProbe probe = d.target;
HDProbeUI.DrawHandles(s, d, o);
switch (EditMode.editMode)
if (probe.useMirrorPlane)
case EditBaseShape:
InfluenceVolumeUI.DrawHandles_EditBase(s.influenceVolume, d.influenceVolume, o, mat, d);
break;
case EditInfluenceShape:
InfluenceVolumeUI.DrawHandles_EditInfluence(s.influenceVolume, d.influenceVolume, o, mat, d);
break;
case EditInfluenceNormalShape:
InfluenceVolumeUI.DrawHandles_EditInfluenceNormal(s.influenceVolume, d.influenceVolume, o, mat, d);
break;
case EditMirrorPosition:
{
EditorGUI.BeginChangeCheck();
var m = Handles.matrix;
Handles.matrix = mat;
var p = Handles.PositionHandle(d.captureMirrorPlaneLocalPosition, d.transform.rotation);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(d, "Translate Mirror Plane");
d.captureMirrorPlaneLocalPosition = p;
EditorUtility.SetDirty(d);
}
Handles.matrix = m;
break;
}
case EditMirrorRotation:
{
EditorGUI.BeginChangeCheck();
var m = Handles.matrix;
Handles.matrix = mat;
var q = Quaternion.LookRotation(d.captureMirrorPlaneLocalNormal, Vector3.up);
q = Handles.RotationHandle(q, d.captureMirrorPlaneLocalPosition);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(d, "Rotate Mirror Plane");
d.captureMirrorPlaneLocalNormal = q * Vector3.forward;
EditorUtility.SetDirty(d);
}
Handles.matrix = m;
break;
}
case EditCenter:
var m = Handles.matrix;
var mat = Matrix4x4.TRS(probe.transform.position, probe.transform.rotation, Vector3.one*1.5f);
using (new Handles.DrawingScope(k_GizmoMirrorPlaneCamera, mat))
EditorGUI.BeginChangeCheck();
var m = Handles.matrix;
Handles.matrix = mat;
var p = Handles.PositionHandle(d.captureLocalPosition, d.transform.rotation);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(d, "Translate Capture Position");
d.captureLocalPosition = p;
EditorUtility.SetDirty(d);
}
Handles.matrix = m;
break;
Handles.ArrowHandleCap(
0,
probe.captureMirrorPlaneLocalPosition,
Quaternion.LookRotation(probe.captureMirrorPlaneLocalNormal),
HandleUtility.GetHandleSize(probe.captureMirrorPlaneLocalPosition),
Event.current.type
);
if (d.useMirrorPlane)
{
var m = Handles.matrix;
Handles.matrix = mat;
Handles.color = k_GizmoMirrorPlaneCamera;
Handles.ArrowHandleCap(
0,
d.captureMirrorPlaneLocalPosition,
Quaternion.LookRotation(d.captureMirrorPlaneLocalNormal),
HandleUtility.GetHandleSize(d.captureMirrorPlaneLocalPosition),
Event.current.type
);
Handles.matrix = m;
}
if (d.proxyVolume != null)
ReflectionProxyVolumeComponentUI.DrawHandles_EditNone(s.reflectionProxyVolume, d.proxyVolume);
public static void DrawGizmos(PlanarReflectionProbe d, GizmoType gizmoType)
internal static void DrawGizmos(PlanarReflectionProbe d, GizmoType gizmoType)
PlanarReflectionProbeUI s;
if (!PlanarReflectionProbeEditor.TryGetUIStateFor(d, out s))
return;
var mat = Matrix4x4.TRS(d.transform.position, d.transform.rotation, Vector3.one);
switch (EditMode.editMode)
{
case EditBaseShape:
InfluenceVolumeUI.DrawGizmos(
s.influenceVolume,
d.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.Base,
InfluenceVolumeUI.HandleType.All);
break;
case EditInfluenceShape:
InfluenceVolumeUI.DrawGizmos(
s.influenceVolume,
d.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.Influence,
InfluenceVolumeUI.HandleType.All);
break;
case EditInfluenceNormalShape:
InfluenceVolumeUI.DrawGizmos(
s.influenceVolume,
d.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.InfluenceNormal,
InfluenceVolumeUI.HandleType.All);
break;
default:
{
var showedHandles = s.influenceVolume.showInfluenceHandles
? InfluenceVolumeUI.HandleType.All
: InfluenceVolumeUI.HandleType.Base;
InfluenceVolumeUI.DrawGizmos(
s.influenceVolume,
d.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.None,
showedHandles);
break;
}
}
if (d.proxyVolume != null)
ReflectionProxyVolumeComponentUI.DrawGizmos_EditNone(s.reflectionProxyVolume, d.proxyVolume);
HDProbeUI.DrawGizmos(d, gizmoType);
var showFrustrum = s.showCaptureHandles
|| EditMode.editMode == EditCenter;
var showCaptureMirror = d.useMirrorPlane
|| EditMode.editMode == EditMirrorPosition
|| EditMode.editMode == EditMirrorRotation;
HDProbeUI s;
if (!HDProbeEditor.TryGetUIStateFor(d, out s))
return;
if (showFrustrum)
DrawGizmos_CaptureFrustrum(s, d);
if (s.showCaptureHandles || EditMode.editMode == EditCenter)
DrawGizmos_CaptureFrustrum(d);
if (showCaptureMirror)
DrawGizmos_CaptureMirror(s, d);
if (d.useMirrorPlane)
DrawGizmos_CaptureMirror(d);
static void DrawGizmos_CaptureMirror(PlanarReflectionProbeUI s, PlanarReflectionProbe d)
static void DrawGizmos_CaptureMirror(PlanarReflectionProbe d)
{
var c = Gizmos.color;
var m = Gizmos.matrix;

Gizmos.color = c;
}
static void DrawGizmos_CaptureFrustrum(PlanarReflectionProbeUI s, PlanarReflectionProbe d)
static void DrawGizmos_CaptureFrustrum(PlanarReflectionProbe d)
{
var viewerCamera = Camera.current;
var c = Gizmos.color;

out aspect, out fov, out clearFlags, out backgroundColor,
out worldToCameraRHS, out projection,
out capturePosition, out captureRotation, viewerCamera);
#if false
// TODO: fix frustrum drawing
var viewProj = projection * worldToCameraRHS;
var invViewProj = viewProj.inverse;
var near = new[]
{
new Vector3(-1, -1, -1),
new Vector3(-1, 1, -1),
new Vector3(1, 1, -1),
new Vector3(1, -1, -1),
};
var far = new[]
{
new Vector3(-1, -1, 1),
new Vector3(-1, 1, 1),
new Vector3(1, 1, 1),
new Vector3(1, -1, 1),
};
for (var i = 0; i < near.Length; ++i)
{
var p = invViewProj * new Vector4(near[i].x, near[i].y, near[i].z, 1);
var w = Mathf.Abs(p.w);
near[i].Set(p.x / w, p.y / w, p.z / w);
}
for (var i = 0; i < far.Length; ++i)
{
var p = invViewProj * new Vector4(far[i].x, far[i].y, far[i].z, 1);
var w = Mathf.Abs(p.w);
far[i].Set(p.x / w, p.y / w, p.z / w);
}
Gizmos.color = k_GizmoCamera;
for (var i = 0; i < 4; ++i)
{
Gizmos.DrawLine(near[i], near[(i + 1) % 4]);
Gizmos.DrawLine(far[i], far[(i + 1) % 4]);
Gizmos.DrawLine(near[i], far[i]);
}
Gizmos.matrix = m;
#endif
Gizmos.DrawSphere(capturePosition, HandleUtility.GetHandleSize(capturePosition) * 0.2f);
Gizmos.color = c;

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Handles.cs.meta


fileFormatVersion: 2
guid: 8ee668677cd59784d8fb06a531b49a77
guid: a5aea6d1bf1e73b4ab7307bcab55151d
MonoImporter:
externalObjects: {}
serializedVersion: 2

121
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.cs


using System;
using UnityEditor.AnimatedValues;
using UnityEngine.Events;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine.Rendering;
partial class PlanarReflectionProbeUI : BaseUI<SerializedPlanarReflectionProbe>
using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine.Rendering;
using CED = CoreEditorDrawer<HDProbeUI, SerializedHDProbe>;
partial class PlanarReflectionProbeUI : HDProbeUI
const int k_AnimBoolFields = 6;
static readonly int k_ReflectionProbeModeModeCount = Enum.GetValues(typeof(ReflectionProbeMode)).Length;
static readonly int k_AnimBoolTotal = k_AnimBoolFields + k_ReflectionProbeModeModeCount;
static readonly GUIContent overrideFieldOfViewContent = CoreEditorUtils.GetContent("Override Field Of View");
static readonly GUIContent fieldOfViewSolidAngleContent = CoreEditorUtils.GetContent("Field Of View");
public InfluenceVolumeUI influenceVolume = new InfluenceVolumeUI();
public FrameSettingsUI frameSettings = new FrameSettingsUI();
public ReflectionProxyVolumeComponentUI reflectionProxyVolume = new ReflectionProxyVolumeComponentUI();
public static CED.IDrawer Inspector;
public static readonly CED.IDrawer SectionFoldoutCaptureSettings = CED.FoldoutGroup(
"Capture Settings",
(s, d, o) => s.isSectionExpandedCaptureSettings,
FoldoutOption.Indent,
CED.Action(Drawer_SectionCaptureSettings)
);
public AnimBool isSectionExpandedInfluenceSettings { get { return m_AnimBools[k_ReflectionProbeModeModeCount]; } }
public AnimBool isSectionExpandedCaptureSettings { get { return m_AnimBools[k_ReflectionProbeModeModeCount + 1]; } }
public AnimBool isSectionExpandedCaptureMirrorSettings { get { return m_AnimBools[k_ReflectionProbeModeModeCount + 2]; } }
public AnimBool isSectionExpandedCaptureStaticSettings { get { return m_AnimBools[k_ReflectionProbeModeModeCount + 3]; } }
public AnimBool isSectionExpendedProxyVolume { get { return m_AnimBools[k_ReflectionProbeModeModeCount + 4]; } }
public AnimBool isSectionExpendedAdditionalSettings { get { return m_AnimBools[k_ReflectionProbeModeModeCount + 5]; } }
public bool showCaptureHandles { get; set; }
public PlanarReflectionProbeUI()
: base(k_AnimBoolTotal)
static PlanarReflectionProbeUI()
isSectionExpandedInfluenceSettings.value = true;
isSectionExpandedCaptureSettings.value = true;
isSectionExpendedProxyVolume.value = true;
isSectionExpendedAdditionalSettings.value = false;
Inspector = CED.Group(
CED.Action(Drawer_Toolbars),
CED.space,
ProxyVolumeSettings,
CED.Select(
(s, d, o) => s.influenceVolume,
(s, d, o) => d.influenceVolume,
InfluenceVolumeUI.SectionFoldoutShapePlanar
),
CED.Action(Drawer_DifferentShapeError),
SectionFoldoutCaptureSettings,
SectionFoldoutAdditionalSettings,
CED.Select(
(s, d, o) => s.frameSettings,
(s, d, o) => d.frameSettings,
FrameSettingsUI.Inspector
),
CED.space,
CED.Action(Drawer_SectionBakeButton)
);
public AnimBool IsSectionExpandedReflectionProbeMode(ReflectionProbeMode mode)
protected static void Drawer_SectionCaptureSettings(HDProbeUI s, SerializedHDProbe d, Editor o)
return m_AnimBools[(int)mode];
SerializedPlanarReflectionProbe serialized = (SerializedPlanarReflectionProbe)d;
var hdrp = GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset;
GUI.enabled = false;
EditorGUILayout.LabelField(
CoreEditorUtils.GetContent("Probe Texture Size (Set By HDRP)"),
CoreEditorUtils.GetContent(hdrp.renderPipelineSettings.lightLoopSettings.planarReflectionTextureSize.ToString()),
EditorStyles.label);
EditorGUILayout.Toggle(
CoreEditorUtils.GetContent("Probe Compression (Set By HDRP)"),
hdrp.renderPipelineSettings.lightLoopSettings.planarReflectionCacheCompressed);
GUI.enabled = true;
bool on = serialized.overrideFieldOfView.boolValue;
EditorGUI.BeginChangeCheck();
on = EditorGUILayout.Toggle(overrideFieldOfViewContent, on);
if (on)
{
serialized.fieldOfViewOverride.floatValue = EditorGUILayout.FloatField(fieldOfViewSolidAngleContent, serialized.fieldOfViewOverride.floatValue);
}
if (EditorGUI.EndChangeCheck())
{
serialized.overrideFieldOfView.boolValue = on;
serialized.Apply();
}
//GUI.enabled = false;
//EditorGUILayout.LabelField(resolutionContent, CoreEditorUtils.GetContent(((int)hdrp.GetRenderPipelineSettings().lightLoopSettings.reflectionCubemapSize).ToString()));
//EditorGUILayout.LabelField(shadowDistanceContent, EditorStyles.label);
//EditorGUILayout.LabelField(cullingMaskContent, EditorStyles.label);
//EditorGUILayout.LabelField(useOcclusionCullingContent, EditorStyles.label);
//EditorGUILayout.LabelField(nearClipCullingContent, EditorStyles.label);
//EditorGUILayout.LabelField(farClipCullingContent, EditorStyles.label);
//GUI.enabled = true;
public override void Reset(SerializedPlanarReflectionProbe data, UnityAction repaint)
internal PlanarReflectionProbeUI()
reflectionProxyVolume.Reset(data.reflectionProxyVolume, repaint);
frameSettings.Reset(data.frameSettings, repaint);
influenceVolume.Reset(data.influenceVolume, repaint);
base.Reset(data, repaint);
toolBars = new[] { ToolBar.InfluenceShape | ToolBar.Blend };
for (var i = 0; i < k_ReflectionProbeModeModeCount; i++)
m_AnimBools[i].target = i == data.mode.intValue;
isSectionExpandedCaptureMirrorSettings.target = data.isMirrored;
isSectionExpandedCaptureStaticSettings.target = !data.isMirrored;
reflectionProxyVolume.Update();
frameSettings.Update();
influenceVolume.Update();
SerializedPlanarReflectionProbe serialized = data as SerializedPlanarReflectionProbe;
isSectionExpandedCaptureMirrorSettings.target = serialized.isMirrored;
isSectionExpandedCaptureStaticSettings.target = !serialized.isMirrored;
base.Update();
}
}

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.cs.meta


fileFormatVersion: 2
guid: f23cf1efede7335468bfa23bd1838cd2
guid: d6d4b9e119caf434784239e203f89e05
MonoImporter:
externalObjects: {}
serializedVersion: 2

109
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/SerializedHDReflectionProbe.cs


namespace UnityEditor.Experimental.Rendering.HDPipeline
{
internal class SerializedHDReflectionProbe
internal class SerializedHDReflectionProbe : SerializedHDProbe
internal ReflectionProbe target;
internal HDAdditionalReflectionData targetData;
internal SerializedObject so;
internal SerializedObject addso;
internal SerializedObject serializedLegacyObject;
internal SerializedProperty mode;
internal SerializedProperty refreshMode;
internal SerializedProperty intensityMultiplier;
internal SerializedProperty legacyBlendDistance;
internal SerializedProperty boxSize;
internal SerializedProperty boxOffset;
internal SerializedProperty resolution;
internal SerializedProperty shadowDistance;
internal SerializedProperty cullingMask;
internal SerializedProperty useOcclusionCulling;
internal SerializedProperty nearClip;
internal SerializedProperty farClip;
internal SerializedProperty boxProjection;
internal SerializedProperty weight;
internal SerializedProperty multiplier;
internal SerializedProperty proxyVolumeComponent;
SerializedProperty legacyBlendDistance;
SerializedProperty legacySize;
SerializedProperty legacyOffset;
SerializedProperty legacyMode;
internal SerializedInfluenceVolume influenceVolume;
internal new HDAdditionalReflectionData target { get { return serializedObject.targetObject as HDAdditionalReflectionData; } }
internal ReflectionProbe targetLegacy { get { return serializedLegacyObject.targetObject as ReflectionProbe; } }
public SerializedHDReflectionProbe(SerializedObject so, SerializedObject addso)
public SerializedHDReflectionProbe(SerializedObject legacyProbe, SerializedObject additionalData) : base(additionalData)
this.so = so;
this.addso = addso;
serializedLegacyObject = legacyProbe;
proxyVolumeComponent = addso.Find((HDAdditionalReflectionData d) => d.proxyVolume);
influenceVolume = new SerializedInfluenceVolume(addso.Find((HDAdditionalReflectionData d) => d.influenceVolume));
target = (ReflectionProbe)so.targetObject;
targetData = target.GetComponent<HDAdditionalReflectionData>();
mode = so.FindProperty("m_Mode");
customBakedTexture = so.FindProperty("m_CustomBakedTexture");
renderDynamicObjects = so.FindProperty("m_RenderDynamicObjects");
refreshMode = so.FindProperty("m_RefreshMode");
timeSlicingMode = so.FindProperty("m_TimeSlicingMode");
intensityMultiplier = so.FindProperty("m_IntensityMultiplier");
boxSize = so.FindProperty("m_BoxSize");
boxOffset = so.FindProperty("m_BoxOffset");
resolution = so.FindProperty("m_Resolution");
shadowDistance = so.FindProperty("m_ShadowDistance");
cullingMask = so.FindProperty("m_CullingMask");
useOcclusionCulling = so.FindProperty("m_UseOcclusionCulling");
nearClip = so.FindProperty("m_NearClip");
farClip = so.FindProperty("m_FarClip");
boxProjection = so.FindProperty("m_BoxProjection");
legacyBlendDistance = so.FindProperty("m_BlendDistance");
weight = addso.Find((HDAdditionalReflectionData d) => d.weight);
multiplier = addso.Find((HDAdditionalReflectionData d) => d.multiplier);
customBakedTexture = legacyProbe.FindProperty("m_CustomBakedTexture");
renderDynamicObjects = legacyProbe.FindProperty("m_RenderDynamicObjects");
timeSlicingMode = legacyProbe.FindProperty("m_TimeSlicingMode");
legacySize = legacyProbe.FindProperty("m_BoxSize");
legacyOffset = legacyProbe.FindProperty("m_BoxOffset");
resolution = legacyProbe.FindProperty("m_Resolution");
shadowDistance = legacyProbe.FindProperty("m_ShadowDistance");
cullingMask = legacyProbe.FindProperty("m_CullingMask");
useOcclusionCulling = legacyProbe.FindProperty("m_UseOcclusionCulling");
nearClip = legacyProbe.FindProperty("m_NearClip");
farClip = legacyProbe.FindProperty("m_FarClip");
legacyBlendDistance = legacyProbe.FindProperty("m_BlendDistance");
legacyMode = legacyProbe.FindProperty("m_Mode");
public void Update()
internal override void Update()
so.Update();
addso.Update();
//InfluenceVolume does not have Update. Add it here if it have in the futur.
serializedLegacyObject.Update();
base.Update();
//check if the transform have been rotated
if (legacyOffset.vector3Value != ((Component)serializedLegacyObject.targetObject).transform.rotation * influenceVolume.offset.vector3Value)
{
//call the offset setter as it will update legacy reflection probe
((HDAdditionalReflectionData)serializedObject.targetObject).influenceVolume.offset = influenceVolume.offset.vector3Value;
}
public void Apply()
internal override void Apply()
so.ApplyModifiedProperties();
addso.ApplyModifiedProperties();
//sync size with legacy reflection probe
switch(target.influenceVolume.shape)
{
case InfluenceShape.Box:
legacySize.vector3Value = influenceVolume.boxSize.vector3Value;
break;
case InfluenceShape.Sphere:
legacySize.vector3Value = Vector3.one * influenceVolume.sphereRadius.floatValue;
break;
}
// Sync mode with legacy reflection probe
legacyMode.intValue = mode.intValue;
serializedLegacyObject.ApplyModifiedProperties();
base.Apply();
//serializedObject.ApplyModifiedProperties(); //done in base methode
}
}
}

81
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/SerializedPlanarReflectionProbe.cs


namespace UnityEditor.Experimental.Rendering.HDPipeline
{
internal class SerializedPlanarReflectionProbe
internal class SerializedPlanarReflectionProbe : SerializedHDProbe
internal SerializedObject serializedObject;
internal SerializedProperty proxyVolumeReference;
internal SerializedReflectionProxyVolumeComponent reflectionProxyVolume;
internal SerializedInfluenceVolume influenceVolume;
internal SerializedProperty captureNearPlane;
internal SerializedProperty captureFarPlane;
internal SerializedProperty weight;
internal SerializedProperty multiplier;
internal SerializedProperty mode;
internal SerializedProperty refreshMode;
internal SerializedFrameSettings frameSettings;
internal PlanarReflectionProbe target { get { return serializedObject.targetObject as PlanarReflectionProbe; } }
internal new PlanarReflectionProbe target { get { return serializedObject.targetObject as PlanarReflectionProbe; } }
internal bool isMirrored
{

}
}
internal SerializedPlanarReflectionProbe(SerializedObject serializedObject)
internal SerializedPlanarReflectionProbe(SerializedObject serializedObject) : base(serializedObject)
this.serializedObject = serializedObject;
proxyVolumeReference = serializedObject.Find((PlanarReflectionProbe p) => p.proxyVolume);
influenceVolume = new SerializedInfluenceVolume(serializedObject.Find((PlanarReflectionProbe p) => p.influenceVolume));
captureNearPlane = serializedObject.Find((PlanarReflectionProbe p) => p.captureNearPlane);
captureFarPlane = serializedObject.Find((PlanarReflectionProbe p) => p.captureFarPlane);
nearClip = serializedObject.Find((PlanarReflectionProbe p) => p.captureNearPlane);
farClip = serializedObject.Find((PlanarReflectionProbe p) => p.captureFarPlane);
weight = serializedObject.Find((PlanarReflectionProbe p) => p.weight);
multiplier = serializedObject.Find((PlanarReflectionProbe p) => p.multiplier);
mode = serializedObject.Find((PlanarReflectionProbe p) => p.mode);
refreshMode = serializedObject.Find((PlanarReflectionProbe p) => p.refreshMode);
frameSettings = new SerializedFrameSettings(serializedObject.Find((PlanarReflectionProbe p) => p.frameSettings));
InstantiateProxyVolume(serializedObject);
influenceVolume.editorSimplifiedModeBlendNormalDistance.floatValue = 0;
void InstantiateProxyVolume(SerializedObject serializedObject)
{
var objs = new List<Object>();
for (var i = 0; i < serializedObject.targetObjects.Length; i++)
{
var p = ((PlanarReflectionProbe)serializedObject.targetObjects[i]).proxyVolume;
if (p != null)
objs.Add(p);
}
reflectionProxyVolume = objs.Count > 0
? new SerializedReflectionProxyVolumeComponent(new SerializedObject(objs.ToArray()))
: null;
}
public void Update()
internal override void Update()
serializedObject.Update();
base.Update();
//temporarily force value until other mode are supported
var updateProxyVolume = reflectionProxyVolume != null
&& serializedObject.targetObjects.Length != reflectionProxyVolume.serializedObject.targetObjects.Length;
if (!updateProxyVolume && reflectionProxyVolume != null)
{
var proxyVolumeTargets = reflectionProxyVolume.serializedObject.targetObjects;
for (var i = 0; i < serializedObject.targetObjects.Length; i++)
{
if (proxyVolumeTargets[i] != ((PlanarReflectionProbe)serializedObject.targetObjects[i]).proxyVolume)
{
updateProxyVolume = true;
break;
}
}
}
if (updateProxyVolume)
InstantiateProxyVolume(serializedObject);
public void Apply()
{
serializedObject.ApplyModifiedProperties();
if (reflectionProxyVolume != null)
reflectionProxyVolume.Apply();
}
}
}

163
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Drawers.cs


partial class InfluenceVolumeUI
{
//[TODO: planar / non planar will be redone in next PR]
public static readonly CED.IDrawer SectionFoldoutShapePlanar;
public static readonly CED.IDrawer SectionFoldoutShape;
public static readonly CED.IDrawer SectionShapeBoxPlanar = CED.Action((s, p, o) => Drawer_SectionShapeBox(s,p,o,false,false));
public static readonly CED.IDrawer SectionShapeBox = CED.Action((s, p, o) => Drawer_SectionShapeBox(s, p, o, true, true));
public static readonly CED.IDrawer SectionShapeSpherePlanar = CED.Action((s, p, o) => Drawer_SectionShapeSphere(s, p, o, false, false));
public static readonly CED.IDrawer SectionShapeSphere = CED.Action((s, p, o) => Drawer_SectionShapeSphere(s, p, o, true, true));
internal static readonly CED.IDrawer SectionFoldoutShapePlanar;
internal static readonly CED.IDrawer SectionFoldoutShape;
static readonly CED.IDrawer SectionShapeBoxPlanar = CED.Action((s, p, o) => Drawer_SectionShapeBox( s, p, o, false, false, false));
static readonly CED.IDrawer SectionShapeBox = CED.Action((s, p, o) => Drawer_SectionShapeBox(s, p, o, true, true, true));
static readonly CED.IDrawer SectionShapeSpherePlanar = CED.Action((s, p, o) => Drawer_SectionShapeSphere(s, p, o, false, false));
static readonly CED.IDrawer SectionShapeSphere = CED.Action((s, p, o) => Drawer_SectionShapeSphere(s, p, o, true, true));
"Influence Volume",
influenceVolumeHeader,
(s, d, o) => s.isSectionExpandedShape,
FoldoutOption.Indent,
CED.Action(Drawer_InfluenceAdvancedSwitch),

);
SectionFoldoutShape = CED.Group(
CED.FoldoutGroup(
"Influence Volume",
influenceVolumeHeader,
(s, d, o) => s.isSectionExpandedShape,
FoldoutOption.Indent,
CED.Action(Drawer_InfluenceAdvancedSwitch),

static void Drawer_FieldShapeType(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o)
{
EditorGUILayout.PropertyField(d.shape, _.GetContent("Shape Type"));
EditorGUILayout.PropertyField(d.shape, shapeContent);
}
static void Drawer_InfluenceAdvancedSwitch(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor owner)

GUILayout.FlexibleSpace();
if (d.shape.intValue == (int)InfluenceShape.Sphere)
{
GUI.enabled = false;
}
advanced = !GUILayout.Toggle(!advanced, CoreEditorUtils.GetContent("Normal|Normal parameters mode (only change for box shape)."), EditorStyles.miniButtonLeft, GUILayout.Width(60f), GUILayout.ExpandWidth(false));
advanced = GUILayout.Toggle(advanced, CoreEditorUtils.GetContent("Advanced|Advanced parameters mode (only change for box shape)."), EditorStyles.miniButtonRight, GUILayout.Width(60f), GUILayout.ExpandWidth(false));
advanced = !GUILayout.Toggle(!advanced, normalModeContent, EditorStyles.miniButtonLeft, GUILayout.Width(60f), GUILayout.ExpandWidth(false));
advanced = GUILayout.Toggle(advanced, advancedModeContent, EditorStyles.miniButtonRight, GUILayout.Width(60f), GUILayout.ExpandWidth(false));
s.boxInfluenceHandle.allHandleControledByOne = s.boxInfluenceNormalHandle.allHandleControledByOne = !advanced;
if (d.editorAdvancedModeEnabled.boolValue ^ advanced)
{

d.boxBlendDistanceNegative.vector3Value = d.editorAdvancedModeBlendDistanceNegative.vector3Value;
d.boxBlendNormalDistancePositive.vector3Value = d.editorAdvancedModeBlendNormalDistancePositive.vector3Value;
d.boxBlendNormalDistanceNegative.vector3Value = d.editorAdvancedModeBlendNormalDistanceNegative.vector3Value;
d.boxSideFadePositive.vector3Value = d.editorAdvancedModeFaceFadePositive.vector3Value;
d.boxSideFadeNegative.vector3Value = d.editorAdvancedModeFaceFadeNegative.vector3Value;
d.boxSideFadeNegative.vector3Value = d.boxSideFadePositive.vector3Value = Vector3.one;
if (d.shape.intValue == (int)InfluenceShape.Sphere)
{
GUI.enabled = true;
}
static void Drawer_SectionShapeBox(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o, bool drawOffset, bool drawNormal)
static void Drawer_SectionShapeBox(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o, bool drawOffset, bool drawNormal, bool drawFace)
{
bool advanced = d.editorAdvancedModeEnabled.boolValue;
var maxFadeDistance = d.boxSize.vector3Value * 0.5f;

EditorGUILayout.PropertyField(d.boxSize, _.GetContent("Box Size"));
PlanarReflectionProbeUI.Drawer_ToolBarButton(0, o, GUILayout.Width(28f), GUILayout.MinHeight(22f));
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(d.boxSize, boxSizeContent);
if (EditorGUI.EndChangeCheck())
{
Vector3 blendPositive = d.boxBlendDistancePositive.vector3Value;
Vector3 blendNegative = d.boxBlendDistanceNegative.vector3Value;
Vector3 blendNormalPositive = d.boxBlendNormalDistancePositive.vector3Value;
Vector3 blendNormalNegative = d.boxBlendNormalDistanceNegative.vector3Value;
Vector3 size = d.boxSize.vector3Value;
for(int i = 0; i<3; ++i)
{
size[i] = Mathf.Max(0f, size[i]);
}
d.boxSize.vector3Value = size;
Vector3 halfSize = size * .5f;
for (int i = 0; i < 3; ++i)
{
blendPositive[i] = Mathf.Clamp(blendPositive[i], 0f, halfSize[i]);
blendNegative[i] = Mathf.Clamp(blendNegative[i], 0f, halfSize[i]);
blendNormalPositive[i] = Mathf.Clamp(blendNormalPositive[i], 0f, halfSize[i]);
blendNormalNegative[i] = Mathf.Clamp(blendNormalNegative[i], 0f, halfSize[i]);
}
d.boxBlendDistancePositive.vector3Value = blendPositive;
d.boxBlendDistanceNegative.vector3Value = blendNegative;
d.boxBlendNormalDistancePositive.vector3Value = blendNormalPositive;
d.boxBlendNormalDistanceNegative.vector3Value = blendNormalNegative;
if (d.editorAdvancedModeEnabled.boolValue)
{
d.editorAdvancedModeBlendDistancePositive.vector3Value = d.boxBlendDistancePositive.vector3Value;
d.editorAdvancedModeBlendDistanceNegative.vector3Value = d.boxBlendDistanceNegative.vector3Value;
d.editorAdvancedModeBlendNormalDistancePositive.vector3Value = d.boxBlendNormalDistancePositive.vector3Value;
d.editorAdvancedModeBlendNormalDistanceNegative.vector3Value = d.boxBlendNormalDistanceNegative.vector3Value;
}
else
{
d.editorSimplifiedModeBlendDistance.floatValue = Mathf.Max(blendPositive.x, blendPositive.y, blendPositive.z, blendNegative.x, blendNegative.y, blendNegative.z);
d.boxBlendDistancePositive.vector3Value = d.boxBlendDistanceNegative.vector3Value = Vector3.one * d.editorSimplifiedModeBlendDistance.floatValue;
d.editorSimplifiedModeBlendNormalDistance.floatValue = Mathf.Max(blendNormalPositive.x, blendNormalPositive.y, blendNormalPositive.z, blendNormalNegative.x, blendNormalNegative.y, blendNormalNegative.z);
d.boxBlendNormalDistancePositive.vector3Value = d.boxBlendNormalDistanceNegative.vector3Value = Vector3.one * d.editorSimplifiedModeBlendNormalDistance.floatValue;
}
}
HDProbeUI.Drawer_ToolBarButton(HDProbeUI.ToolBar.InfluenceShape, o, GUILayout.Width(28f), GUILayout.MinHeight(22f));
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(d.offset, _.GetContent("Offset"));
HDReflectionProbeUI.Drawer_ToolBarButton(3, o, GUILayout.Width(28f), GUILayout.MinHeight(22f));
EditorGUILayout.EndHorizontal();
Drawer_Offset(s, d, o);
GUILayout.Space(EditorGUIUtility.standardVerticalSpacing);
Drawer_AdvancedBlendDistance(
d,
false,
maxFadeDistance,
CoreEditorUtils.GetContent("Blend Distance|Area around the probe where it is blended with other probes. Only used in deferred probes.")
);
PlanarReflectionProbeUI.Drawer_ToolBarButton(1, o, GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight((advanced ? 3 : 1) * (EditorGUIUtility.singleLineHeight + 3)));
Drawer_AdvancedBlendDistance(d, false, maxFadeDistance, blendDistanceContent);
HDProbeUI.Drawer_ToolBarButton(HDProbeUI.ToolBar.Blend, o, GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight((advanced ? 2 : 1) * (EditorGUIUtility.singleLineHeight + 3)));
GUILayout.Space(EditorGUIUtility.standardVerticalSpacing * 2f);
Drawer_AdvancedBlendDistance(
d,
true,
maxFadeDistance,
CoreEditorUtils.GetContent("Blend Normal Distance|Area around the probe where the normals influence the probe. Only used in deferred probes.")
);
PlanarReflectionProbeUI.Drawer_ToolBarButton(2, o, GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight((advanced ? 3 : 1) * (EditorGUIUtility.singleLineHeight + 3)));
Drawer_AdvancedBlendDistance(d, true, maxFadeDistance, blendNormalDistanceContent);
HDProbeUI.Drawer_ToolBarButton(HDProbeUI.ToolBar.NormalBlend, o, GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight((advanced ? 2 : 1) * (EditorGUIUtility.singleLineHeight + 3)));
GUILayout.Space(EditorGUIUtility.standardVerticalSpacing * 2f);
if (advanced)
if (advanced && drawFace)
CoreEditorUtils.DrawVector6(
CoreEditorUtils.GetContent("Face fade|Fade faces of the cubemap."),
d.boxSideFadePositive, d.boxSideFadeNegative, Vector3.zero, Vector3.one, HDReflectionProbeEditor.k_handlesColor);
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
CoreEditorUtils.DrawVector6(faceFadeContent, d.editorAdvancedModeFaceFadePositive, d.editorAdvancedModeFaceFadeNegative, Vector3.zero, Vector3.one, HDReflectionProbeEditor.k_handlesColor);
if (EditorGUI.EndChangeCheck())
{
d.boxSideFadePositive.vector3Value = d.editorAdvancedModeFaceFadePositive.vector3Value;
d.boxSideFadeNegative.vector3Value = d.editorAdvancedModeFaceFadeNegative.vector3Value;
}
GUILayout.Space(28f + 9f); //add right margin for alignment
EditorGUILayout.EndHorizontal();
GUILayout.Space(EditorGUIUtility.standardVerticalSpacing * 2f);
}
}

distance = EditorGUILayout.FloatField(content, distance);
if (EditorGUI.EndChangeCheck())
{
distance = Mathf.Clamp(distance, 0f, Mathf.Max(maxBlendDistance.x, maxBlendDistance.y, maxBlendDistance.z));
Vector3 decal = Vector3.one * distance;
bdp.x = Mathf.Clamp(decal.x, 0f, maxBlendDistance.x);
bdp.y = Mathf.Clamp(decal.y, 0f, maxBlendDistance.y);

{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(d.sphereRadius, _.GetContent("Radius"));
PlanarReflectionProbeUI.Drawer_ToolBarButton(0, o, GUILayout.Width(28f), GUILayout.MinHeight(22f));
EditorGUILayout.PropertyField(d.sphereRadius, radiusContent);
HDProbeUI.Drawer_ToolBarButton(HDProbeUI.ToolBar.InfluenceShape, o, GUILayout.Width(28f), GUILayout.MinHeight(22f));
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(d.offset, _.GetContent("Offset"));
HDReflectionProbeUI.Drawer_ToolBarButton(3, o, GUILayout.Width(28f), GUILayout.MinHeight(22f));
EditorGUILayout.EndHorizontal();
Drawer_Offset(s, d, o);
}
EditorGUILayout.Space();

EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(d.sphereBlendDistance, _.GetContent("Blend Distance|Area around the probe where it is blended with other probes. Only used in deferred probes."));
EditorGUILayout.PropertyField(d.sphereBlendDistance, blendDistanceContent);
PlanarReflectionProbeUI.Drawer_ToolBarButton(1, o, GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight + 3));
HDProbeUI.Drawer_ToolBarButton(HDProbeUI.ToolBar.Blend, o, GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight + 3));
EditorGUILayout.EndHorizontal();
if (drawNormal)

EditorGUILayout.PropertyField(d.sphereBlendNormalDistance, _.GetContent("Blend Distance|Area around the probe where it is blended with other probes. Only used in deferred probes."));
EditorGUILayout.PropertyField(d.sphereBlendNormalDistance, blendNormalDistanceContent);
PlanarReflectionProbeUI.Drawer_ToolBarButton(2, o, GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight + 3));
HDProbeUI.Drawer_ToolBarButton(HDProbeUI.ToolBar.NormalBlend, o, GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight(EditorGUIUtility.singleLineHeight + 3));
}
static void Drawer_Offset(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o)
{
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(d.offset, offsetContent);
if(EditorGUI.EndChangeCheck())
{
//call the offset setter as it will update legacy reflection probe
HDProbeEditor editor = (HDProbeEditor)o;
InfluenceVolume influenceVolume = editor.GetTarget(editor.target).influenceVolume;
influenceVolume.offset = d.offset.vector3Value;
}
HDProbeUI.Drawer_ToolBarButton(HDProbeUI.ToolBar.CapturePosition, o, GUILayout.Width(28f), GUILayout.MinHeight(22f));
EditorGUILayout.EndHorizontal();
}
}
}

311
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Handles.cs


{
partial class InfluenceVolumeUI
{
public static void DrawHandles_EditBase(InfluenceVolumeUI s, InfluenceVolume d, Editor o, Matrix4x4 matrix, Object sourceAsset)
public static void DrawHandles_EditBase(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o, Matrix4x4 matrix, Object sourceAsset)
var mat = Handles.matrix;
var c = Handles.color;
Handles.matrix = matrix;
Handles.color = k_GizmoThemeColorBase;
switch (d.shape)
using (new Handles.DrawingScope(k_GizmoThemeColorBase, matrix))
case InfluenceShape.Box:
{
var center = d.offset;
var size = d.boxSize;
DrawBoxHandle(
s, d, o, sourceAsset,
s1 => s1.boxBaseHandle,
ref center,
ref size);
d.offset = center;
d.boxSize = size;
switch ((InfluenceShape)d.shape.intValue)
{
case InfluenceShape.Box:
DrawBoxHandle(s, d, o, sourceAsset, s.boxBaseHandle);
}
case InfluenceShape.Sphere:
{
var center = d.offset;
var radius = d.sphereRadius;
DrawSphereHandle(
s, d, o, sourceAsset,
s1 => s1.sphereBaseHandle,
ref center,
ref radius);
d.offset = center;
d.sphereRadius = radius;
case InfluenceShape.Sphere:
DrawSphereHandle(s, d, o, sourceAsset, s.sphereBaseHandle);
}
}
Handles.matrix = mat;
Handles.color = c;
public static void DrawHandles_EditInfluence(InfluenceVolumeUI s, InfluenceVolume d, Editor o, Matrix4x4 matrix, Object sourceAsset)
public static void DrawHandles_EditInfluence(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o, Matrix4x4 matrix, Object sourceAsset)
var mat = Handles.matrix;
var c = Handles.color;
Handles.matrix = matrix;
Handles.color = k_GizmoThemeColorInfluence;
switch (d.shape)
using (new Handles.DrawingScope(k_GizmoThemeColorInfluence, matrix))
case InfluenceShape.Box:
{
var positive = d.boxBlendDistancePositive;
var negative = d.boxBlendDistanceNegative;
DrawBoxFadeHandle(
s, d, o, sourceAsset,
s1 => s1.boxInfluenceHandle,
d.offset, d.boxSize,
ref positive,
ref negative);
s.data.boxBlendDistancePositive.vector3Value = positive;
s.data.boxBlendDistanceNegative.vector3Value = negative;
//save advanced/simplified saved data
if (s.data.editorAdvancedModeEnabled.boolValue)
switch ((InfluenceShape)d.shape.intValue)
{
case InfluenceShape.Box:
EditorGUI.BeginChangeCheck();
DrawBoxFadeHandle(s, d, o, sourceAsset, s.boxInfluenceHandle, d.boxBlendDistancePositive, d.boxBlendDistanceNegative);
if (EditorGUI.EndChangeCheck())
s.data.editorAdvancedModeBlendDistancePositive.vector3Value = positive;
s.data.editorAdvancedModeBlendDistanceNegative.vector3Value = negative;
}
else
{
s.data.editorSimplifiedModeBlendDistance.floatValue = positive.x;
//save advanced/simplified saved data
if (d.editorAdvancedModeEnabled.boolValue)
{
d.editorAdvancedModeBlendDistancePositive.vector3Value = d.boxBlendDistancePositive.vector3Value;
d.editorAdvancedModeBlendDistanceNegative.vector3Value = d.boxBlendDistanceNegative.vector3Value;
}
else
{
d.editorSimplifiedModeBlendDistance.floatValue = d.boxBlendDistancePositive.vector3Value.x;
}
d.Apply();
s.data.Apply();
}
case InfluenceShape.Sphere:
{
var fade = d.sphereBlendDistance;
DrawSphereFadeHandle(
s, d, o, sourceAsset,
s1 => s1.sphereInfluenceHandle,
d.offset, d.sphereRadius,
ref fade);
d.sphereBlendDistance = fade;
case InfluenceShape.Sphere:
DrawSphereFadeHandle(s, d, o, sourceAsset, s.sphereInfluenceHandle, d.sphereBlendDistance);
}
}
Handles.matrix = mat;
Handles.color = c;
public static void DrawHandles_EditInfluenceNormal(InfluenceVolumeUI s, InfluenceVolume d, Editor o, Matrix4x4 matrix, Object sourceAsset)
public static void DrawHandles_EditInfluenceNormal(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o, Matrix4x4 matrix, Object sourceAsset)
var mat = Handles.matrix;
var c = Handles.color;
Handles.matrix = matrix;
Handles.color = k_GizmoThemeColorInfluenceNormal;
switch (d.shape)
using (new Handles.DrawingScope(k_GizmoThemeColorInfluenceNormal, matrix))
case InfluenceShape.Box:
{
Vector3 positive = d.boxBlendNormalDistancePositive;
Vector3 negative = d.boxBlendNormalDistanceNegative;
DrawBoxFadeHandle(
s, d, o, sourceAsset,
s1 => s1.boxInfluenceNormalHandle,
d.offset, d.boxSize,
ref positive,
ref negative);
s.data.boxBlendNormalDistancePositive.vector3Value = positive;
s.data.boxBlendNormalDistanceNegative.vector3Value = negative;
//save advanced/simplified saved data
if (s.data.editorAdvancedModeEnabled.boolValue)
switch ((InfluenceShape)d.shape.intValue)
{
case InfluenceShape.Box:
EditorGUI.BeginChangeCheck();
DrawBoxFadeHandle(s, d, o, sourceAsset, s.boxInfluenceNormalHandle, d.boxBlendNormalDistancePositive, d.boxBlendNormalDistanceNegative);
if (EditorGUI.EndChangeCheck())
s.data.editorAdvancedModeBlendNormalDistancePositive.vector3Value = positive;
s.data.editorAdvancedModeBlendNormalDistanceNegative.vector3Value = negative;
//save advanced/simplified saved data
if (d.editorAdvancedModeEnabled.boolValue)
{
d.editorAdvancedModeBlendNormalDistancePositive.vector3Value = d.boxBlendNormalDistancePositive.vector3Value;
d.editorAdvancedModeBlendNormalDistanceNegative.vector3Value = d.boxBlendNormalDistanceNegative.vector3Value;
}
else
{
d.editorSimplifiedModeBlendNormalDistance.floatValue = d.boxBlendNormalDistancePositive.vector3Value.x;
}
d.Apply();
else
{
s.data.editorSimplifiedModeBlendNormalDistance.floatValue = positive.x;
}
s.data.Apply();
}
case InfluenceShape.Sphere:
{
var fade = d.sphereBlendNormalDistance;
DrawSphereFadeHandle(
s, d, o, sourceAsset,
s1 => s1.sphereInfluenceNormalHandle,
d.offset, d.sphereRadius,
ref fade);
d.sphereBlendNormalDistance = fade;
case InfluenceShape.Sphere:
DrawSphereFadeHandle(s, d, o, sourceAsset, s.sphereInfluenceNormalHandle, d.sphereBlendNormalDistance);
}
}
Handles.matrix = mat;
Handles.color = c;
static void DrawBoxHandle(
InfluenceVolumeUI s, InfluenceVolume d, Editor o, Object sourceAsset,
Func<InfluenceVolumeUI, Gizmo6FacesBox> boundsGetter,
ref Vector3 center, ref Vector3 size)
static void DrawBoxHandle(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o, Object sourceAsset, Gizmo6FacesBox box)
var b = boundsGetter(s);
b.center = center;
b.size = size;
box.center = d.offset.vector3Value;
box.size = d.boxSize.vector3Value;
b.DrawHandle();
box.DrawHandle();
center = b.center;
size = b.size;
d.offset.vector3Value = box.center;
var size = box.size;
Vector3 blendPositive = d.boxBlendDistancePositive.vector3Value;
Vector3 blendNegative = d.boxBlendDistanceNegative.vector3Value;
Vector3 blendNormalPositive = d.boxBlendNormalDistancePositive.vector3Value;
Vector3 blendNormalNegative = d.boxBlendNormalDistanceNegative.vector3Value;
for (int i = 0; i < 3; ++i)
{
size[i] = Mathf.Max(0f, size[i]);
}
d.boxSize.vector3Value = size;
Vector3 halfSize = size * .5f;
for (int i = 0; i < 3; ++i)
{
blendPositive[i] = Mathf.Clamp(blendPositive[i], 0f, halfSize[i]);
blendNegative[i] = Mathf.Clamp(blendNegative[i], 0f, halfSize[i]);
blendNormalPositive[i] = Mathf.Clamp(blendNormalPositive[i], 0f, halfSize[i]);
blendNormalNegative[i] = Mathf.Clamp(blendNormalNegative[i], 0f, halfSize[i]);
}
d.boxBlendDistancePositive.vector3Value = blendPositive;
d.boxBlendDistanceNegative.vector3Value = blendNegative;
d.boxBlendNormalDistancePositive.vector3Value = blendNormalPositive;
d.boxBlendNormalDistanceNegative.vector3Value = blendNormalNegative;
EditorUtility.SetDirty(sourceAsset);
if (d.editorAdvancedModeEnabled.boolValue)
{
d.editorAdvancedModeBlendDistancePositive.vector3Value = d.boxBlendDistancePositive.vector3Value;
d.editorAdvancedModeBlendDistanceNegative.vector3Value = d.boxBlendDistanceNegative.vector3Value;
d.editorAdvancedModeBlendNormalDistancePositive.vector3Value = d.boxBlendNormalDistancePositive.vector3Value;
d.editorAdvancedModeBlendNormalDistanceNegative.vector3Value = d.boxBlendNormalDistanceNegative.vector3Value;
}
else
{
d.editorSimplifiedModeBlendDistance.floatValue = Mathf.Min(
d.boxBlendDistancePositive.vector3Value.x,
d.boxBlendDistancePositive.vector3Value.y,
d.boxBlendDistancePositive.vector3Value.z,
d.boxBlendDistanceNegative.vector3Value.x,
d.boxBlendDistanceNegative.vector3Value.y,
d.boxBlendDistanceNegative.vector3Value.z);
d.boxBlendDistancePositive.vector3Value = d.boxBlendDistanceNegative.vector3Value = Vector3.one * d.editorSimplifiedModeBlendDistance.floatValue;
d.editorSimplifiedModeBlendNormalDistance.floatValue = Mathf.Min(
d.boxBlendNormalDistancePositive.vector3Value.x,
d.boxBlendNormalDistancePositive.vector3Value.y,
d.boxBlendNormalDistancePositive.vector3Value.z,
d.boxBlendNormalDistanceNegative.vector3Value.x,
d.boxBlendNormalDistanceNegative.vector3Value.y,
d.boxBlendNormalDistanceNegative.vector3Value.z);
d.boxBlendNormalDistancePositive.vector3Value = d.boxBlendNormalDistanceNegative.vector3Value = Vector3.one * d.editorSimplifiedModeBlendNormalDistance.floatValue;
}
d.Apply();
static void DrawBoxFadeHandle(
InfluenceVolumeUI s, InfluenceVolume d, Editor o, Object sourceAsset,
Func<InfluenceVolumeUI, Gizmo6FacesBox> boundsGetter,
Vector3 baseOffset, Vector3 baseSize,
ref Vector3 positive, ref Vector3 negative)
static void DrawBoxFadeHandle(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o, Object sourceAsset, Gizmo6FacesBox box, SerializedProperty positive, SerializedProperty negative)
var b = boundsGetter(s);
b.center = baseOffset - (positive - negative) * 0.5f;
b.size = baseSize - positive - negative;
b.allHandleControledByOne = !s.data.editorAdvancedModeEnabled.boolValue;
box.center = d.offset.vector3Value - (positive.vector3Value - negative.vector3Value) * 0.5f;
box.size = d.boxSize.vector3Value - positive.vector3Value - negative.vector3Value;
box.allHandleControledByOne = !d.editorAdvancedModeEnabled.boolValue;
b.DrawHandle();
box.DrawHandle();
var center = baseOffset;
var influenceSize = baseSize;
var influenceCenter = d.offset.vector3Value;
var halfInfluenceSize = d.boxSize.vector3Value * .5f;
var diff = 2 * (b.center - center);
var sum = influenceSize - b.size;
var positiveNew = (sum - diff) * 0.5f;
var negativeNew = (sum + diff) * 0.5f;
var blendDistancePositive = Vector3.Max(Vector3.zero, Vector3.Min(positiveNew, influenceSize));
var blendDistanceNegative = Vector3.Max(Vector3.zero, Vector3.Min(negativeNew, influenceSize));
var centerDiff = box.center - influenceCenter;
var halfSizeDiff = halfInfluenceSize - box.size * .5f;
var positiveNew = halfSizeDiff - centerDiff;
var negativeNew = halfSizeDiff + centerDiff;
var blendDistancePositive = Vector3.Max(Vector3.zero, Vector3.Min(positiveNew, halfInfluenceSize));
var blendDistanceNegative = Vector3.Max(Vector3.zero, Vector3.Min(negativeNew, halfInfluenceSize));
positive = blendDistancePositive;
negative = blendDistanceNegative;
positive.vector3Value = blendDistancePositive;
negative.vector3Value = blendDistanceNegative;
EditorUtility.SetDirty(sourceAsset);
d.Apply();
static void DrawSphereHandle(
InfluenceVolumeUI s, InfluenceVolume d, Editor o, Object sourceAsset,
Func<InfluenceVolumeUI, SphereBoundsHandle> boundsGetter,
ref Vector3 center, ref float radius)
static void DrawSphereHandle(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o, Object sourceAsset, SphereBoundsHandle sphere)
var b = boundsGetter(s);
b.center = center;
b.radius = radius;
sphere.center = d.offset.vector3Value;
sphere.radius = d.sphereRadius.floatValue;
b.DrawHandle();
sphere.DrawHandle();
radius = b.radius;
EditorUtility.SetDirty(sourceAsset);
float radius = sphere.radius;
d.sphereRadius.floatValue = radius;
d.sphereBlendDistance.floatValue = Mathf.Clamp(s.data.sphereBlendDistance.floatValue, 0, radius);
d.sphereBlendNormalDistance.floatValue = Mathf.Clamp(s.data.sphereBlendNormalDistance.floatValue, 0, radius);
d.Apply();
static void DrawSphereFadeHandle(
InfluenceVolumeUI s, InfluenceVolume d, Editor o, Object sourceAsset,
Func<InfluenceVolumeUI, SphereBoundsHandle> boundsGetter,
Vector3 baseOffset, float baseRadius,
ref float radius)
static void DrawSphereFadeHandle(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o, Object sourceAsset, SphereBoundsHandle sphere, SerializedProperty radius)
var b = boundsGetter(s);
b.center = baseOffset;
b.radius = Mathf.Clamp(baseRadius - radius, 0, baseRadius);
sphere.center = d.offset.vector3Value;
sphere.radius = radius.floatValue;
b.DrawHandle();
sphere.DrawHandle();
radius = Mathf.Clamp(baseRadius - b.radius, 0, baseRadius);
EditorUtility.SetDirty(sourceAsset);
radius.floatValue = Mathf.Clamp(d.sphereRadius.floatValue - sphere.radius, 0, d.sphereRadius.floatValue);
d.Apply();
}
}
}

20
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.cs


partial class InfluenceVolumeUI : BaseUI<SerializedInfluenceVolume>
{
const int k_AnimBoolFields = 2;
internal static readonly Color k_GizmoThemeColorBase = new Color(255f / 255f, 229f / 255f, 148f / 255f, 80f / 255f);
internal static readonly Color k_GizmoThemeColorBaseFace = new Color(255f / 255f, 229f / 255f, 148f / 255f, 45f / 255f);
internal static readonly Color k_GizmoThemeColorInfluence = new Color(83f / 255f, 255f / 255f, 95f / 255f, 75f / 255f);
internal static readonly Color k_GizmoThemeColorInfluenceFace = new Color(83f / 255f, 255f / 255f, 95f / 255f, 17f / 255f);
internal static readonly Color k_GizmoThemeColorInfluenceNormal = new Color(0f / 255f, 229f / 255f, 255f / 255f, 80f / 255f);
internal static readonly Color k_GizmoThemeColorInfluenceNormalFace = new Color(0f / 255f, 229f / 255f, 255f / 255f, 36f / 255f);
internal static readonly Color k_GizmoThemeColorProjection = new Color(0x00 / 255f, 0xE5 / 255f, 0xFF / 255f, 0x20 / 255f);
internal static readonly Color k_GizmoThemeColorProjectionFace = new Color(0x00 / 255f, 0xE5 / 255f, 0xFF / 255f, 0x20 / 255f);
internal static readonly Color k_GizmoThemeColorDisabled = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
internal static readonly Color k_GizmoThemeColorDisabledFace = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
static readonly int k_ShapeCount = Enum.GetValues(typeof(InfluenceShape)).Length;
public Gizmo6FacesBox boxBaseHandle;

boxInfluenceNormalHandle.faceColorsSelected = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceNormalBlendFace };
}
public override void Update()
public void SetIsSectionExpanded_Shape(InfluenceShape shape)
base.Update();
SetIsSectionExpanded_Shape((InfluenceShape)data.shape.intValue);
SetIsSectionExpanded_Shape((int)shape);
void SetIsSectionExpanded_Shape(InfluenceShape shape)
public void SetIsSectionExpanded_Shape(int shape)
m_AnimBools[i].target = (int)shape == i;
m_AnimBools[i].target = shape == i;
}
public AnimBool IsSectionExpanded_Shape(InfluenceShape shapeType)

135
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/ProxyVolumeUI.cs


namespace UnityEditor.Experimental.Rendering.HDPipeline
{
using _ = CoreEditorUtils;
//Skin
internal static Color k_GizmoThemeColorProjectionFace = new Color(0x00 / 255f, 0xE5 / 255f, 0xFF / 255f, 0x20 / 255f);
internal static Color k_GizmoThemeColorDisabled = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
internal static Color k_GizmoThemeColorDisabledFace = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
//internal static Color k_GizmoThemeColorProjectionFace = new Color(0x00 / 255f, 0xE5 / 255f, 0xFF / 255f, 0x20 / 255f);
//internal static Color k_GizmoThemeColorDisabled = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
//internal static Color k_GizmoThemeColorDisabledFace = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
internal static GUIContent shapeContent = CoreEditorUtils.GetContent("Shape|The shape of the Proxy.\nInfinite is compatible with any kind of InfluenceShape.");
internal static GUIContent boxSizeContent = CoreEditorUtils.GetContent("Box Size|The size of the box.");
internal static GUIContent sphereRadiusContent = CoreEditorUtils.GetContent("Sphere Radius|The radius of the sphere.");
//logic
public static readonly CED.IDrawer SectionShapeBox = CED.Action(Drawer_SectionShapeBox);
public static readonly CED.IDrawer SectionShapeSphere = CED.Action(Drawer_SectionShapeSphere);

);
}
public BoxBoundsHandle boxProjectionHandle = new BoxBoundsHandle();
public SphereBoundsHandle sphereProjectionHandle = new SphereBoundsHandle();
public ProxyVolumeUI()
: base(k_ShapeCount)
{

return m_AnimBools[(int)shapeType];
}
//gizmo
public static void DrawGizmos(Transform transform, ProxyVolume proxyVolume)
{
switch (proxyVolume.shape)
{
case ProxyShape.Box:
Gizmos_Box(transform, proxyVolume);
break;
case ProxyShape.Sphere:
Gizmos_Sphere(transform, proxyVolume);
break;
}
}
static void Gizmos_Sphere(Transform t, ProxyVolume d)
{
var mat = Gizmos.matrix;
Color col = Gizmos.color;
Gizmos.matrix = Matrix4x4.TRS(t.position, t.rotation, Vector3.one);
Gizmos.color = k_GizmoThemeColorProjection;
Gizmos.DrawWireSphere(Vector3.zero, d.sphereRadius);
Gizmos.color = col;
Gizmos.matrix = mat;
}
static void Gizmos_Box(Transform t, ProxyVolume d)
{
var mat = Gizmos.matrix;
Color col = Gizmos.color;
Gizmos.matrix = Matrix4x4.TRS(t.position, t.rotation, Vector3.one);
Gizmos.color = k_GizmoThemeColorProjection;
Gizmos.DrawWireCube(Vector3.zero, d.boxSize);
Gizmos.color = col;
Gizmos.matrix = mat;
}
//handles
public BoxBoundsHandle boxProjectionHandle = new BoxBoundsHandle();
public SphereBoundsHandle sphereProjectionHandle = new SphereBoundsHandle();
EditorGUILayout.PropertyField(d.shape, _.GetContent("Shape Type"));
EditorGUILayout.PropertyField(d.shape, shapeContent);
EditorGUILayout.PropertyField(d.boxSize, _.GetContent("Box Size"));
EditorGUILayout.PropertyField(d.boxSize, boxSizeContent);
EditorGUILayout.PropertyField(d.sphereRadius, _.GetContent("Sphere Radius"));
EditorGUILayout.PropertyField(d.sphereRadius, sphereRadiusContent);
}
public static void DrawHandles_EditBase(Transform transform, ProxyVolume proxyVolume, ProxyVolumeUI ui, Object sourceAsset)

}
}
public static void DrawHandles_EditNone(Transform transform, ProxyVolume proxyVolume, ProxyVolumeUI ui, Object sourceAsset)
{
}
Matrix4x4 mat = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
var mat = Handles.matrix;
Handles.matrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
Handles.color = k_GizmoThemeColorProjection;
s.sphereProjectionHandle.DrawHandle();
using (new Handles.DrawingScope(k_GizmoThemeColorProjection, mat))
{
s.sphereProjectionHandle.DrawHandle();
}
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(sourceAsset, "Modified Projection Volume");

//the gizmo is not an object of the scene. Flag it as dirty
Handles.matrix = mat;
}
static void Handles_EditBase_Box(Transform transform, ProxyVolume proxyVolume, ProxyVolumeUI s, Object sourceAsset)

var mat = Handles.matrix;
Handles.matrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
Matrix4x4 mat = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
Handles.color = k_GizmoThemeColorProjection;
s.boxProjectionHandle.DrawHandle();
using (new Handles.DrawingScope(k_GizmoThemeColorProjection, mat))
{
s.boxProjectionHandle.DrawHandle();
}
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(sourceAsset, "Modified Projection Volume AABB");

//the gizmo is not an object of the scene. Flag it as dirty
Handles.matrix = mat;
}
public static void DrawGizmos_EditNone(Transform transform, ProxyVolume proxyVolume, ProxyVolumeUI ui, Object sourceAsset)
{
switch (proxyVolume.shape)
{
case ProxyShape.Box:
Gizmos_EditNone_Box(transform, proxyVolume, ui, sourceAsset);
break;
case ProxyShape.Sphere:
Gizmos_EditNone_Sphere(transform, proxyVolume, ui, sourceAsset);
break;
}
}
static void Gizmos_EditNone_Sphere(Transform t, ProxyVolume d, ProxyVolumeUI s, Object o)
{
var mat = Gizmos.matrix;
Gizmos.matrix = Matrix4x4.TRS(t.position, t.rotation, Vector3.one);
Gizmos.color = k_GizmoThemeColorProjection;
Gizmos.DrawWireSphere(Vector3.zero, d.sphereRadius);
Gizmos.matrix = mat;
}
static void Gizmos_EditNone_Box(Transform t, ProxyVolume d, ProxyVolumeUI s, Object o)
{
var mat = Gizmos.matrix;
Gizmos.matrix = Matrix4x4.TRS(t.position, t.rotation, Vector3.one);
Gizmos.color = k_GizmoThemeColorProjection;
Gizmos.DrawWireCube(Vector3.zero, d.boxSize);
Gizmos.matrix = mat;
}
}
}

9
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/ReflectionProxyVolumeComponentUI.cs


ProxyVolumeUI.DrawHandles_EditBase(target.transform, target.proxyVolume, ui.proxyVolume, target);
}
public static void DrawHandles_EditNone(ReflectionProxyVolumeComponentUI ui, ReflectionProxyVolumeComponent target)
public static void DrawGizmos_EditNone(ReflectionProxyVolumeComponent target)
ProxyVolumeUI.DrawHandles_EditNone(target.transform, target.proxyVolume, ui.proxyVolume, target);
}
public static void DrawGizmos_EditNone(ReflectionProxyVolumeComponentUI ui, ReflectionProxyVolumeComponent target)
{
ProxyVolumeUI.DrawGizmos_EditNone(target.transform, target.proxyVolume, ui.proxyVolume, target);
ProxyVolumeUI.DrawGizmos(target.transform, target.proxyVolume);
}
}
}

29
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/SerializedInfluenceVolume.cs


internal SerializedProperty boxSize;
internal SerializedProperty boxBlendDistancePositive;
internal SerializedProperty boxBlendDistanceNegative;
//internal SerializedProperty boxBlendSize;
//internal SerializedProperty boxBlendNormalSize;
internal SerializedProperty boxSideFadePositive;
internal SerializedProperty boxSideFadeNegative;
internal SerializedProperty sphereRadius;

internal SerializedProperty editorAdvancedModeBlendNormalDistanceNegative;
internal SerializedProperty editorSimplifiedModeBlendNormalDistance;
internal SerializedProperty editorAdvancedModeEnabled;
internal SerializedProperty editorAdvancedModeFaceFadePositive;
internal SerializedProperty editorAdvancedModeFaceFadeNegative;
public SerializedInfluenceVolume(SerializedProperty root)
{

boxSize = root.Find((InfluenceVolume i) => i.boxSize);
boxBlendDistancePositive = root.Find((InfluenceVolume i) => i.boxBlendDistancePositive);
boxBlendDistanceNegative = root.Find((InfluenceVolume i) => i.boxBlendDistanceNegative);
//boxBlendSize = root.Find((InfluenceVolume i) => i.boxBlendSize);
//boxBlendNormalSize = root.Find((InfluenceVolume i) => i.boxBlendNormalSize);
boxSideFadePositive = root.Find((InfluenceVolume i) => i.boxSideFadePositive);
boxSideFadeNegative = root.Find((InfluenceVolume i) => i.boxSideFadeNegative);
sphereRadius = root.Find((InfluenceVolume i) => i.sphereRadius);

editorAdvancedModeBlendNormalDistanceNegative = root.FindPropertyRelative("m_EditorAdvancedModeBlendNormalDistanceNegative");
editorSimplifiedModeBlendNormalDistance = root.FindPropertyRelative("m_EditorSimplifiedModeBlendNormalDistance");
editorAdvancedModeEnabled = root.FindPropertyRelative("m_EditorAdvancedModeEnabled");
editorAdvancedModeFaceFadePositive = root.FindPropertyRelative("m_EditorAdvancedModeFaceFadePositive");
editorAdvancedModeFaceFadeNegative = root.FindPropertyRelative("m_EditorAdvancedModeFaceFadeNegative");
if(editorAdvancedModeBlendDistancePositive.vector3Value == Vector3.zero
if (editorAdvancedModeBlendDistancePositive.vector3Value == Vector3.zero
&& editorAdvancedModeBlendDistanceNegative.vector3Value == Vector3.zero
&& editorSimplifiedModeBlendDistance.floatValue == 0f
&& editorAdvancedModeBlendNormalDistancePositive.vector3Value == Vector3.zero

|| boxBlendDistanceNegative.vector3Value != Vector3.zero))
|| boxBlendDistanceNegative.vector3Value != Vector3.zero
|| boxBlendNormalDistancePositive.vector3Value != Vector3.zero
|| boxBlendNormalDistanceNegative.vector3Value != Vector3.zero))
{
Vector3 positive = boxBlendDistancePositive.vector3Value;
Vector3 negative = boxBlendDistanceNegative.vector3Value;

|| negative.x != negative.y
|| negative.x != negative.z
|| positive.x != negative.x;
Apply();
}
if(editorAdvancedModeFaceFadePositive.vector3Value == Vector3.one
&& editorAdvancedModeFaceFadeNegative.vector3Value == Vector3.one
&& (boxSideFadePositive.vector3Value != Vector3.one
|| boxSideFadeNegative.vector3Value != Vector3.one))
{
editorAdvancedModeFaceFadePositive.vector3Value = boxSideFadePositive.vector3Value;
editorAdvancedModeFaceFadeNegative.vector3Value = boxSideFadeNegative.vector3Value;
if(!editorAdvancedModeEnabled.boolValue)
{
boxSideFadePositive.vector3Value = Vector3.one;
boxSideFadeNegative.vector3Value = Vector3.one;
}
Apply();
}
}

6
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Volumetric/DensityVolumeTextureTool.cs


void OnGUI()
{
EditorGUILayout.LabelField(textureLabel, null);
EditorGUILayout.LabelField(textureLabel);
tileSize = EditorGUILayout.IntField(tileSizeLabel, tileSize, null);
tileSize = EditorGUILayout.IntField(tileSizeLabel, tileSize);
bool validData = (sourceTexture != null && IsTileSizeValid());
bool create = false;

using (new EditorGUI.DisabledScope(!validData))
{
create = GUILayout.Button(createLabel, null);
create = GUILayout.Button(createLabel);
}
if (create)

14
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/BaseLitUI.cs


windShiverDirectionality = FindProperty(kWindShiverDirectionality, props, false);
// Decal
supportDecals = FindProperty(kSupportDecals, props);
supportDecals = FindProperty(kSupportDecals, props, false);
// specular AA
enableGeometricSpecularAA = FindProperty(kEnableGeometricSpecularAA, props, false);

EditorGUI.showMixedValue = false;
}
protected abstract void UpdateDisplacement();
protected virtual void UpdateDisplacement() {}
protected override void BaseMaterialPropertiesGUI()
{

}
}
m_MaterialEditor.ShaderProperty(supportDecals, StylesBaseLit.supportDecalsText);
if (supportDecals != null)
{
m_MaterialEditor.ShaderProperty(supportDecals, StylesBaseLit.supportDecalsText);
}
if (enableGeometricSpecularAA != null)
{

{
SetupBaseUnlitKeywords(material);
if (material.HasProperty(kDoubleSidedEnable) && material.GetFloat(kDoubleSidedEnable) > 0.0f)
bool doubleSidedEnable = material.HasProperty(kDoubleSidedEnable) ? material.GetFloat(kDoubleSidedEnable) > 0.0f : false;
if (doubleSidedEnable)
{
DoubleSidedNormalMode doubleSidedNormalMode = (DoubleSidedNormalMode)material.GetFloat(kDoubleSidedNormalMode);
switch (doubleSidedNormalMode)

SetupMainTexForAlphaTestGI("_BaseColorMap", "_BaseColor", material);
// Use negation so we don't create keyword by default
CoreUtils.SetKeyword(material, "_DISABLE_DECALS", material.GetFloat(kSupportDecals) == 0.0);
CoreUtils.SetKeyword(material, "_DISABLE_DECALS", material.HasProperty(kSupportDecals) && material.GetFloat(kSupportDecals) == 0.0);
CoreUtils.SetKeyword(material, "_ENABLE_GEOMETRIC_SPECULAR_AA", material.HasProperty(kEnableGeometricSpecularAA) && material.GetFloat(kEnableGeometricSpecularAA) == 1.0);
}

4
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Unlit/BaseUnlitUI.cs


protected abstract void FindMaterialProperties(MaterialProperty[] props);
protected abstract void SetupMaterialKeywordsAndPassInternal(Material material);
protected abstract void MaterialPropertiesGUI(Material material);
protected abstract void MaterialPropertiesAdvanceGUI(Material material);
protected virtual void MaterialPropertiesAdvanceGUI(Material material) {}
protected abstract bool ShouldEmissionBeEnabled(Material material);
protected virtual bool ShouldEmissionBeEnabled(Material material) { return false; }
protected virtual void FindBaseMaterialProperties(MaterialProperty[] props)
{

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


newAsset.name = Path.GetFileName(pathName);
newAsset.Init();
AssetDatabase.CreateAsset(newAsset, pathName);
ProjectWindowUtil.ShowCreatedAsset(newAsset);
}

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


{ "HDRenderPipeline/Lit", LitGUI.SetupMaterialKeywordsAndPass },
{ "HDRenderPipeline/LitTessellation", LitGUI.SetupMaterialKeywordsAndPass },
{ "HDRenderPipeline/Unlit", UnlitGUI.SetupMaterialKeywordsAndPass },
{ "HDRenderPipeline/Fabric", FabricGUI.SetupMaterialKeywordsAndPass },
{ "HDRenderPipeline/Decal", DecalUI.SetupMaterialKeywordsAndPass }
};

3
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/SharedCode.template.hlsl


$FragInputs.color: output.color = input.color;
#if SHADER_STAGE_FRAGMENT
$FragInputs.isFrontFace: output.isFrontFace = IS_FRONT_VFACE(input.cullFace, true, false); // TODO: SHADER_STAGE_FRAGMENT only
$FragInputs.isFrontFace: // Handle handness of the view matrix (In Unity view matrix default to a determinant of -1)
$FragInputs.isFrontFace: // when we render a cubemap the view matrix handness is flipped (due to convention used for cubemap) we have a determinant of +1
$FragInputs.isFrontFace: output.isFrontFace = _DetViewMatrix < 0.0 ? output.isFrontFace : !output.isFrontFace;
#endif // SHADER_STAGE_FRAGMENT
return output;

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


mat.shader.name == "HDRenderPipeline/LayeredLitTessellation" ||
mat.shader.name == "HDRenderPipeline/StackLit" ||
mat.shader.name == "HDRenderPipeline/Unlit" ||
mat.shader.name == "HDRenderPipeline/Fabric" ||
mat.shader.name == "HDRenderPipeline/Decal"
)
{

154
com.unity.render-pipelines.high-definition/HDRP/Lighting/Light/HDAdditionalLightData.cs


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

// To be able to have correct default values for our lights and to also control the conversion of intensity from the light editor (so it is compatible with GI)
// we add intensity (for each type of light we want to manage).
[System.Obsolete("directionalIntensity is deprecated, use intensity and lightUnit instead")]
public float directionalIntensity = Mathf.PI; // In Lux
public float directionalIntensity = k_DefaultDirectionalLightIntensity;
public float punctualIntensity = 600.0f; // Light default to 600 lumen, i.e ~48 candela
public float punctualIntensity = k_DefaultPunctualLightIntensity;
public float areaIntensity = 200.0f; // Light default to 200 lumen to better match point light
public float areaIntensity = k_DefaultAreaLightIntensity;
public const float k_DefaultPunctualLightIntensity = 600.0f; // In lumens
public const float k_DefaultAreaLightIntensity = 200.0f; // In lumens
public const float k_DefaultPunctualLightIntensity = 600.0f; // Light default to 600 lumen, i.e ~48 candela
public const float k_DefaultAreaLightIntensity = 200.0f; // Light default to 200 lumen to better match point light
public float intensity
{

public bool enableSpotReflector = false;
[Range(0.0f, 100.0f)]
public float m_InnerSpotPercent = 0.0f; // To display this field in the UI this need to be public
public float m_InnerSpotPercent; // To display this field in the UI this need to be public
public float GetInnerSpotPercent01()
{

public float volumetricDimmer = 1.0f;
// Used internally to convert any light unit input into light intensity
public LightUnit lightUnit;
public LightUnit lightUnit = LightUnit.Lumen;
// Not used for directional lights.
public float fadeDistance = 10000.0f;

public float aspectRatio = 1.0f;
// Only for Sphere/Disc
public float shapeRadius = 0.0f;
public float shapeRadius;
// Only for Spot/Point - use to cheaply fake specular spherical area light
[Range(0.0f, 1.0f)]

// This function return a mask of light layers as uint and handle the case of Everything as being 0xFF and not -1
public uint GetLightLayers()
{
int value = Convert.ToInt32(lightLayers);
int value = (int)(lightLayers);
return value < 0 ? (uint)LightLayerEnum.Everything : (uint)value;
}

TimelineWorkaround timelineWorkaround;
TimelineWorkaround timelineWorkaround = new TimelineWorkaround();
#endif
// For light that used the old intensity system we update them

// Runtime datas used to compute light intensity
Light _light;
Light m_Light
Light _light;
Light m_Light
{
get
{

else
m_Light.intensity = intensity;
#if UNITY_EDITOR
#if UNITY_EDITOR
#endif
#endif
}
void SetLightIntensityPunctual(float intensity)

}
}
private void DrawGizmos(bool selected)
{
var light = gameObject.GetComponent<Light>();
var gizmoColor = light.color;
gizmoColor.a = selected ? 1.0f : 0.3f; // Fade for the gizmo
Gizmos.color = Handles.color = gizmoColor;
if (lightTypeExtent == LightTypeExtent.Punctual)
{
switch (light.type)
{
case LightType.Directional:
HDLightEditorUtilities.DrawDirectionalLightGizmo(light);
break;
case LightType.Point:
HDLightEditorUtilities.DrawPointlightGizmo(light, selected);
break;
case LightType.Spot:
if (spotLightShape == SpotLightShape.Cone)
HDLightEditorUtilities.DrawSpotlightGizmo(light, selected);
else if (spotLightShape == SpotLightShape.Pyramid)
HDLightEditorUtilities.DrawFrustumlightGizmo(light);
else if (spotLightShape == SpotLightShape.Box)
HDLightEditorUtilities.DrawFrustumlightGizmo(light);
break;
}
}
else
{
switch (lightTypeExtent)
{
case LightTypeExtent.Rectangle:
HDLightEditorUtilities.DrawArealightGizmo(light);
break;
case LightTypeExtent.Line:
HDLightEditorUtilities.DrawArealightGizmo(light);
break;
}
}
if (selected)
{
DrawVerticalRay();
}
}
// Trace a ray down to better locate the light location
private void DrawVerticalRay()
{
Ray ray = new Ray(transform.position, Vector3.down);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Handles.color = Color.green;
Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual;
Handles.DrawLine(transform.position, hit.point);
Handles.DrawWireDisc(hit.point, hit.normal, 0.5f);
Handles.color = Color.red;
Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater;
Handles.DrawLine(transform.position, hit.point);
Handles.DrawWireDisc(hit.point, hit.normal, 0.5f);
}
}
private void OnDrawGizmos()
{
// DrawGizmos(false);
}
private void OnDrawGizmosSelected()
{
DrawGizmos(true);
}
// TODO: There are a lot of old != current checks and assignation in this function, maybe think about using another system ?
void LateUpdate()
{

}
if (m_Light.color != timelineWorkaround.oldLightColor
|| transform.localScale !=timelineWorkaround.oldLocalScale
|| transform.localScale != timelineWorkaround.oldLocalScale
|| lightTypeExtent !=timelineWorkaround.oldLightTypeExtent
|| lightTypeExtent != timelineWorkaround.oldLightTypeExtent
|| m_Light.colorTemperature != timelineWorkaround.oldLightColorTemperature)
{
UpdateAreaLightEmissiveMesh();

public void UpdateAreaLightEmissiveMesh()
{
MeshRenderer emissiveMeshRenderer = GetComponent<MeshRenderer>();
MeshFilter emissiveMeshFilter = GetComponent<MeshFilter>();
MeshRenderer emissiveMeshRenderer = GetComponent<MeshRenderer>();
MeshFilter emissiveMeshFilter = GetComponent<MeshFilter>();
bool displayEmissiveMesh = IsAreaLight(lightTypeExtent) && lightTypeExtent != LightTypeExtent.Line && displayAreaLightEmissiveMesh;

DestroyImmediate(emissiveMeshFilter);
// We don't have anything to do left if the dislay emissive mesh option is disabled
return ;
return;
}
Vector3 lightSize;

#endif
public void CopyTo(HDAdditionalLightData data)
{
#pragma warning disable 0618
data.directionalIntensity = directionalIntensity;
data.punctualIntensity = punctualIntensity;
data.areaIntensity = areaIntensity;
#pragma warning restore 0618
data.enableSpotReflector = enableSpotReflector;
data.m_InnerSpotPercent = m_InnerSpotPercent;
data.lightDimmer = lightDimmer;
data.volumetricDimmer = volumetricDimmer;
data.lightUnit = lightUnit;
data.fadeDistance = fadeDistance;
data.affectDiffuse = affectDiffuse;
data.affectSpecular = affectSpecular;
data.nonLightmappedOnly = nonLightmappedOnly;
data.lightTypeExtent = lightTypeExtent;
data.spotLightShape = spotLightShape;
data.shapeWidth = shapeWidth;
data.shapeHeight = shapeHeight;
data.aspectRatio = aspectRatio;
data.shapeRadius = shapeRadius;
data.maxSmoothness = maxSmoothness;
data.applyRangeAttenuation = applyRangeAttenuation;
data.useOldInspector = useOldInspector;
data.featuresFoldout = featuresFoldout;
data.showAdditionalSettings = showAdditionalSettings;
data.displayLightIntensity = displayLightIntensity;
data.displayAreaLightEmissiveMesh = displayAreaLightEmissiveMesh;
data.needsIntensityUpdate_1_0 = needsIntensityUpdate_1_0;
#if UNITY_EDITOR
data.timelineWorkaround = timelineWorkaround;
#endif
}
// As we have our own default value, we need to initialize the light intensity correctly
public static void InitDefaultHDAdditionalLightData(HDAdditionalLightData lightData)
{

light.lightShadowCasterMode = LightShadowCasterMode.Everything;
}
public void OnBeforeSerialize() {}
public void OnBeforeSerialize() { }
public void OnAfterDeserialize()
{

m_Version = currentVersion;
version = currentVersion;
#pragma warning restore 0618
}
}

3
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightEvaluation.hlsl


// Our subsurface scattering models use the semi-infinite planar slab assumption.
// Therefore, we need to find the thickness along the normal.
float thicknessInUnits = (distFrontFaceToLight - distBackFaceToLight) * -NdotL;
// Warning: based on the artist's input, dependence on the NdotL has been disabled.
float thicknessInUnits = (distFrontFaceToLight - distBackFaceToLight) /* * -NdotL */;
float thicknessInMeters = thicknessInUnits * _WorldScales[bsdfData.diffusionProfile].x;
float thicknessInMillimeters = thicknessInMeters * MILLIMETERS_PER_METER;

332
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoop.cs


namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public static class VisibleLightExtensionMethods
{
public static Vector3 GetPosition(this VisibleLight value)
{
return value.localToWorld.GetColumn(3);
}
public static Vector3 GetForward(this VisibleLight value)
{
return value.localToWorld.GetColumn(2);
}
public static Vector3 GetUp(this VisibleLight value)
{
return value.localToWorld.GetColumn(1);
}
public static Vector3 GetRight(this VisibleLight value)
{
return value.localToWorld.GetColumn(0);
}
}
class ShadowSetup : IDisposable
{

// For now we don't use shadow cascade borders.
static public readonly bool s_UseCascadeBorders = false;
// Keep sorting array around to avoid garbage
uint[] m_SortKeys = null;
void UpdateSortKeysArray(int count)
{
if (m_SortKeys == null ||count > m_SortKeys.Length)
{
m_SortKeys = new uint[count];
}
}
// Matrix used for Light list building
// Keep them around to avoid allocations
Matrix4x4[] m_LightListProjMatrices = new Matrix4x4[2];
Matrix4x4[] m_LightListProjscrMatrices = new Matrix4x4[2];
Matrix4x4[] m_LightListInvProjscrMatrices = new Matrix4x4[2];
Matrix4x4[] m_LightListProjHMatrices = new Matrix4x4[2];
Matrix4x4[] m_LightListInvProjHMatrices = new Matrix4x4[2];
public class LightList
{

ContactShadows m_ContactShadows = null;
bool m_EnableContactShadow = false;
IndirectLightingController m_indirectLightingController = null;
// Following is an array of material of size eight for all combination of keyword: OUTPUT_SPLIT_LIGHTING - LIGHTLOOP_TILE_PASS - SHADOWS_SHADOWMASK - USE_FPTL_LIGHTLIST/USE_CLUSTERED_LIGHTLIST - DEBUG_DISPLAY

Material m_DebugLightVolumeMaterial;
Material m_CubeToPanoMaterial;
Light m_CurrentSunLight;

m_DebugViewTilesMaterial = CoreUtils.CreateEngineMaterial(m_Resources.debugViewTilesShader);
m_DebugShadowMapMaterial = CoreUtils.CreateEngineMaterial(m_Resources.debugShadowMapShader);
m_DebugLightVolumeMaterial = CoreUtils.CreateEngineMaterial(m_Resources.debugLightVolumeShader);
m_CubeToPanoMaterial = CoreUtils.CreateEngineMaterial(m_Resources.cubeToPanoShader);
m_lightList = new LightList();

{
s_GenListPerTileKernel = buildPerTileLightListShader.FindKernel(m_FrameSettings.lightLoopSettings.enableBigTilePrepass ? "TileLightListGen_SrcBigTile_FeatureFlags" : "TileLightListGen_FeatureFlags");
s_GenListPerTileKernel_Oblique = buildPerTileLightListShader.FindKernel(m_FrameSettings.lightLoopSettings.enableBigTilePrepass ? "TileLightListGen_SrcBigTile_FeatureFlags_Oblique" : "TileLightListGen_FeatureFlags_Oblique");
}
else
{

return new Vector3(light.finalColor.r, light.finalColor.g, light.finalColor.b);
}
bool GetDominantLightWithShadows(AdditionalShadowData additionalShadowData, VisibleLight light, int lightIndex = -1)
bool GetDominantLightWithShadows(AdditionalShadowData additionalShadowData, VisibleLight light, Light lightComponent, int lightIndex = -1)
// Can happen for particle lights (where we don't support shadows anyway)
if (lightComponent == null)
return false;
float lightDominanceValue = light.screenRect.size.magnitude * light.light.intensity;
float lightDominanceValue = light.screenRect.size.magnitude * lightComponent.intensity;
if (additionalShadowData == null || !additionalShadowData.contactShadows || light.light.shadows == LightShadows.None)
if (additionalShadowData == null || !additionalShadowData.contactShadows || lightComponent.shadows == LightShadows.None)
return false;
if (lightDominanceValue <= m_DominantLightValue || m_DominantLightValue == Single.PositiveInfinity)
return false;

return true;
}
public bool GetDirectionalLightData(CommandBuffer cmd, ShadowSettings shadowSettings, GPULightType gpuLightType, VisibleLight light, HDAdditionalLightData additionalData, AdditionalShadowData additionalShadowData, int lightIndex, DebugDisplaySettings debugDisplaySettings)
public bool GetDirectionalLightData(CommandBuffer cmd, ShadowSettings shadowSettings, GPULightType gpuLightType, VisibleLight light, Light lightComponent, HDAdditionalLightData additionalData, AdditionalShadowData additionalShadowData, int lightIndex, DebugDisplaySettings debugDisplaySettings)
{
var directionalLightData = new DirectionalLightData();

return false;
// Discard light if disabled in debug display settings
if (!debugDisplaySettings.lightingDebugSettings.showDirectionalLight)
return false;

// Light direction for directional is opposite to the forward direction
directionalLightData.forward = light.light.transform.forward;
directionalLightData.forward = light.GetForward();
directionalLightData.right = light.light.transform.right * 2 / Mathf.Max(additionalData.shapeWidth, 0.001f);
directionalLightData.up = light.light.transform.up * 2 / Mathf.Max(additionalData.shapeHeight, 0.001f);
directionalLightData.positionRWS = light.light.transform.position;
directionalLightData.right = light.GetRight() * 2 / Mathf.Max(additionalData.shapeWidth, 0.001f);
directionalLightData.up = light.GetUp() * 2 / Mathf.Max(additionalData.shapeHeight, 0.001f);
directionalLightData.positionRWS = light.GetPosition();
directionalLightData.color = GetLightColor(light);
// 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.

directionalLightData.volumetricDimmer = additionalData.volumetricDimmer;
directionalLightData.shadowIndex = directionalLightData.cookieIndex = -1;
if (light.light.cookie != null)
if (lightComponent != null && lightComponent.cookie != null)
directionalLightData.tileCookie = light.light.cookie.wrapMode == TextureWrapMode.Repeat ? 1 : 0;
directionalLightData.cookieIndex = m_CookieTexArray.FetchSlice(cmd, light.light.cookie);
directionalLightData.tileCookie = lightComponent.cookie.wrapMode == TextureWrapMode.Repeat ? 1 : 0;
directionalLightData.cookieIndex = m_CookieTexArray.FetchSlice(cmd, lightComponent.cookie);
}
// fix up shadow information
int shadowIdx;

m_CurrentSunLight = light.light;
m_CurrentSunLight = lightComponent;
if (IsBakedShadowMaskLight(light.light))
if (IsBakedShadowMaskLight(lightComponent))
directionalLightData.shadowMaskSelector[light.light.bakingOutput.occlusionMaskChannel] = 1.0f;
directionalLightData.nonLightmappedOnly = light.light.lightShadowCasterMode == LightShadowCasterMode.NonLightmappedOnly ? 1 : 0;
directionalLightData.shadowMaskSelector[lightComponent.bakingOutput.occlusionMaskChannel] = 1.0f;
directionalLightData.nonLightmappedOnly = lightComponent.lightShadowCasterMode == LightShadowCasterMode.NonLightmappedOnly ? 1 : 0;
}
else
{

}
// Fallback to the first non shadow casting directional light.
m_CurrentSunLight = m_CurrentSunLight == null ? light.light : m_CurrentSunLight;
m_CurrentSunLight = m_CurrentSunLight == null ? lightComponent : m_CurrentSunLight;
if (GetDominantLightWithShadows(additionalShadowData, light))
if (GetDominantLightWithShadows(additionalShadowData, light, lightComponent))
directionalLightData.contactShadowIndex = 0;
m_lightList.directionalLights.Add(directionalLightData);

}
public bool GetLightData(CommandBuffer cmd, ShadowSettings shadowSettings, Camera camera, GPULightType gpuLightType,
VisibleLight light, HDAdditionalLightData additionalLightData, AdditionalShadowData additionalshadowData,
VisibleLight light, Light lightComponent, HDAdditionalLightData additionalLightData, AdditionalShadowData additionalshadowData,
int lightIndex, ref Vector3 lightDimensions, DebugDisplaySettings debugDisplaySettings)
{
var lightData = new LightData();

lightData.lightType = gpuLightType;
lightData.positionRWS = light.light.transform.position;
lightData.positionRWS = light.GetPosition();
bool applyRangeAttenuation = additionalLightData.applyRangeAttenuation && (gpuLightType != GPULightType.ProjectorBox);

lightData.color = GetLightColor(light);
lightData.forward = light.light.transform.forward;
lightData.up = light.light.transform.up;
lightData.right = light.light.transform.right;
lightData.forward = light.GetForward();
lightData.up = light.GetUp();
lightData.right = light.GetRight();
lightDimensions.x = additionalLightData.shapeWidth;
lightDimensions.y = additionalLightData.shapeHeight;

lightData.cookieIndex = -1;
lightData.shadowIndex = -1;
if (light.light.cookie != null)
if (lightComponent != null && lightComponent.cookie != null)
lightData.cookieIndex = m_CookieTexArray.FetchSlice(cmd, light.light.cookie);
lightData.cookieIndex = m_CookieTexArray.FetchSlice(cmd, lightComponent.cookie);
lightData.cookieIndex = m_CubeCookieTexArray.FetchSlice(cmd, light.light.cookie);
lightData.cookieIndex = m_CubeCookieTexArray.FetchSlice(cmd, lightComponent.cookie);
break;
}
}

lightData.shadowMaskSelector = Vector4.zero;
if (IsBakedShadowMaskLight(light.light))
if (IsBakedShadowMaskLight(lightComponent))
lightData.shadowMaskSelector[light.light.bakingOutput.occlusionMaskChannel] = 1.0f;
lightData.shadowMaskSelector[lightComponent.bakingOutput.occlusionMaskChannel] = 1.0f;
lightData.nonLightmappedOnly = light.light.lightShadowCasterMode == LightShadowCasterMode.NonLightmappedOnly ? 1 : 0;
lightData.nonLightmappedOnly = lightComponent.lightShadowCasterMode == LightShadowCasterMode.NonLightmappedOnly ? 1 : 0;
}
else
{

// Check if the current light is dominant and store it's index to change it's property later,
// as we can't know which one will be dominant before checking all the lights
GetDominantLightWithShadows(additionalshadowData, light, m_lightList.lights.Count -1);
GetDominantLightWithShadows(additionalshadowData, light, lightComponent, m_lightList.lights.Count -1);
return true;
}

const float pi = 3.1415926535897932384626433832795f;
const float degToRad = (float)(pi / 180.0);
var sa = light.light.spotAngle;
var sa = light.spotAngle;
var cs = Mathf.Cos(0.5f * sa * degToRad);
var si = Mathf.Sin(0.5f * sa * degToRad);

// Unfortunately we don't have this information at the moment.
if (probe.mode == ReflectionProbeMode.Realtime && camera.cameraType == CameraType.Reflection)
return false;
// Discard probe if disabled in debug menu
if (!debugDisplaySettings.lightingDebugSettings.showReflectionProbe)
return false;

public bool IsBakedShadowMaskLight(Light light)
{
// This can happen for particle lights.
if (light == null)
return false;
return light.bakingOutput.lightmapBakeType == LightmapBakeType.Mixed &&
light.bakingOutput.mixedLightingMode == MixedLightingMode.Shadowmask &&
light.bakingOutput.occlusionMaskChannel != -1; // We need to have an occlusion mask channel assign, else we have no shadow mask

for (int i = 0; i < lcnt; ++i)
{
VisibleLight vl = cullResults.visibleLights[i];
if (vl.light.shadows == LightShadows.None)
var lightComponent = vl.light;
// This can happen for particle light which don't have a proper game object. We don't support shadows for them.
if (lightComponent == null)
continue;
if (lightComponent.shadows == LightShadows.None)
AdditionalShadowData asd = vl.light.GetComponent<AdditionalShadowData>();
AdditionalShadowData asd = lightComponent.GetComponent<AdditionalShadowData>();
if (asd != null && asd.shadowDimmer > 0.0f)
{
m_ShadowRequests.Add(i);

int areaLightCount = 0;
int lightCount = Math.Min(cullResults.visibleLights.Count, k_MaxLightsOnScreen);
var sortKeys = new uint[lightCount];
UpdateSortKeysArray(lightCount);
var lightComponent = light.light;
var additionalData = GetHDAdditionalLightData(light);
var additionalData = GetHDAdditionalLightData(lightComponent);
LightCategory lightCategory = LightCategory.Count;
GPULightType gpuLightType = GPULightType.Point;

uint shadow = m_ShadowIndices.ContainsKey(lightIndex) ? 1u : 0;
// 5 bit (0x1F) light category, 5 bit (0x1F) GPULightType, 5 bit (0x1F) lightVolume, 1 bit for shadow casting, 16 bit index
sortKeys[sortCount++] = (uint)lightCategory << 27 | (uint)gpuLightType << 22 | (uint)lightVolumeType << 17 | shadow << 16 | (uint)lightIndex;
m_SortKeys[sortCount++] = (uint)lightCategory << 27 | (uint)gpuLightType << 22 | (uint)lightVolumeType << 17 | shadow << 16 | (uint)lightIndex;
CoreUtils.QuickSort(sortKeys, 0, sortCount - 1); // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory (note the SortCount-1 that is different from original call).
CoreUtils.QuickSort(m_SortKeys, 0, sortCount - 1); // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory (note the SortCount-1 that is different from original call).
// TODO: Refactor shadow management
// The good way of managing shadow:

for (int sortIndex = 0; sortIndex < sortCount; ++sortIndex)
{
// In 1. we have already classify and sorted the light, we need to use this sorted order here
uint sortKey = sortKeys[sortIndex];
uint sortKey = m_SortKeys[sortIndex];
LightCategory lightCategory = (LightCategory)((sortKey >> 27) & 0x1F);
GPULightType gpuLightType = (GPULightType)((sortKey >> 22) & 0x1F);
LightVolumeType lightVolumeType = (LightVolumeType)((sortKey >> 17) & 0x1F);

var lightComponent = light.light;
m_enableBakeShadowMask = m_enableBakeShadowMask || IsBakedShadowMaskLight(light.light);
m_enableBakeShadowMask = m_enableBakeShadowMask || IsBakedShadowMaskLight(lightComponent);
var additionalLightData = GetHDAdditionalLightData(light);
var additionalShadowData = light.light.GetComponent<AdditionalShadowData>(); // Can be null
var additionalLightData = GetHDAdditionalLightData(lightComponent);
var additionalShadowData = lightComponent != null ? lightComponent.GetComponent<AdditionalShadowData>() : null; // Can be null
if (GetDirectionalLightData(cmd, shadowSettings, gpuLightType, light, additionalLightData, additionalShadowData, lightIndex, debugDisplaySettings))
if (GetDirectionalLightData(cmd, shadowSettings, gpuLightType, light, lightComponent, additionalLightData, additionalShadowData, lightIndex, debugDisplaySettings))
{
directionalLightcount++;

Vector3 lightDimensions = new Vector3(); // X = length or width, Y = height, Z = range (depth)
// Punctual, area, projector lights - the rendering side.
if (GetLightData(cmd, shadowSettings, camera, gpuLightType, light, additionalLightData, additionalShadowData, lightIndex, ref lightDimensions, debugDisplaySettings))
if (GetLightData(cmd, shadowSettings, camera, gpuLightType, light, lightComponent, additionalLightData, additionalShadowData, lightIndex, ref lightDimensions, debugDisplaySettings))
{
switch (lightCategory)
{

m_areaLightCount = areaLightCount;
// Redo everything but this time with envLights
Debug.Assert(k_MaxEnvLightsOnScreen <= 256); //for key construction
sortKeys = new uint[probeCount];
UpdateSortKeysArray(probeCount);
sortCount = 0;
for (int probeIndex = 0, numProbes = totalProbes; (probeIndex < numProbes) && (sortCount < probeCount); probeIndex++)

var logVolume = CalculateProbeLogVolume(probe.bounds);
sortKeys[sortCount++] = PackProbeKey(logVolume, lightVolumeType, 0u, probeIndex); // Sort by volume
m_SortKeys[sortCount++] = PackProbeKey(logVolume, lightVolumeType, 0u, probeIndex); // Sort by volume
}
else
{

var logVolume = CalculateProbeLogVolume(probe.bounds);
sortKeys[sortCount++] = PackProbeKey(logVolume, lightVolumeType, 1u, planarProbeIndex); // Sort by volume
m_SortKeys[sortCount++] = PackProbeKey(logVolume, lightVolumeType, 1u, planarProbeIndex); // Sort by volume
CoreUtils.QuickSort(sortKeys, 0, sortCount - 1); // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory (note the SortCount-1 that is different from original call).
CoreUtils.QuickSort(m_SortKeys, 0, sortCount - 1); // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory (note the SortCount-1 that is different from original call).
uint sortKey = sortKeys[sortIndex];
uint sortKey = m_SortKeys[sortIndex];
LightVolumeType lightVolumeType;
int probeIndex;
int listType;

static float CalculateProbeLogVolume(Bounds bounds)
{
float boxVolume = 8 * bounds.extents.x * bounds.extents.y * bounds.extents.z;
float logVolume = Mathf.Clamp(256 + Mathf.Log(boxVolume, 1.05f), 0, 4095); // Allow for negative exponents
//Notes:
// - 1+ term is to prevent having negative values in the log result
// - 1000* is too keep 3 digit after the dot while we truncate the result later
// - 1048575 is 2^20-1 as we pack the result on 20bit later
float boxVolume = 8f* bounds.extents.x * bounds.extents.y * bounds.extents.z;
float logVolume = Mathf.Clamp(Mathf.Log(1 + boxVolume, 1.05f)*1000, 0, 1048575);
lightVolumeType = (LightVolumeType)((sortKey >> 17) & 0x3);
probeIndex = (int)(sortKey & 0xFFFF);
listType = (int)((sortKey >> 16) & 1);
lightVolumeType = (LightVolumeType)((sortKey >> 9) & 0x3);
probeIndex = (int)(sortKey & 0xFF);
listType = (int)((sortKey >> 8) & 1);
// 12 bit volume, 3 bit LightVolumeType, 1 bit list type, 16 bit index
return (uint)logVolume << 20 | (uint)lightVolumeType << 17 | listType << 16 | ((uint)probeIndex & 0xFFFF);
// 20 bit volume, 3 bit LightVolumeType, 1 bit list type, 8 bit index
return (uint)logVolume << 12 | (uint)lightVolumeType << 9 | listType << 8 | ((uint)probeIndex & 0xFF);
}
void VoxelLightListGeneration(CommandBuffer cmd, HDCamera hdCamera, Matrix4x4[] projscrArr, Matrix4x4[] invProjscrArr, RenderTargetIdentifier cameraDepthBufferRT)

bool isOrthographic = camera.orthographic;
// camera to screen matrix (and it's inverse)
var projArr = new Matrix4x4[2];
var projscrArr = new Matrix4x4[2];
var invProjscrArr = new Matrix4x4[2];
if (m_FrameSettings.enableStereo)
{
// XRTODO: If possible, we could generate a non-oblique stereo projection

// Once we generate this non-oblique projection matrix, it can be shared across both eyes (un-array)
for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++)
{
projArr[eyeIndex] = CameraProjectionStereoLHS(hdCamera.camera, (Camera.StereoscopicEye)eyeIndex);
projscrArr[eyeIndex] = temp * projArr[eyeIndex];
invProjscrArr[eyeIndex] = projscrArr[eyeIndex].inverse;
m_LightListProjMatrices[eyeIndex] = CameraProjectionStereoLHS(hdCamera.camera, (Camera.StereoscopicEye)eyeIndex);
m_LightListProjscrMatrices[eyeIndex] = temp * m_LightListProjMatrices[eyeIndex];
m_LightListInvProjscrMatrices[eyeIndex] = m_LightListProjscrMatrices[eyeIndex].inverse;
projArr[0] = GeometryUtils.GetProjectionMatrixLHS(hdCamera.camera);
projscrArr[0] = temp * projArr[0];
invProjscrArr[0] = projscrArr[0].inverse;
m_LightListProjMatrices[0] = GeometryUtils.GetProjectionMatrixLHS(hdCamera.camera);
m_LightListProjscrMatrices[0] = temp * m_LightListProjMatrices[0];
m_LightListInvProjscrMatrices[0] = m_LightListProjscrMatrices[0].inverse;
var isProjectionOblique = GeometryUtils.IsProjectionMatrixOblique(projArr[0]);
var isProjectionOblique = GeometryUtils.IsProjectionMatrixOblique(m_LightListProjMatrices[0]);
// generate screen-space AABBs (used for both fptl and clustered).
if (m_lightCount != 0)

temp.SetRow(2, new Vector4(0.0f, 0.0f, 0.5f, 0.5f));
temp.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
var projhArr = new Matrix4x4[2];
var invProjhArr = new Matrix4x4[2];
projhArr[eyeIndex] = temp * projArr[eyeIndex];
invProjhArr[eyeIndex] = projhArr[eyeIndex].inverse;
m_LightListProjHMatrices[eyeIndex] = temp * m_LightListProjMatrices[eyeIndex];
m_LightListInvProjHMatrices[eyeIndex] = m_LightListProjHMatrices[eyeIndex].inverse;
projhArr[0] = temp * projArr[0];
invProjhArr[0] = projhArr[0].inverse;
m_LightListProjHMatrices[0] = temp * m_LightListProjMatrices[0];
m_LightListInvProjHMatrices[0] = m_LightListProjHMatrices[0].inverse;
}
var genAABBKernel = isProjectionOblique ? s_GenAABBKernel_Oblique : s_GenAABBKernel;

cmd.SetComputeIntParam(buildScreenAABBShader, HDShaderIDs.g_iNrVisibLights, m_lightCount);
cmd.SetComputeBufferParam(buildScreenAABBShader, genAABBKernel, HDShaderIDs.g_data, s_ConvexBoundsBuffer);
cmd.SetComputeMatrixArrayParam(buildScreenAABBShader, HDShaderIDs.g_mProjectionArr, projhArr);
cmd.SetComputeMatrixArrayParam(buildScreenAABBShader, HDShaderIDs.g_mInvProjectionArr, invProjhArr);
cmd.SetComputeMatrixArrayParam(buildScreenAABBShader, HDShaderIDs.g_mProjectionArr, m_LightListProjHMatrices);
cmd.SetComputeMatrixArrayParam(buildScreenAABBShader, HDShaderIDs.g_mInvProjectionArr, m_LightListInvProjHMatrices);
// In stereo, we output two sets of AABB bounds
cmd.SetComputeBufferParam(buildScreenAABBShader, genAABBKernel, HDShaderIDs.g_vBoundsBuffer, s_AABBBoundsBuffer);

cmd.SetComputeIntParam(buildPerBigTileLightListShader, HDShaderIDs._EnvLightIndexShift, m_lightList.lights.Count);
cmd.SetComputeIntParam(buildPerBigTileLightListShader, HDShaderIDs._DecalIndexShift, m_lightList.lights.Count + m_lightList.envLights.Count);
cmd.SetComputeMatrixArrayParam(buildPerBigTileLightListShader, HDShaderIDs.g_mScrProjectionArr, projscrArr);
cmd.SetComputeMatrixArrayParam(buildPerBigTileLightListShader, HDShaderIDs.g_mInvScrProjectionArr, invProjscrArr);
cmd.SetComputeMatrixArrayParam(buildPerBigTileLightListShader, HDShaderIDs.g_mScrProjectionArr, m_LightListProjscrMatrices);
cmd.SetComputeMatrixArrayParam(buildPerBigTileLightListShader, HDShaderIDs.g_mInvScrProjectionArr, m_LightListInvProjscrMatrices);
cmd.SetComputeFloatParam(buildPerBigTileLightListShader, HDShaderIDs.g_fNearPlane, camera.nearClipPlane);
cmd.SetComputeFloatParam(buildPerBigTileLightListShader, HDShaderIDs.g_fFarPlane, camera.farClipPlane);

cmd.SetComputeBufferParam(buildPerTileLightListShader, genListPerTileKernel, HDShaderIDs._LightVolumeData, s_LightVolumeDataBuffer);
cmd.SetComputeBufferParam(buildPerTileLightListShader, genListPerTileKernel, HDShaderIDs.g_data, s_ConvexBoundsBuffer);
cmd.SetComputeMatrixParam(buildPerTileLightListShader, HDShaderIDs.g_mScrProjection, projscrArr[0]);
cmd.SetComputeMatrixParam(buildPerTileLightListShader, HDShaderIDs.g_mInvScrProjection, invProjscrArr[0]);
cmd.SetComputeMatrixParam(buildPerTileLightListShader, HDShaderIDs.g_mScrProjection, m_LightListProjscrMatrices[0]);
cmd.SetComputeMatrixParam(buildPerTileLightListShader, HDShaderIDs.g_mInvScrProjection, m_LightListInvProjscrMatrices[0]);
cmd.SetComputeTextureParam(buildPerTileLightListShader, genListPerTileKernel, HDShaderIDs.g_depth_tex, cameraDepthBufferRT);
cmd.SetComputeBufferParam(buildPerTileLightListShader, genListPerTileKernel, HDShaderIDs.g_vLightList, s_LightList);

}
// Cluster
VoxelLightListGeneration(cmd, hdCamera, projscrArr, invProjscrArr, cameraDepthBufferRT);
VoxelLightListGeneration(cmd, hdCamera, m_LightListProjscrMatrices, m_LightListInvProjscrMatrices, cameraDepthBufferRT);
if (enableFeatureVariants)
{

s_LightVolumeDataBuffer.SetData(m_lightList.lightVolumes);
}
HDAdditionalLightData GetHDAdditionalLightData(VisibleLight light)
HDAdditionalLightData GetHDAdditionalLightData(Light light)
var add = light.light.GetComponent<HDAdditionalLightData>();
// Light reference can be null for particle lights.
var add = light != null ? light.GetComponent<HDAdditionalLightData>() : null;
if (add == null)
{
add = HDUtils.s_DefaultHDAdditionalLightData;

}
}
public void RenderDebugOverlay(HDCamera hdCamera, CommandBuffer cmd, DebugDisplaySettings debugDisplaySettings, ref float x, ref float y, float overlaySize, float width)
public void RenderDebugOverlay(HDCamera hdCamera, CommandBuffer cmd, DebugDisplaySettings debugDisplaySettings, ref float x, ref float y, float overlaySize, float width, CullResults cullResults)
{
LightingDebugSettings lightingDebug = debugDisplaySettings.lightingDebugSettings;

{
m_ShadowMgr.DisplayShadowMap(cmd, m_DebugShadowMapMaterial, lightingDebug.shadowAtlasIndex, lightingDebug.shadowSliceIndex, x, y, overlaySize, overlaySize, lightingDebug.shadowMinValue, lightingDebug.shadowMaxValue, hdCamera.camera.cameraType != CameraType.SceneView);
HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, hdCamera.actualWidth);
}
}
if (lightingDebug.displayLightVolumes)
{
// First of all let's do the regions for the light sources (we only support Poncutal and Area)
int numLights = cullResults.visibleLights.Count;
for (int lightIdx = 0; lightIdx < numLights; ++lightIdx)
{
// Let's build the light's bounding sphere matrix
Light currentLegacyLight = cullResults.visibleLights[lightIdx].light;
if (currentLegacyLight == null) continue;
HDAdditionalLightData currentHDRLight = currentLegacyLight.GetComponent<HDAdditionalLightData>();
if (currentHDRLight == null) continue;
MaterialPropertyBlock materialBlock = new MaterialPropertyBlock();
Matrix4x4 positionMat = Matrix4x4.Translate(currentLegacyLight.transform.position);
if(currentLegacyLight.type == LightType.Point || currentLegacyLight.type == LightType.Area)
{
materialBlock.SetVector("_Range", new Vector3(currentLegacyLight.range, currentLegacyLight.range, currentLegacyLight.range));
switch (currentHDRLight.lightTypeExtent)
{
case LightTypeExtent.Punctual:
{
materialBlock.SetColor("_Color", new Color(0.0f, 1.0f, 0.0f, 0.5f));
materialBlock.SetVector("_Offset", new Vector3(0, 0, 0));
cmd.DrawMesh(DebugShapes.instance.RequestSphereMesh(), positionMat, m_DebugLightVolumeMaterial, 0, -1, materialBlock);
}
break;
case LightTypeExtent.Rectangle:
{
materialBlock.SetColor("_Color", new Color(0.0f, 1.0f, 1.0f, 0.5f));
materialBlock.SetVector("_Offset", new Vector3(0, 0, 0));
cmd.DrawMesh(DebugShapes.instance.RequestSphereMesh(), positionMat, m_DebugLightVolumeMaterial, 0, -1, materialBlock);
}
break;
case LightTypeExtent.Line:
{
materialBlock.SetColor("_Color", new Color(1.0f, 0.0f, 0.5f, 0.5f));
materialBlock.SetVector("_Offset", new Vector3(0, 0, 0));
cmd.DrawMesh(DebugShapes.instance.RequestSphereMesh(), positionMat, m_DebugLightVolumeMaterial, 0, -1, materialBlock);
}
break;
default:
break;
}
}
else if(currentLegacyLight.type == LightType.Spot)
{
if(currentHDRLight.spotLightShape == SpotLightShape.Cone)
{
float bottomRadius = Mathf.Tan(currentLegacyLight.spotAngle * Mathf.PI / 360.0f) * currentLegacyLight.range;
materialBlock.SetColor("_Color", new Color(1.0f, 0.5f, 0.0f, 0.5f));
materialBlock.SetVector("_Range", new Vector3(bottomRadius, bottomRadius, currentLegacyLight.range));
materialBlock.SetVector("_Offset", new Vector3(0, 0, 0));
cmd.DrawMesh(DebugShapes.instance.RequestConeMesh(), currentLegacyLight.gameObject.transform.localToWorldMatrix, m_DebugLightVolumeMaterial, 0, -1, materialBlock);
}
else if(currentHDRLight.spotLightShape == SpotLightShape.Box)
{
materialBlock.SetColor("_Color", new Color(1.0f, 0.5f, 0.0f, 0.5f));
materialBlock.SetVector("_Range", new Vector3(currentHDRLight.shapeWidth, currentHDRLight.shapeHeight, currentLegacyLight.range));
materialBlock.SetVector("_Offset", new Vector3(0, 0, currentLegacyLight.range / 2.0f));
cmd.DrawMesh(DebugShapes.instance.RequestBoxMesh(), currentLegacyLight.gameObject.transform.localToWorldMatrix, m_DebugLightVolumeMaterial, 0, -1, materialBlock);
}
else if (currentHDRLight.spotLightShape == SpotLightShape.Pyramid)
{
float bottomWidth = Mathf.Tan(currentLegacyLight.spotAngle * Mathf.PI / 360.0f) * currentLegacyLight.range;
materialBlock.SetColor("_Color", new Color(1.0f, 0.5f, 0.0f, 0.5f));
materialBlock.SetVector("_Range", new Vector3(currentHDRLight.aspectRatio * bottomWidth * 2, bottomWidth * 2 , currentLegacyLight.range));
materialBlock.SetVector("_Offset", new Vector3(0, 0, 0));
cmd.DrawMesh(DebugShapes.instance.RequestPyramidMesh(), currentLegacyLight.gameObject.transform.localToWorldMatrix, m_DebugLightVolumeMaterial, 0, -1, materialBlock);
}
}
}
// Now let's do the same but for reflection probes
int numProbes = cullResults.visibleReflectionProbes.Count;
for (int probeIdx = 0; probeIdx < numProbes; ++probeIdx)
{
// Let's build the light's bounding sphere matrix
ReflectionProbe currentLegacyProbe = cullResults.visibleReflectionProbes[probeIdx].probe;
HDAdditionalReflectionData currentHDProbe = currentLegacyProbe.GetComponent<HDAdditionalReflectionData>();
MaterialPropertyBlock materialBlock = new MaterialPropertyBlock();
Mesh targetMesh = null;
if (currentHDProbe.influenceVolume.shape == InfluenceShape.Sphere)
{
materialBlock.SetVector("_Range", new Vector3(currentHDProbe.influenceVolume.sphereRadius, currentHDProbe.influenceVolume.sphereRadius, currentHDProbe.influenceVolume.sphereRadius));
targetMesh = DebugShapes.instance.RequestSphereMesh();
}
else
{
materialBlock.SetVector("_Range", new Vector3(currentHDProbe.influenceVolume.boxSize.x, currentHDProbe.influenceVolume.boxSize.y, currentHDProbe.influenceVolume.boxSize.z));
targetMesh = DebugShapes.instance.RequestBoxMesh();
}
materialBlock.SetColor("_Color", new Color(1.0f, 1.0f, 0.0f, 0.5f));
materialBlock.SetVector("_Offset", new Vector3(0, 0, 0));
Matrix4x4 positionMat = Matrix4x4.Translate(currentLegacyProbe.transform.position);
cmd.DrawMesh(targetMesh, positionMat, m_DebugLightVolumeMaterial, 0, -1, materialBlock);
}
}
}

61
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/HDAdditionalReflectionData.cs


Second,
HDProbeChild,
UseInfluenceVolume,
MergeEditors,
// Add new version here and they will automatically be the Current one
Max,
Current = Max - 1

int m_Version;
ReflectionProbe m_LegacyProbe;
ReflectionProbe legacyProbe
/// <summary>Get the sibling component ReflectionProbe</summary>
public ReflectionProbe reflectionProbe
if (m_LegacyProbe == null || m_LegacyProbe.Equals(null))
if(m_LegacyProbe == null || m_LegacyProbe.Equals(null))
return m_LegacyProbe;
else
{
return m_LegacyProbe;
}
return m_LegacyProbe;
}
}

bool needMigrateToHDProbeChild = false;
bool needMigrateToUseInfluenceVolume = false;
bool needMigrateToMergeEditors = false;
public void CopyTo(HDAdditionalReflectionData data)
{

{
needMigrateToUseInfluenceVolume = true;
}
else if (m_Version < (int)Version.MergeEditors)
{
needMigrateToMergeEditors = true;
}
else
{
// Add here data migration code that do not use other component

MigrateToHDProbeChild();
if (needMigrateToUseInfluenceVolume)
MigrateToUseInfluenceVolume();
if (needMigrateToMergeEditors)
MigrateToMergeEditors();
ReflectionSystem.RegisterProbe(this);
}
void OnDisable()
{
ReflectionSystem.UnregisterProbe(this);
}
void OnValidate()
{
ReflectionSystem.UnregisterProbe(this);
if (isActiveAndEnabled)
ReflectionSystem.RegisterProbe(this);
mode = legacyProbe.mode;
refreshMode = legacyProbe.refreshMode;
mode = reflectionProbe.mode;
refreshMode = reflectionProbe.refreshMode;
m_Version = (int)Version.HDProbeChild;
needMigrateToHDProbeChild = false;
OnAfterDeserialize(); //continue migrating if needed

{
influenceVolume.boxSize = legacyProbe.size;
influenceVolume.boxSize = reflectionProbe.size;
#pragma warning disable CS0618 // Type or member is obsolete
influenceVolume.sphereRadius = influenceSphereRadius;
influenceVolume.shape = influenceShape; //must be done after each size transfert

//User will lose parameters corresponding to non used mode between simplified and advanced
}
void MigrateToMergeEditors()
{
infiniteProjection = !reflectionProbe.boxProjection;
reflectionProbe.boxProjection = false;
m_Version = (int)Version.MergeEditors;
needMigrateToMergeEditors = false;
OnAfterDeserialize(); //continue migrating if needed
}
legacyProbe.mode = value; //ensure compatibility till we capture without the legacy component
reflectionProbe.mode = value; //ensure compatibility till we capture without the legacy component
if(value == ReflectionProbeMode.Realtime)
{
refreshMode = ReflectionProbeRefreshMode.EveryFrame;
}
}
}

{
base.refreshMode = value;
legacyProbe.refreshMode = value; //ensure compatibility till we capture without the legacy component
reflectionProbe.refreshMode = value; //ensure compatibility till we capture without the legacy component
legacyProbe.size = size;
legacyProbe.center = transform.rotation*offset;
reflectionProbe.size = size;
reflectionProbe.center = transform.rotation*offset;
}
}
}

26
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/HDProbe.cs


{
[SerializeField, FormerlySerializedAs("proxyVolumeComponent"), FormerlySerializedAs("m_ProxyVolumeReference")]
ReflectionProxyVolumeComponent m_ProxyVolume = null;
[SerializeField]
bool m_InfiniteProjection = true; //usable when no proxy set
[SerializeField]
FrameSettings m_FrameSettings = null;
[SerializeField, FormerlySerializedAsAttribute("dimmer"), FormerlySerializedAsAttribute("m_Dimmer"), FormerlySerializedAsAttribute("multiplier")]
float m_Multiplier = 1.0f;

ReflectionProbeMode m_Mode = ReflectionProbeMode.Baked;
[SerializeField]
ReflectionProbeRefreshMode m_RefreshMode = ReflectionProbeRefreshMode.OnAwake;
RenderTexture m_RealtimeTexture = null;
/// <summary>ProxyVolume currently used by this probe.</summary>
public ReflectionProxyVolumeComponent proxyVolume { get { return m_ProxyVolume; } }

/// <summary>Frame settings in use with this probe.</summary>
public FrameSettings frameSettings { get { return m_FrameSettings; } }
/// <summary>Get the realtime acquired Render Texture</summary>
public RenderTexture realtimeTexture { get { return m_RealtimeTexture; } internal set { m_RealtimeTexture = value; } }
/// <summary>The capture mode.</summary>
public virtual ReflectionProbeMode mode

{
get { return m_RefreshMode; }
set { m_RefreshMode = value; }
}
public bool infiniteProjection
{
get
{
return (proxyVolume != null && proxyVolume.proxyVolume.shape == ProxyShape.Infinite)
|| (proxyVolume == null && m_InfiniteProjection);
}
set
{
m_InfiniteProjection = value;
}
}
internal void Awake()

19
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/PlanarReflectionProbe.cs


using UnityEngine.Serialization;
using UnityEngine.Rendering;
using UnityEngine.Assertions;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{

[SerializeField]
Texture m_BakedTexture;
[SerializeField]
FrameSettings m_FrameSettings = null;
[SerializeField]
float m_CaptureNearPlane = 1;
[SerializeField]
float m_CaptureFarPlane = 1000;

[SerializeField]
[Range(0, 180)]
float m_FieldOfViewOverride = 90;
RenderTexture m_RealtimeTexture;
public bool overrideFieldOfView { get { return m_OverrideFieldOfView; } }
public float fieldOfViewOverride { get { return m_FieldOfViewOverride; } }

}
public Texture customTexture { get { return m_CustomTexture; } set { m_CustomTexture = value; } }
public Texture bakedTexture { get { return m_BakedTexture; } set { m_BakedTexture = value; }}
public RenderTexture realtimeTexture { get { return m_RealtimeTexture; } internal set { m_RealtimeTexture = value; } }
public FrameSettings frameSettings { get { return m_FrameSettings; } }
public float captureNearPlane { get { return m_CaptureNearPlane; } }
public float captureFarPlane { get { return m_CaptureFarPlane; } }
public CapturePositionMode capturePositionMode { get { return m_CapturePositionMode; } }

: influenceVolume.boxSize;
}
}
public bool infiniteProjection
{
get
{
return proxyVolume != null
&& proxyVolume.proxyVolume.shape == ProxyShape.Infinite;
}
}
public bool useMirrorPlane
{

public void OnAfterDeserialize()
{
Assert.IsNotNull(influenceVolume, "influenceVolume must have an instance at this point. See HDProbe.Awake()");
if (m_Version != currentVersion)
{
// Add here data migration code

}
m_Version = currentVersion;
}
influenceVolume.boxBlendNormalDistanceNegative = Vector3.zero;
influenceVolume.boxBlendNormalDistancePositive = Vector3.zero;
}
}
}

29
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ProbeWrapper.cs


if (add.influenceVolume == null)
{
add.Awake(); // We need to init the 'default' data if it isn't
}
}
Vector3 distance = Vector3.one * probe.blendDistance;
add.influenceVolume.boxBlendDistancePositive = distance;
add.influenceVolume.boxBlendDistanceNegative = distance;

}
}
public override Texture texture { get { return probe.texture; } }
public override Texture texture
{
get
{
if(additional.mode == ReflectionProbeMode.Realtime)
{
return additional.realtimeTexture;
}
else
{
return probe.texture;
}
}
}
public override ReflectionProbeMode mode { get { return probe.probe.mode; } }
public override EnvShapeType influenceShapeType { get { return ConvertShape(additional.influenceVolume.shape); } }
public override float weight { get { return additional.weight; } }

: influenceExtents;
}
}
public override bool infiniteProjection
{
get
{
return additional.proxyVolume != null
? additional.proxyVolume.proxyVolume.shape == ProxyShape.Infinite
: probe.boxProjection == 0;
}
}
public override bool infiniteProjection { get { return additional.infiniteProjection; } }
public override Matrix4x4 proxyToWorld
{

10
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ReflectionSystem.cs


s_Instance.RegisterProbe(planarProbe);
}
public static void RegisterProbe(HDAdditionalReflectionData probe)
{
s_Instance.RegisterProbe(probe);
}
}
public static void UnregisterProbe(HDAdditionalReflectionData probe)
{
s_Instance.UnregisterProbe(probe);
}
public static void RequestRealtimeRender(PlanarReflectionProbe probe)

167
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ReflectionSystemInternal.cs


{
static Camera s_RenderCamera = null;
static HDAdditionalCameraData s_RenderCameraData;
static int frame = Time.frameCount;
HashSet<HDAdditionalReflectionData> m_AdditionalDataReflectionProbes;
HashSet<HDAdditionalReflectionData> m_AdditionalDataReflectionProbe_RealtimeUpdate;
HashSet<HDAdditionalReflectionData> m_AdditionalDataReflectionProbe_RequestRealtimeRender;
HDAdditionalReflectionData[] m_AdditionalDataReflectionProbe_RealtimeUpdate_WorkArray;
HashSet<PlanarReflectionProbe> m_PlanarReflectionProbes;
HashSet<PlanarReflectionProbe> m_PlanarReflectionProbe_DirtyBounds;

m_PlanarReflectionProbesArray = new PlanarReflectionProbe[parameters.maxActivePlanarReflectionProbe];
m_PlanarReflectionProbeBoundsArray = new BoundingSphere[parameters.maxActivePlanarReflectionProbe];
m_PlanarReflectionProbe_RealtimeUpdate_WorkArray = new PlanarReflectionProbe[parameters.maxPlanarReflectionProbePerCamera];
m_AdditionalDataReflectionProbe_RealtimeUpdate_WorkArray = new HDAdditionalReflectionData[parameters.maxPlanarReflectionProbePerCamera]; ;
m_AdditionalDataReflectionProbes = new HashSet<HDAdditionalReflectionData>();
m_AdditionalDataReflectionProbe_RealtimeUpdate = new HashSet<HDAdditionalReflectionData>();
m_AdditionalDataReflectionProbe_RequestRealtimeRender = new HashSet<HDAdditionalReflectionData>();
m_PlanarReflectionProbes = new HashSet<PlanarReflectionProbe>();
m_PlanarReflectionProbe_DirtyBounds = new HashSet<PlanarReflectionProbe>();
m_PlanarReflectionProbe_RequestRealtimeRender = new HashSet<PlanarReflectionProbe>();

if (previous != null)
{
m_AdditionalDataReflectionProbes.UnionWith(previous.m_AdditionalDataReflectionProbes);
m_AdditionalDataReflectionProbe_RequestRealtimeRender.UnionWith(previous.m_AdditionalDataReflectionProbe_RequestRealtimeRender);
m_AdditionalDataReflectionProbe_RealtimeUpdate.UnionWith(previous.m_AdditionalDataReflectionProbe_RealtimeUpdate);
m_PlanarReflectionProbes.UnionWith(previous.m_PlanarReflectionProbes);
m_PlanarReflectionProbe_DirtyBounds.UnionWith(m_PlanarReflectionProbes);
m_PlanarReflectionProbe_RequestRealtimeRender.UnionWith(previous.m_PlanarReflectionProbe_RequestRealtimeRender);

}
}
public void RegisterProbe(HDAdditionalReflectionData additional)
{
m_AdditionalDataReflectionProbes.Add(additional);
//SetProbeBoundsDirty(probe);
if (additional.mode == ReflectionProbeMode.Realtime)
{
//switch (additional.refreshMode)
//{
// case ReflectionProbeRefreshMode.OnAwake:
// m_AdditionalDataReflectionProbe_RequestRealtimeRender.Add(additional);
// break;
// case ReflectionProbeRefreshMode.EveryFrame:
m_AdditionalDataReflectionProbe_RealtimeUpdate.Add(additional);
// break;
//}
}
}
public void UnregisterProbe(PlanarReflectionProbe planarProbe)
{
m_PlanarReflectionProbes.Remove(planarProbe);

m_PlanarReflectionProbe_PerCamera_RealtimeUpdate.Remove(planarProbe);
}
public void UnregisterProbe(HDAdditionalReflectionData additional)
{
m_AdditionalDataReflectionProbes.Remove(additional);
m_AdditionalDataReflectionProbe_RequestRealtimeRender.Remove(additional);
m_AdditionalDataReflectionProbe_RealtimeUpdate.Remove(additional);
}
public void PrepareCull(Camera camera, ReflectionProbeCullResults results)
{
UpdateAllPlanarReflectionProbeBounds();

{
var probe = m_PlanarReflectionProbe_RealtimeUpdate_WorkArray[i];
if (!IsRealtimeTextureValid(probe.realtimeTexture))
if (!IsRealtimeTextureValid(probe.realtimeTexture, true))
{
if (probe.realtimeTexture != null)
probe.realtimeTexture.Release();

{
var probe = m_PlanarReflectionProbe_RealtimeUpdate_WorkArray[i];
if (!IsRealtimeTextureValid(probe.realtimeTexture))
if (!IsRealtimeTextureValid(probe.realtimeTexture, true))
{
if (probe.realtimeTexture != null)
probe.realtimeTexture.Release();

Render(probe, probe.realtimeTexture);
}
}
if ((probeTypes & ReflectionProbeType.ReflectionProbe) != 0 && frame != Time.frameCount)
{
//do only one per frame
frame = Time.frameCount;
// Discard disabled probes in requested render probes
m_AdditionalDataReflectionProbe_RequestRealtimeRender.IntersectWith(m_AdditionalDataReflectionProbes);
// Include all realtime probe modes
m_AdditionalDataReflectionProbe_RequestRealtimeRender.UnionWith(m_AdditionalDataReflectionProbe_RealtimeUpdate);
var length = Mathf.Min(m_AdditionalDataReflectionProbe_RequestRealtimeRender.Count, m_AdditionalDataReflectionProbe_RealtimeUpdate_WorkArray.Length);
m_AdditionalDataReflectionProbe_RequestRealtimeRender.CopyTo(m_AdditionalDataReflectionProbe_RealtimeUpdate_WorkArray);
m_AdditionalDataReflectionProbe_RequestRealtimeRender.Clear();
// 1. Allocate if necessary target texture
for (var i = 0; i < length; i++)
{
var additional = m_AdditionalDataReflectionProbe_RealtimeUpdate_WorkArray[i];
if (!IsRealtimeTextureValid(additional.realtimeTexture, false))
{
if (additional.realtimeTexture != null)
additional.realtimeTexture.Release();
additional.realtimeTexture = NewRenderTarget(additional);
}
}
// 2. Render
for (var i = 0; i < length; i++)
{
var additional = m_AdditionalDataReflectionProbe_RealtimeUpdate_WorkArray[i];
Render(additional, additional.realtimeTexture);
}
}
}
public RenderTexture NewRenderTarget(PlanarReflectionProbe probe)

return rt;
}
public RenderTexture NewRenderTarget(HDAdditionalReflectionData probe)
{
var rt = new RenderTexture(m_Parameters.reflectionProbeSize, m_Parameters.reflectionProbeSize, 0, RenderTextureFormat.ARGBHalf);
// No hide and don't save for this one
rt.useMipMap = true;
rt.autoGenerateMips = false;
rt.name = CoreUtils.GetRenderTargetAutoName(m_Parameters.reflectionProbeSize, m_Parameters.reflectionProbeSize, 1, RenderTextureFormat.ARGBHalf, "ProbeRT");
rt.dimension = TextureDimension.Cube;
rt.Create();
return rt;
}
//public float GetCaptureCameraFOVFor(PlanarReflectionProbe probe, Camera viewerCamera)
//{
// switch (probe.influenceVolume.shapeType)

// }
//}
bool IsRealtimeTextureValid(RenderTexture renderTexture)
bool IsRealtimeTextureValid(RenderTexture renderTexture, bool isPlanar)
return renderTexture != null
&& renderTexture.width == m_Parameters.planarReflectionProbeSize
&& renderTexture.height == m_Parameters.planarReflectionProbeSize
&& renderTexture.format == RenderTextureFormat.ARGBHalf
&& renderTexture.useMipMap;
if(isPlanar)
return renderTexture != null
&& renderTexture.width == m_Parameters.planarReflectionProbeSize
&& renderTexture.height == m_Parameters.planarReflectionProbeSize
&& renderTexture.format == RenderTextureFormat.ARGBHalf
&& renderTexture.useMipMap;
else
return renderTexture != null
&& renderTexture.width == m_Parameters.reflectionProbeSize
&& renderTexture.height == m_Parameters.reflectionProbeSize
&& renderTexture.format == RenderTextureFormat.ARGBHalf
&& renderTexture.useMipMap;
}
public void RequestRealtimeRender(PlanarReflectionProbe probe)

renderCamera.Render();
GL.invertCulling = false;
renderCamera.targetTexture = null;
target.IncrementUpdateCount();
}
public void Render(HDAdditionalReflectionData additional, RenderTexture target, Camera viewerCamera = null)
{
var renderCamera = GetRenderCamera();
// Copy current frameSettings of this probe to the HDAdditionalData of the render camera
//probe.frameSettings.CopyTo(s_RenderCameraData.GetFrameSettings());
SetupCameraForRender(renderCamera, additional, viewerCamera);
renderCamera.RenderToCubemap(target);
target.IncrementUpdateCount();
}

ctr.rotation = captureRotation;
}
static void SetupCameraForRender(Camera camera, HDAdditionalReflectionData additional, Camera viewerCamera = null)
{
float nearClipPlane, farClipPlane, aspect, fov;
Color backgroundColor;
CameraClearFlags clearFlags;
Vector3 capturePosition;
Quaternion captureRotation;
Matrix4x4 worldToCamera, projection;
CalculateCaptureCameraProperties(additional,
out nearClipPlane, out farClipPlane,
out aspect, out fov, out clearFlags, out backgroundColor,
out worldToCamera, out projection,
out capturePosition, out captureRotation, viewerCamera);
camera.farClipPlane = farClipPlane;
camera.nearClipPlane = nearClipPlane;
camera.fieldOfView = fov;
camera.aspect = aspect;
camera.clearFlags = clearFlags;
camera.backgroundColor = camera.backgroundColor;
camera.projectionMatrix = projection;
camera.worldToCameraMatrix = worldToCamera;
camera.cullingMask = additional.reflectionProbe.cullingMask;
var ctr = camera.transform;
ctr.position = capturePosition;
ctr.rotation = captureRotation;
}
public static void CalculateCaptureCameraViewProj(PlanarReflectionProbe probe, out Matrix4x4 worldToCamera, out Matrix4x4 projection, out Vector3 capturePosition, out Quaternion captureRotation, Camera viewerCamera = null)
{
float nearClipPlane, farClipPlane, aspect, fov;

CalculateMirroredCaptureCameraProperties(probe, viewerCamera, out nearClipPlane, out farClipPlane, out aspect, out fov, out clearFlags, out backgroundColor, out worldToCamera, out projection, out capturePosition, out captureRotation);
else
CalculateStaticCaptureCameraProperties(probe, out nearClipPlane, out farClipPlane, out aspect, out fov, out clearFlags, out backgroundColor, out worldToCamera, out projection, out capturePosition, out captureRotation);
}
public static void CalculateCaptureCameraProperties(HDAdditionalReflectionData additional, out float nearClipPlane, out float farClipPlane, out float aspect, out float fov, out CameraClearFlags clearFlags, out Color backgroundColor, out Matrix4x4 worldToCamera, out Matrix4x4 projection, out Vector3 capturePosition, out Quaternion captureRotation, Camera viewerCamera = null)
{
nearClipPlane = additional.reflectionProbe.nearClipPlane;
farClipPlane = additional.reflectionProbe.farClipPlane;
aspect = 1f;
fov = 90f;
clearFlags = CameraClearFlags.Nothing;
backgroundColor = Color.white;
capturePosition = additional.transform.position; //at the moment capture position is at probe position
captureRotation = Quaternion.identity;
worldToCamera = GeometryUtils.CalculateWorldToCameraMatrixRHS(capturePosition, captureRotation);
projection = Matrix4x4.Perspective(fov, aspect, nearClipPlane, farClipPlane);
}
static bool IsProbeCaptureMirrored(PlanarReflectionProbe probe, Camera viewerCamera)

14
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/ReflectionSystemParameters.cs


{
maxPlanarReflectionProbePerCamera = 128,
maxActivePlanarReflectionProbe = 512,
planarReflectionProbeSize = 128
planarReflectionProbeSize = 128,
maxActiveReflectionProbe = 512,
reflectionProbeSize = 128
};
/// <summary>

/// Size of the planar probe textures.
/// </summary>
public int planarReflectionProbeSize;
/// <summary>
/// Maximum number of active non planar reflection in the world.
/// </summary>
public int maxActiveReflectionProbe;
/// <summary>
/// Size of the non planar probe textures.
/// </summary>
public int reflectionProbeSize;
}
}

16
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/Volumes/InfluenceVolume.cs


float m_EditorSimplifiedModeBlendNormalDistance;
[SerializeField, FormerlySerializedAs("editorAdvancedModeEnabled")]
bool m_EditorAdvancedModeEnabled;
[SerializeField]
Vector3 m_EditorAdvancedModeFaceFadePositive = Vector3.one;
[SerializeField]
Vector3 m_EditorAdvancedModeFaceFadeNegative = Vector3.one;
// Sphere
[SerializeField, FormerlySerializedAs("m_SphereBaseRadius")]

data.m_EditorAdvancedModeBlendNormalDistanceNegative = m_EditorAdvancedModeBlendNormalDistanceNegative;
data.m_EditorSimplifiedModeBlendNormalDistance = m_EditorSimplifiedModeBlendNormalDistance;
data.m_EditorAdvancedModeEnabled = m_EditorAdvancedModeEnabled;
data.m_EditorAdvancedModeFaceFadePositive = m_EditorAdvancedModeFaceFadePositive;
data.m_EditorAdvancedModeFaceFadeNegative = m_EditorAdvancedModeFaceFadeNegative;
}
/// <summary>Shape of this InfluenceVolume.</summary>

}
/// <summary>Offset of this influence volume to the component handling him.</summary>
public Vector3 offset { get { return m_Offset; } set { m_Offset = value; } }
public Vector3 offset
{
get { return m_Offset; }
set
{
m_Offset = value;
m_Probe.UpdatedInfluenceVolumeShape(boxSize, m_Offset);
}
}
/// <summary>Size of the InfluenceVolume in Box Mode.</summary>
public Vector3 boxSize

8
com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumetricLighting.cs


// VisualEnvironment sets global fog parameters: _GlobalAnisotropy, _GlobalScattering, _GlobalExtinction.
if (!hdCamera.frameSettings.enableVolumetrics || visualEnvironment.fogType != FogType.Volumetric)
if (!hdCamera.frameSettings.enableVolumetrics || visualEnvironment.fogType.value != FogType.Volumetric)
{
// Set the neutral black texture.
cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, CoreUtils.blackVolumeTexture);

return densityVolumes;
var visualEnvironment = VolumeManager.instance.stack.GetComponent<VisualEnvironment>();
if (visualEnvironment.fogType != FogType.Volumetric)
if (visualEnvironment.fogType.value != FogType.Volumetric)
return densityVolumes;
using (new ProfilingSample(cmd, "Prepare Visible Density Volume List"))

return;
var visualEnvironment = VolumeManager.instance.stack.GetComponent<VisualEnvironment>();
if (visualEnvironment.fogType != FogType.Volumetric)
if (visualEnvironment.fogType.value != FogType.Volumetric)
return;
using (new ProfilingSample(cmd, "Volume Voxelization"))

return;
var visualEnvironment = VolumeManager.instance.stack.GetComponent<VisualEnvironment>();
if (visualEnvironment.fogType != FogType.Volumetric)
if (visualEnvironment.fogType.value != FogType.Volumetric)
return;
using (new ProfilingSample(cmd, "Volumetric Lighting"))

6
com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLitData.hlsl


// If user provide bent normal then we process a better term
#if (defined(_BENTNORMALMAP0) || defined(_BENTNORMALMAP1) || defined(_BENTNORMALMAP2) || defined(_BENTNORMALMAP3)) && defined(_ENABLESPECULAROCCLUSION)
// If we have bent normal and ambient occlusion, process a specular occlusion
surfaceData.specularOcclusion = GetSpecularOcclusionFromBentAO(V, bentNormalWS, surfaceData);
#ifdef SPECULAR_OCCLUSION_USE_SPTD
surfaceData.specularOcclusion = GetSpecularOcclusionFromBentAOPivot(V, bentNormalWS, surfaceData.normalWS, surfaceData.ambientOcclusion, PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness));
#else
surfaceData.specularOcclusion = GetSpecularOcclusionFromBentAO(V, bentNormalWS, surfaceData.normalWS, surfaceData.ambientOcclusion, PerceptualSmoothnessToRoughness(surfaceData.perceptualSmoothness));
#endif
#elif defined(_MASKMAP0) || defined(_MASKMAP1) || defined(_MASKMAP2) || defined(_MASKMAP3)
surfaceData.specularOcclusion = GetSpecularOcclusionFromAmbientOcclusion(dot(surfaceData.normalWS, V), surfaceData.ambientOcclusion, PerceptualSmoothnessToRoughness(surfaceData.perceptualSmoothness));
#else

10
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.hlsl


#define HAS_REFRACTION (defined(_REFRACTION_PLANE) || defined(_REFRACTION_SPHERE)) && (defined(_REFRACTION_SSRAY_PROXY) || defined(_REFRACTION_SSRAY_HIZ))
#define DEFAULT_SPECULAR_VALUE 0.04
// Enum for materialFeatureId (only use for encode/decode GBuffer)
#define GBUFFER_LIT_STANDARD 0
// we have not enough space (3bit) to store mat feature to have SSS and Transmission as bitmask, such why we have all variant

preLightData.ltcTransformSpecular._m00_m02_m11_m20 = SAMPLE_TEXTURE2D_ARRAY_LOD(_LtcData, s_linear_clamp_sampler, uv, LTC_GGX_MATRIX_INDEX, 0);
// Construct a right-handed view-dependent orthogonal basis around the normal
preLightData.orthoBasisViewNormal[0] = normalize(V - N * preLightData.NdotV); // Do not clamp NdotV here
preLightData.orthoBasisViewNormal[2] = N;
preLightData.orthoBasisViewNormal[1] = cross(preLightData.orthoBasisViewNormal[2], preLightData.orthoBasisViewNormal[0]);
preLightData.orthoBasisViewNormal = GetOrthoBasisViewNormal(V, N, preLightData.NdotV);
preLightData.ltcTransformCoat = 0.0;
if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))

// If refraction is enable we use the transmittanceMask to lerp between current diffuse lighting and refraction value
// Physically speaking, transmittanceMask should be 1, but for artistic reasons, we let the value vary
//
// Note we also transfer the refracted light (lighting.indirect.specularTransmitted) into diffuseLighting
// since we know it won't be further processed: it is called at the end of the LightLoop(), but doing this
// enables opacity to affect it (in ApplyBlendMode()) while the rest of specularLighting escapes it.
#if HAS_REFRACTION
diffuseLighting = lerp(diffuseLighting, lighting.indirect.specularTransmitted, bsdfData.transmittanceMask);
#endif

20
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitData.hlsl


#include "HDRP/Material/MaterialUtilities.hlsl"
#include "HDRP/Material/Decal/DecalUtilities.hlsl"
// TODO: move this function to commonLighting.hlsl once validated it work correctly
float GetSpecularOcclusionFromBentAO(float3 V, float3 bentNormalWS, SurfaceData surfaceData)
{
// Retrieve cone angle
// Ambient occlusion is cosine weighted, thus use following equation. See slide 129
float cosAv = sqrt(1.0 - surfaceData.ambientOcclusion);
float roughness = max(PerceptualSmoothnessToRoughness(surfaceData.perceptualSmoothness), 0.01); // Clamp to 0.01 to avoid edge cases
float cosAs = exp2((-log(10.0)/log(2.0)) * Sq(roughness));
float cosB = dot(bentNormalWS, reflect(-V, surfaceData.normalWS));
return SphericalCapIntersectionSolidArea(cosAv, cosAs, cosB) / (TWO_PI * (1.0 - cosAs));
}
//#include "HDRP/Material/SphericalCapPivot/SPTDistribution.hlsl"
//#define SPECULAR_OCCLUSION_USE_SPTD
// Struct that gather UVMapping info of all layers + common calculation
// This is use to abstract the mapping that can differ on layers

// If user provide bent normal then we process a better term
#if defined(_BENTNORMALMAP) && defined(_ENABLESPECULAROCCLUSION)
// If we have bent normal and ambient occlusion, process a specular occlusion
surfaceData.specularOcclusion = GetSpecularOcclusionFromBentAO(V, bentNormalWS, surfaceData);
#ifdef SPECULAR_OCCLUSION_USE_SPTD
surfaceData.specularOcclusion = GetSpecularOcclusionFromBentAOPivot(V, bentNormalWS, surfaceData.normalWS, surfaceData.ambientOcclusion, PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness));
#else
surfaceData.specularOcclusion = GetSpecularOcclusionFromBentAO(V, bentNormalWS, surfaceData.normalWS, surfaceData.ambientOcclusion, PerceptualSmoothnessToRoughness(surfaceData.perceptualSmoothness));
#endif
#elif defined(_MASKMAP)
surfaceData.specularOcclusion = GetSpecularOcclusionFromAmbientOcclusion(ClampNdotV(dot(surfaceData.normalWS, V)), surfaceData.ambientOcclusion, PerceptualSmoothnessToRoughness(surfaceData.perceptualSmoothness));
#else

16
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitDataIndividualLayer.hlsl


#ifdef SURFACE_GRADIENT
normalTS += detailNormalTS * detailMask;
#else
normalTS = lerp(normalTS, BlendNormalRNM(normalTS, detailNormalTS), detailMask);
normalTS = lerp(normalTS, BlendNormalRNM(normalTS, detailNormalTS), detailMask); // todo: detailMask should lerp the angle of the quaternion rotation, not the normals
#endif
#endif
#else

surfaceData.baseColor = SAMPLE_UVMAPPING_TEXTURE2D(ADD_IDX(_BaseColorMap), ADD_ZERO_IDX(sampler_BaseColorMap), ADD_IDX(layerTexCoord.base)).rgb * ADD_IDX(_BaseColor).rgb;
#ifdef _DETAIL_MAP_IDX
// Goal: we want the detail albedo map to be able to darken down to black and brighten up to white the surface albedo.
// The scale control the speed of the gradient. We simply remap detailAlbedo from [0..1] to [-1..1] then perform a lerp to black or white
// with a factor based on speed.
// Goal: we want the detail albedo map to be able to darken down to black and brighten up to white the surface albedo.
// The scale control the speed of the gradient. We simply remap detailAlbedo from [0..1] to [-1..1] then perform a lerp to black or white
// with a factor based on speed.
float albedoDetailSpeed = saturate(abs(detailAlbedo) * ADD_IDX(_DetailAlbedoScale));
float3 baseColorOverlay = lerp(sqrt(surfaceData.baseColor), (detailAlbedo < 0.0) ? float3(0.0, 0.0, 0.0) : float3(1.0, 1.0, 1.0), albedoDetailSpeed * albedoDetailSpeed);
baseColorOverlay *= baseColorOverlay;
float albedoDetailSpeed = saturate(abs(detailAlbedo) * ADD_IDX(_DetailAlbedoScale));
float3 baseColorOverlay = lerp(sqrt(surfaceData.baseColor), (detailAlbedo < 0.0) ? float3(0.0, 0.0, 0.0) : float3(1.0, 1.0, 1.0), albedoDetailSpeed * albedoDetailSpeed);
baseColorOverlay *= baseColorOverlay;
// Lerp with details mask
surfaceData.baseColor = lerp(surfaceData.baseColor, saturate(baseColorOverlay), detailMask);
#endif

#ifdef _DETAIL_MAP_IDX
// See comment for baseColorOverlay
float smoothnessDetailSpeed = saturate(abs(detailSmoothness) * ADD_IDX(_DetailSmoothnessScale));
float smoothnessOverlay = lerp(surfaceData.perceptualSmoothness, (detailSmoothness < 0.0) ? 0.0 : 1.0, smoothnessDetailSpeed);
float smoothnessOverlay = lerp(surfaceData.perceptualSmoothness, (detailSmoothness < 0.0) ? 0.0 : 1.0, smoothnessDetailSpeed);
// Lerp with details mask
surfaceData.perceptualSmoothness = lerp(surfaceData.perceptualSmoothness, saturate(smoothnessOverlay), detailMask);
#endif

2
com.unity.render-pipelines.high-definition/HDRP/Material/Material.hlsl


#include "Unlit/Unlit.hlsl"
#elif defined(UNITY_MATERIAL_STACKLIT)
#include "StackLit/StackLit.hlsl"
#elif defined(UNITY_MATERIAL_FABRIC)
#include "Fabric/Fabric.hlsl"
#endif
//-----------------------------------------------------------------------------

40
com.unity.render-pipelines.high-definition/HDRP/Material/MaterialEvaluation.hlsl


float3 indirectSpecularOcclusion;
};
void GetScreenSpaceAmbientOcclusion(float2 positionSS, float NdotV, float perceptualRoughness, float ambientOcclusionFromData, float specularOcclusionFromData, out AmbientOcclusionFactor aoFactor)
// Get screen space ambient occlusion only:
float GetScreenSpaceDiffuseOcclusion(float2 positionSS)
// Ambient occlusion use for indirect lighting (reflection probe, baked diffuse lighting)
// Ambient occlusion use for indirect lighting (reflection probe, baked diffuse lighting)
// Ambient occlusion use for direct lighting (directional, punctual, area)
float directAmbientOcclusion = lerp(1.0, indirectAmbientOcclusion, _AmbientOcclusionParam.w);
float directAmbientOcclusion = 1.0;
return indirectAmbientOcclusion;
}
void GetScreenSpaceAmbientOcclusion(float2 positionSS, float NdotV, float perceptualRoughness, float ambientOcclusionFromData, float specularOcclusionFromData, out AmbientOcclusionFactor aoFactor)
{
float indirectAmbientOcclusion = GetScreenSpaceDiffuseOcclusion(positionSS);
float directAmbientOcclusion = lerp(1.0, indirectAmbientOcclusion, _AmbientOcclusionParam.w);
float roughness = PerceptualRoughnessToRoughness(perceptualRoughness);
float specularOcclusion = GetSpecularOcclusionFromAmbientOcclusion(ClampNdotV(NdotV), indirectAmbientOcclusion, roughness);

aoFactor.directAmbientOcclusion = lerp(_AmbientOcclusionParam.rgb, float3(1.0, 1.0, 1.0), directAmbientOcclusion);
}
// Use GTAOMultiBounce approximation for ambient occlusion (allow to get a tint from the diffuseColor)
// Use GTAOMultiBounce approximation for ambient occlusion (allow to get a tint from the diffuseColor)
// Note: When we ImageLoad outside of texture size, the value returned by Load is 0 (Note: On Metal maybe it clamp to value of texture which is also fine)
// We use this property to have a neutral value for AO that doesn't consume a sampler and work also with compute shader (i.e use ImageLoad)
// We store inverse AO so neutral is black. So either we sample inside or outside the texture it return 0 in case of neutral
// Ambient occlusion use for indirect lighting (reflection probe, baked diffuse lighting)
#ifndef _SURFACE_TYPE_TRANSPARENT
float indirectAmbientOcclusion = 1.0 - LOAD_TEXTURE2D(_AmbientOcclusionTexture, positionSS).x;
// Ambient occlusion use for direct lighting (directional, punctual, area)
float indirectAmbientOcclusion = GetScreenSpaceDiffuseOcclusion(positionSS);
#else
float indirectAmbientOcclusion = 1.0;
float directAmbientOcclusion = 1.0;
#endif
float roughness = PerceptualRoughnessToRoughness(perceptualRoughness);
float specularOcclusion = GetSpecularOcclusionFromAmbientOcclusion(ClampNdotV(NdotV), indirectAmbientOcclusion, roughness);

void ApplyAmbientOcclusionFactor(AmbientOcclusionFactor aoFactor, inout BuiltinData builtinData, inout AggregateLighting lighting)
{
// Note: in case of deferred Lit, builtinData.bakeDiffuseLighting contain indirect diffuse * surfaceData.ambientOcclusion + emissive,
// so emissive is affected by SSAO and we get a double darkening from SSAO and from AO which is incorrect but we accept the tradeoff
// Note: In case of deferred Lit, builtinData.bakeDiffuseLighting contains indirect diffuse * surfaceData.ambientOcclusion + emissive,
// so SSAO is multiplied by emissive which is wrong.
// Also, we have double occlusion for diffuse lighting since it already had precomputed AO (aka "FromData") applied
// (the * surfaceData.ambientOcclusion above)
// This is a tradeoff to avoid storing the precomputed (from data) AO in the GBuffer.
// (This is also why GetScreenSpaceAmbientOcclusion*() is effectively called with AOFromData = 1.0 in Lit:PostEvaluateBSDF() in the
// deferred case since DecodeFromGBuffer will init bsdfData.ambientOcclusion to 1.0 and we will only have SSAO in the aoFactor here)
builtinData.bakeDiffuseLighting *= aoFactor.indirectAmbientOcclusion;
lighting.indirect.specularReflected *= aoFactor.indirectSpecularOcclusion;
lighting.direct.diffuse *= aoFactor.directAmbientOcclusion;

12
com.unity.render-pipelines.high-definition/HDRP/Material/PreIntegratedFGD/PreIntegratedFGD.cs


public enum FGDIndex
{
FGD_GGXAndDisneyDiffuse = 0,
FGD_CharlieAndClothLambert = 1,
FGD_CharlieAndFabricLambert = 1,
Count = 2
}

m_PreIntegratedFGD[(int)index].Create();
break;
case FGDIndex.FGD_CharlieAndClothLambert:
m_PreIntegratedFGDMaterial[(int)index] = CoreUtils.CreateEngineMaterial(hdrp.renderPipelineResources.preIntegratedFGD_CharlieClothLambert);
case FGDIndex.FGD_CharlieAndFabricLambert:
m_PreIntegratedFGDMaterial[(int)index] = CoreUtils.CreateEngineMaterial(hdrp.renderPipelineResources.preIntegratedFGD_CharlieFabricLambert);
m_PreIntegratedFGD[(int)index].name = CoreUtils.GetRenderTargetAutoName(128, 128, 1, RenderTextureFormat.ARGB2101010, "preIntegratedFGD_CharlieClothLambert");
m_PreIntegratedFGD[(int)index].name = CoreUtils.GetRenderTargetAutoName(128, 128, 1, RenderTextureFormat.ARGB2101010, "preIntegratedFGD_CharlieFabricLambert");
m_PreIntegratedFGD[(int)index].Create();
break;

Shader.SetGlobalTexture(HDShaderIDs._PreIntegratedFGD_GGXDisneyDiffuse, m_PreIntegratedFGD[(int)index]);
break;
case FGDIndex.FGD_CharlieAndClothLambert:
Shader.SetGlobalTexture(HDShaderIDs._PreIntegratedFGD_CharlieAndCloth, m_PreIntegratedFGD[(int)index]);
case FGDIndex.FGD_CharlieAndFabricLambert:
Shader.SetGlobalTexture(HDShaderIDs._PreIntegratedFGD_CharlieAndFabric, m_PreIntegratedFGD[(int)index]);
break;
default:

10
com.unity.render-pipelines.high-definition/HDRP/Material/PreIntegratedFGD/PreIntegratedFGD.hlsl


reflectivity = preFGD.y;
}
TEXTURE2D(_PreIntegratedFGD_CharlieAndCloth);
TEXTURE2D(_PreIntegratedFGD_CharlieAndFabric);
void GetPreIntegratedFGDCharlieAndClothLambert(float NdotV, float perceptualRoughness, float3 fresnel0, out float3 CharlieSpecularFGD, out float clothLambertDiffuseFGD, out float reflectivity)
void GetPreIntegratedFGDCharlieAndFabricLambert(float NdotV, float perceptualRoughness, float3 fresnel0, out float3 CharlieSpecularFGD, out float fabricLambertDiffuseFGD, out float reflectivity)
float3 preFGD = SAMPLE_TEXTURE2D_LOD(_PreIntegratedFGD_CharlieAndCloth, s_linear_clamp_sampler, float2(NdotV, perceptualRoughness), 0).xyz;
float3 preFGD = SAMPLE_TEXTURE2D_LOD(_PreIntegratedFGD_CharlieAndFabric, s_linear_clamp_sampler, float2(NdotV, perceptualRoughness), 0).xyz;
// z = ClothLambert
clothLambertDiffuseFGD = preFGD.z;
// z = FabricLambert
fabricLambertDiffuseFGD = preFGD.z;
reflectivity = preFGD.y;
}

4
com.unity.render-pipelines.high-definition/HDRP/Material/PreIntegratedFGD/preIntegratedFGD_CharlieFabricLambert.shader


Shader "Hidden/HDRenderPipeline/preIntegratedFGD_CharlieClothLambert"
Shader "Hidden/HDRenderPipeline/preIntegratedFGD_CharlieFabricLambert"
{
SubShader
{

float3 N = float3(0.0, 0.0, 1.0);
// Pre integrate GGX with smithJoint visibility as well as DisneyDiffuse
float4 preFGD = IntegrateCharlieAndClothLambertFGD(V, N, PerceptualRoughnessToRoughness(perceptualRoughness));
float4 preFGD = IntegrateCharlieAndFabricLambertFGD(V, N, PerceptualRoughnessToRoughness(perceptualRoughness));
return float4(preFGD.xyz, 1.0);
}

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


{
CoreUtils.DisplayUnsupportedAPIMessage();
// Display more information to the users when it should have use Metal instead of OpenGL
if (SystemInfo.graphicsDeviceType.ToString().StartsWith("OpenGL"))
{
if (SystemInfo.operatingSystem.StartsWith("Mac"))
CoreUtils.DisplayUnsupportedMessage("Use Metal API instead.");
else if (SystemInfo.operatingSystem.StartsWith("Windows"))
CoreUtils.DisplayUnsupportedMessage("Use Vulkan API instead.");
}
return false;
}

}
// TODO: Render only visible probes
var isReflection = cameras.Any(c => c.cameraType == CameraType.Reflection);
if (!isReflection)
ReflectionSystem.RenderAllRealtimeProbes(ReflectionProbeType.PlanarReflection);
var probeTypeToRender = ReflectionProbeType.ReflectionProbe;
var isPlanarReflection = cameras.Any(c => c.cameraType == CameraType.Reflection);
if (isPlanarReflection)
probeTypeToRender |= ReflectionProbeType.PlanarReflection;
ReflectionSystem.RenderAllRealtimeProbes(probeTypeToRender);
// We first update the state of asset frame settings as they can be use by various camera
// but we keep the dirty state to correctly reset other camera that use RenderingPath.Default.

{
currentFrameSettings.enablePostprocess = false;
}
// Disable SSS if luxmeter is enabled
if (debugDisplaySettings.lightingDebugSettings.debugLightingMode == DebugLightingMode.LuxMeter)
{

{
VolumeManager.instance.Update(hdCamera.volumeAnchor, hdCamera.volumeLayerMask);
}
// Do anything we need to do upon a new frame.
// The NewFrame must be after the VolumeManager update and before Resize because it uses properties set in NewFrame
m_LightLoop.NewFrame(currentFrameSettings);

#endif
PushFullScreenDebugTexture(hdCamera, cmd, m_CameraColorBuffer, FullScreenDebugMode.ScreenSpaceTracing);
// Caution: RenderDebug need to take into account that we have flip the screen (so anything capture before the flip will be flipped)
RenderDebug(hdCamera, cmd);
RenderDebug(hdCamera, cmd, m_CullResults);
#if UNITY_EDITOR
// We need to make sure the viewport is correctly set for the editor rendering. It might have been changed by debug overlay rendering just before.

m_SkyManager.RenderSky(hdCamera, m_LightLoop.GetCurrentSunLight(), m_CameraColorBuffer, m_CameraDepthStencilBuffer, m_CurrentDebugDisplaySettings, cmd);
if (visualEnv.fogType != FogType.None)
if (visualEnv.fogType.value != FogType.None)
m_SkyManager.RenderOpaqueAtmosphericScattering(cmd);
}

public void ApplyDebugDisplaySettings(HDCamera hdCamera, CommandBuffer cmd)
{
// See ShaderPassForward.hlsl: for forward shaders, if DEBUG_DISPLAY is enabled and no DebugLightingMode or DebugMipMapMod
// modes have been set, lighting is automatically skipped (To avoid some crashed due to lighting RT not set on console).
// However debug mode like colorPickerModes and false color don't need DEBUG_DISPLAY and must work with the lighting.
// So we will enabled DEBUG_DISPLAY independently
// Enable globally the keyword DEBUG_DISPLAY on shader that support it with multicompile
CoreUtils.SetKeyword(cmd, "DEBUG_DISPLAY", m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled());
// enable globally the keyword DEBUG_DISPLAY on shader that support it with multicompile
cmd.EnableShaderKeyword("DEBUG_DISPLAY");
// This is for texture streaming
m_CurrentDebugDisplaySettings.UpdateMaterials();

// The DebugNeedsExposure test allows us to set a neutral value if exposure is not needed. This way we don't need to make various tests inside shaders but only in this function.
cmd.SetGlobalFloat(HDShaderIDs._DebugExposure, m_CurrentDebugDisplaySettings.DebugNeedsExposure() ? lightingDebugSettings.debugExposure : 0.0f);
}
else
{
// TODO: Be sure that if there is no change in the state of this keyword, it doesn't imply any work on CPU side! else we will need to save the sate somewher
cmd.DisableShaderKeyword("DEBUG_DISPLAY");
}
}
public void PushColorPickerDebugTexture(CommandBuffer cmd, RTHandleSystem.RTHandle textureID, HDCamera hdCamera)

}
}
void RenderDebug(HDCamera hdCamera, CommandBuffer cmd)
void RenderDebug(HDCamera hdCamera, CommandBuffer cmd, CullResults cullResults)
{
// We don't want any overlay for these kind of rendering
if (hdCamera.camera.cameraType == CameraType.Reflection || hdCamera.camera.cameraType == CameraType.Preview)

HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, hdCamera.actualWidth);
}
m_LightLoop.RenderDebugOverlay(hdCamera, cmd, m_CurrentDebugDisplaySettings, ref x, ref y, overlaySize, hdCamera.actualWidth);
m_LightLoop.RenderDebugOverlay(hdCamera, cmd, m_CurrentDebugDisplaySettings, ref x, ref y, overlaySize, hdCamera.actualWidth, cullResults);
DecalSystem.instance.RenderDebugOverlay(hdCamera, cmd, m_CurrentDebugDisplaySettings, ref x, ref y, overlaySize, hdCamera.actualWidth);

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


{
maxPlanarReflectionProbePerCamera = renderPipelineSettings.lightLoopSettings.planarReflectionProbeCacheSize,
maxActivePlanarReflectionProbe = 512,
planarReflectionProbeSize = (int)renderPipelineSettings.lightLoopSettings.planarReflectionTextureSize
planarReflectionProbeSize = (int)renderPipelineSettings.lightLoopSettings.planarReflectionTextureSize,
maxActiveReflectionProbe = 512,
reflectionProbeSize = (int)renderPipelineSettings.lightLoopSettings.reflectionCubemapSize
};
}
}

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


public static readonly int _NonJitteredViewProjMatrix = Shader.PropertyToID("_NonJitteredViewProjMatrix");
public static readonly int _ViewProjMatrix = Shader.PropertyToID("_ViewProjMatrix");
public static readonly int _InvViewProjMatrix = Shader.PropertyToID("_InvViewProjMatrix");
public static readonly int _DetViewMatrix = Shader.PropertyToID("_DetViewMatrix");
public static readonly int _ZBufferParams = Shader.PropertyToID("_ZBufferParams");
public static readonly int _ProjectionParams = Shader.PropertyToID("_ProjectionParams");
public static readonly int unity_OrthoParams = Shader.PropertyToID("unity_OrthoParams");

// Preintegrated texture name
public static readonly int _PreIntegratedFGD_GGXDisneyDiffuse = Shader.PropertyToID("_PreIntegratedFGD_GGXDisneyDiffuse");
public static readonly int _PreIntegratedFGD_CharlieAndCloth = Shader.PropertyToID("_PreIntegratedFGD_CharlieAndCloth");
public static readonly int _PreIntegratedFGD_CharlieAndFabric = Shader.PropertyToID("_PreIntegratedFGD_CharlieAndFabric");
}
}

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


MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0

version: 1
m_Version: 2
defaultDiffuseMaterial: {fileID: 2100000, guid: 73c176f402d2c2f4d929aa5da7585d17, type: 2}
defaultMirrorMaterial: {fileID: 2100000, guid: 6b17274157b33bc45b6a40e7d4ff51fe, type: 2}
defaultDecalMaterial: {fileID: 2100000, guid: 500e733574922d04ea961553b1b26a63, type: 2}

debugViewTilesShader: {fileID: 4800000, guid: c7c2bd17b06ceb4468e14081aaf1b96f, type: 3}
debugFullScreenShader: {fileID: 4800000, guid: e874aca2df8300a488258738c31f85cf, type: 3}
debugColorPickerShader: {fileID: 4800000, guid: 8137b807709e178498f22ed710864bb0, type: 3}
debugLightVolumeShader: {fileID: 4800000, guid: f62fc49f20e79e64ba43db3cfd447d80, type: 3}
deferredShader: {fileID: 4800000, guid: 00dd221e34a6ab349a1196b0f2fab693, type: 3}
colorPyramidCS: {fileID: 7200000, guid: 4e3267a1135742441a14298d8dcac04a, type: 3}
depthPyramidCS: {fileID: 7200000, guid: 64a553bb564274041906f78ffba955e4, type: 3}

skyboxCubemap: {fileID: 103, guid: 0000000000000000f000000000000000, type: 0}
gradientSky: {fileID: 4800000, guid: 2b5d4f1b26f03dc4a873b093e0c4adb1, type: 3}
preIntegratedFGD_GGXDisneyDiffuse: {fileID: 4800000, guid: 123f13d52852ef547b2962de4bd9eaad, type: 3}
preIntegratedFGD_CharlieClothLambert: {fileID: 4800000, guid: 3b3bf235775cf8b4baae7f3306787ab0, type: 3}
preIntegratedFGD_CharlieFabricLambert: {fileID: 4800000, guid: 3b3bf235775cf8b4baae7f3306787ab0, type: 3}
encodeBC6HCS: {fileID: 7200000, guid: aa922d239de60304f964e24488559eeb, type: 3}
cubeToPanoShader: {fileID: 4800000, guid: 595434cc3b6405246b6cd3086d0b6f7d, type: 3}
blitCubeTextureFace: {fileID: 4800000, guid: d850d0a2481878d4bbf17e5126b04163, type: 3}

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


{
public class RenderPipelineResources : ScriptableObject
{
const int currentVersion = 2;
const int currentVersion = 3;
[SerializeField]
[FormerlySerializedAs("version")]
int m_Version = 1;

public Shader debugViewTilesShader;
public Shader debugFullScreenShader;
public Shader debugColorPickerShader;
public Shader debugLightVolumeShader;
// Lighting resources
public Shader deferredShader;

// Material
public Shader preIntegratedFGD_GGXDisneyDiffuse;
public Shader preIntegratedFGD_CharlieClothLambert;
public Shader preIntegratedFGD_CharlieFabricLambert;
// Utilities / Core
public ComputeShader encodeBC6HCS;

debugViewTilesShader = Load<Shader>(HDRenderPipelinePath + "Debug/DebugViewTiles.Shader");
debugFullScreenShader = Load<Shader>(HDRenderPipelinePath + "Debug/DebugFullScreen.Shader");
debugColorPickerShader = Load<Shader>(HDRenderPipelinePath + "Debug/DebugColorPicker.Shader");
debugLightVolumeShader = Load<Shader>(HDRenderPipelinePath + "Debug/DebugLightVolume.Shader");
deferredShader = Load<Shader>(HDRenderPipelinePath + "Lighting/Deferred.Shader");
colorPyramidCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/ColorPyramid.compute");

// Material
preIntegratedFGD_GGXDisneyDiffuse = Load<Shader>(HDRenderPipelinePath + "Material/PreIntegratedFGD/PreIntegratedFGD_GGXDisneyDiffuse.shader");
preIntegratedFGD_CharlieClothLambert = Load<Shader>(HDRenderPipelinePath + "Material/PreIntegratedFGD/PreIntegratedFGD_CharlieClothLambert.shader");
preIntegratedFGD_CharlieFabricLambert = Load<Shader>(HDRenderPipelinePath + "Material/PreIntegratedFGD/PreIntegratedFGD_CharlieFabricLambert.shader");
// Utilities / Core
encodeBC6HCS = Load<ComputeShader>(CorePath + "CoreResources/EncodeBC6H.compute");

3
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/VaryingMesh.hlsl


#if defined(VARYINGS_NEED_CULLFACE) && SHADER_STAGE_FRAGMENT
output.isFrontFace = IS_FRONT_VFACE(input.cullFace, true, false);
// Handle handness of the view matrix (In Unity view matrix default to a determinant of -1)
// when we render a cubemap the view matrix handness is flipped (due to convention used for cubemap) we have a determinant of +1
output.isFrontFace = _DetViewMatrix < 0.0 ? output.isFrontFace : !output.isFrontFace;
#endif
return output;

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


#else
float3 _WorldSpaceCameraPos;
#endif
float _DetViewMatrix; // determinant(_ViewMatrix)
float4 _ScreenSize; // { w, h, 1 / w, 1 / h }
float4 _ScreenToTargetScale; // { w / RTHandle.maxWidth, h / RTHandle.maxHeight } : xy = currFrame, zw = prevFrame

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


and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [3.3.0-preview]
### Added
- UNITY_DECLARE_FRAMEBUFFER_INPUT and UNITY_READ_FRAMEBUFFER_INPUT macros were added. They are necessary for reading transient attachments.
- UNITY_MATRIX_I_VP is now defined.
### Changed
- Renamed LightweightForwardRenderer to ScriptableRenderer.
- Moved all light constants to _LightBuffer CBUFFER. Now _PerCamera CBUFFER contains all other per camera constants.
### Fixed
- Lightweight Unlit shader UI doesn't throw an error about missing receive shadow property anymore.
### Changed
- Change real-time attenuation to inverse square.

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


private DirectionalShadowsPass m_DirectionalShadowPass;
private LocalShadowsPass m_LocalShadowPass;
private SetupForwardRenderingPass m_SetupForwardRenderingPass;
private ScreenSpaceShadowResolvePass m_ScreenSpaceShadowResovePass;
private ScreenSpaceShadowResolvePass m_ScreenSpaceShadowResolvePass;
private CreateLightweightRenderTexturesPass m_CreateLightweightRenderTexturesPass;
private BeginXRRenderingPass m_BeginXrRenderingPass;
private SetupLightweightConstanstPass m_SetupLightweightConstants;

m_DirectionalShadowPass = new DirectionalShadowsPass();
m_LocalShadowPass = new LocalShadowsPass();
m_SetupForwardRenderingPass = new SetupForwardRenderingPass();
m_ScreenSpaceShadowResovePass = new ScreenSpaceShadowResolvePass();
m_ScreenSpaceShadowResolvePass = new ScreenSpaceShadowResolvePass();
m_CreateLightweightRenderTexturesPass = new CreateLightweightRenderTexturesPass();
m_BeginXrRenderingPass = new BeginXRRenderingPass();
m_SetupLightweightConstants = new SetupLightweightConstanstPass();

m_Initialized = true;
}
public void Setup(LightweightForwardRenderer renderer, ref ScriptableRenderContext context,
public void Setup(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults, ref RenderingData renderingData)
{
Init();

renderer.SetupPerObjectLightIndices(ref cullResults, ref renderingData.lightData);
RenderTextureDescriptor baseDescriptor = LightweightForwardRenderer.CreateRTDesc(ref renderingData.cameraData);
RenderTextureDescriptor baseDescriptor = ScriptableRenderer.CreateRTDesc(ref renderingData.cameraData);
RenderTextureDescriptor shadowDescriptor = baseDescriptor;
shadowDescriptor.dimension = TextureDimension.Tex2D;

(requiresCameraDepth &&
!LightweightForwardRenderer.CanCopyDepth(ref renderingData.cameraData));
!ScriptableRenderer.CanCopyDepth(ref renderingData.cameraData));
// For now VR requires a depth prepass until we figure out how to properly resolve texture2DMS in stereo
requiresDepthPrepass |= renderingData.cameraData.isStereoEnabled;

if (renderingData.shadowData.renderDirectionalShadows &&
renderingData.shadowData.requiresScreenSpaceShadowResolve)
{
m_ScreenSpaceShadowResovePass.Setup(baseDescriptor, ScreenSpaceShadowmap);
renderer.EnqueuePass(m_ScreenSpaceShadowResovePass);
m_ScreenSpaceShadowResolvePass.Setup(baseDescriptor, ScreenSpaceShadowmap);
renderer.EnqueuePass(m_ScreenSpaceShadowResolvePass);
LightweightForwardRenderer.RequiresIntermediateColorTexture(
ScriptableRenderer.RequiresIntermediateColorTexture(
ref renderingData.cameraData,
baseDescriptor,
requiresDepthAttachment);

Camera camera = renderingData.cameraData.camera;
bool dynamicBatching = renderingData.supportsDynamicBatching;
RendererConfiguration rendererConfiguration = LightweightForwardRenderer.GetRendererConfiguration(renderingData.lightData.totalAdditionalLightsCount);
RendererConfiguration rendererConfiguration = ScriptableRenderer.GetRendererConfiguration(renderingData.lightData.totalAdditionalLightsCount);
m_RenderOpaqueForwardPass.Setup(baseDescriptor, colorHandle, depthHandle, LightweightForwardRenderer.GetCameraClearFlag(camera), camera.backgroundColor, rendererConfiguration,dynamicBatching);
m_RenderOpaqueForwardPass.Setup(baseDescriptor, colorHandle, depthHandle, ScriptableRenderer.GetCameraClearFlag(camera), camera.backgroundColor, rendererConfiguration,dynamicBatching);
renderer.EnqueuePass(m_RenderOpaqueForwardPass);
if (renderingData.cameraData.postProcessEnabled &&

2
com.unity.render-pipelines.lightweight/LWRP/Editor/ShaderGUI/LightweightShaderGUI.cs


cullingProp = FindProperty("_Cull", properties);
alphaClipProp = FindProperty("_AlphaClip", properties);
alphaCutoffProp = FindProperty("_Cutoff", properties);
receiveShadowsProp = FindProperty("_ReceiveShadows", properties);
receiveShadowsProp = FindProperty("_ReceiveShadows", properties, false);
}
public virtual void ShaderPropertiesGUI(Material material)

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


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

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


{
public partial class LightweightPipeline : RenderPipeline
{
private static class PerFrameBuffer
static class PerFrameBuffer
}
static class PerCameraBuffer
{
// TODO: This needs to account for stereo rendering
public static int _InvCameraViewProj;
public static int _ScaledScreenParams;
}
public LightweightPipelineAsset pipelineAsset { get; private set; }

CameraComparer m_CameraComparer = new CameraComparer();
LightweightForwardRenderer m_Renderer;
ScriptableRenderer m_Renderer;
bool m_IsCameraRendering;
public LightweightPipeline(LightweightPipelineAsset asset)
{

PerFrameBuffer._GlossyEnvironmentColor = Shader.PropertyToID("_GlossyEnvironmentColor");
PerFrameBuffer._SubtractiveShadowColor = Shader.PropertyToID("_SubtractiveShadowColor");
SetupLightweightConstanstPass.PerCameraBuffer._ScaledScreenParams = Shader.PropertyToID("_ScaledScreenParams");
m_Renderer = new LightweightForwardRenderer(asset);
PerCameraBuffer._InvCameraViewProj = Shader.PropertyToID("_InvCameraViewProj");
PerCameraBuffer._ScaledScreenParams = Shader.PropertyToID("_ScaledScreenParams");
m_Renderer = new ScriptableRenderer(asset);
// Let engine know we have MSAA on for cases where we support MSAA backbuffer
if (QualitySettings.antiAliasing != pipelineAsset.msaaSampleCount)

m_IsCameraRendering = false;
Lightmapping.SetDelegate(lightsDelegate);
}

public override void Render(ScriptableRenderContext context, Camera[] cameras)
{
if (m_IsCameraRendering)
{
Debug.LogWarning("Nested camera rendering is forbidden. If you are calling camera.Render inside OnWillRenderObject callback, use BeginCameraRender callback instead.");
return;
}
pipelineAsset.savedXRGraphicsConfig.renderScale = pipelineAsset.renderScale;
pipelineAsset.savedXRGraphicsConfig.viewportScale = 1.0f; // Placeholder until viewportScale is all hooked up
// Apply any changes to XRGConfig prior to this point

foreach (Camera camera in cameras)
{
BeginCameraRendering(camera);
string renderCameraTag = "Render " + camera.name;
string renderCameraTag = camera.name;
CommandBuffer cmd = CommandBufferPool.Get(renderCameraTag);
using (new ProfilingSample(cmd, renderCameraTag))
{

cmd.Clear();
#if UNITY_EDITOR
try
// Emit scene view UI
if (cameraData.isSceneViewCamera)
ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
{
m_IsCameraRendering = true;
#if UNITY_EDITOR
// Emit scene view UI
if (cameraData.isSceneViewCamera)
ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
#endif
CullResults.Cull(ref cullingParameters, context, ref m_CullResults);
List<VisibleLight> visibleLights = m_CullResults.visibleLights;
CullResults.Cull(ref cullingParameters, context, ref m_CullResults);
List<VisibleLight> visibleLights = m_CullResults.visibleLights;
RenderingData renderingData;
InitializeRenderingData(ref cameraData, visibleLights,
m_Renderer.maxSupportedLocalLightsPerPass, m_Renderer.maxSupportedVertexLights,
out renderingData);
RenderingData renderingData;
InitializeRenderingData(ref cameraData, visibleLights,
m_Renderer.maxSupportedLocalLightsPerPass, m_Renderer.maxSupportedVertexLights,
out renderingData);
var setup = cameraData.camera.GetComponent<IRendererSetup>();
if (setup == null)
setup = defaultRendererSetup;
var setup = cameraData.camera.GetComponent<IRendererSetup>();
if (setup == null)
setup = defaultRendererSetup;
setup.Setup(m_Renderer, ref context, ref m_CullResults, ref renderingData);
setup.Setup(m_Renderer, ref context, ref m_CullResults, ref renderingData);
m_Renderer.Execute(ref context, ref m_CullResults, ref renderingData);
}
#if UNITY_EDITOR
catch (Exception)
{
CommandBufferPool.Release(cmd);
throw;
}
finally
#endif
{
m_IsCameraRendering = false;
}
m_Renderer.Execute(ref context, ref m_CullResults, ref renderingData);
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);

void SetupPerCameraShaderConstants(CameraData cameraData)
{
Camera camera = cameraData.camera;
Shader.SetGlobalVector(SetupLightweightConstanstPass.PerCameraBuffer._ScaledScreenParams, new Vector4(cameraWidth, cameraHeight, 1.0f + 1.0f / cameraWidth, 1.0f + 1.0f / cameraHeight));
Shader.SetGlobalVector(PerCameraBuffer._ScaledScreenParams, new Vector4(cameraWidth, cameraHeight, 1.0f + 1.0f / cameraWidth, 1.0f + 1.0f / cameraHeight));
Matrix4x4 projMatrix = GL.GetGPUProjectionMatrix(camera.projectionMatrix, false);
Matrix4x4 viewMatrix = camera.worldToCameraMatrix;
Matrix4x4 viewProjMatrix = projMatrix * viewMatrix;
Matrix4x4 invViewProjMatrix = Matrix4x4.Inverse(viewProjMatrix);
Shader.SetGlobalMatrix(PerCameraBuffer._InvCameraViewProj, invViewProjMatrix);
}
public static bool LightDataGIExtract(Light light, ref LightDataGI lightData)

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


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

}
}
}

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


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

float opaqueScaler = m_OpaqueScalerValues[(int)downsampling];
RenderTextureDescriptor opaqueDesc = LightweightForwardRenderer.CreateRTDesc(ref renderingData.cameraData, opaqueScaler);
RenderTextureDescriptor opaqueDesc = ScriptableRenderer.CreateRTDesc(ref renderingData.cameraData, opaqueScaler);
RenderTargetIdentifier colorRT = source.Identifier();
RenderTargetIdentifier opaqueColorRT = destination.Identifier();

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


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

Material depthCopyMaterial = renderer.GetMaterial(MaterialHandles.DepthCopy);
RenderTextureDescriptor descriptor = LightweightForwardRenderer.CreateRTDesc(ref renderingData.cameraData);
RenderTextureDescriptor descriptor = ScriptableRenderer.CreateRTDesc(ref renderingData.cameraData);
descriptor.colorFormat = RenderTextureFormat.Depth;
descriptor.depthBufferBits = 32; //TODO: fix this ;
descriptor.msaaSamples = 1;

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


descriptor = baseDescriptor;
}
public override void Execute(LightweightForwardRenderer renderer, ref ScriptableRenderContext context,
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
{

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


};
}
public override void Execute(LightweightForwardRenderer renderer, ref ScriptableRenderContext context,
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
{

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


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

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


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

}
}

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


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

}
}
}
}

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


this.descriptor = baseDescriptor;
}
public override void Execute(LightweightForwardRenderer renderer, ref ScriptableRenderContext context,
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
{

2
com.unity.render-pipelines.lightweight/LWRP/Passes/LightweightForwardPass.cs


}
[Conditional("DEVELOPMENT_BUILD"), Conditional("UNITY_EDITOR")]
protected void RenderObjectsWithError(LightweightForwardRenderer renderer, ref ScriptableRenderContext context, ref CullResults cullResults, Camera camera, FilterRenderersSettings filterSettings, SortFlags sortFlags)
protected void RenderObjectsWithError(ScriptableRenderer renderer, ref ScriptableRenderContext context, ref CullResults cullResults, Camera camera, FilterRenderersSettings filterSettings, SortFlags sortFlags)
{
Material errorMaterial = renderer.GetMaterial(MaterialHandles.Error);
if (errorMaterial != null)

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


}
}
public override void Execute(LightweightForwardRenderer renderer, ref ScriptableRenderContext context,
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
{

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


descriptor = baseDescriptor;
}
public override void Execute(LightweightForwardRenderer renderer, ref ScriptableRenderContext context,
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
{

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


};
}
public override void Execute(LightweightForwardRenderer renderer, ref ScriptableRenderContext context,
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
{

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


};
}
public override void Execute(LightweightForwardRenderer renderer, ref ScriptableRenderContext context,
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
{

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


this.source = source;
}
public override void Execute(LightweightForwardRenderer renderer, ref ScriptableRenderContext context,
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
{

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


descriptor = baseDescriptor;
}
public override void Execute(LightweightForwardRenderer renderer, ref ScriptableRenderContext context,
public override void Execute(ScriptableRenderer renderer, ref ScriptableRenderContext context,
ref CullResults cullResults,
ref RenderingData renderingData)
{

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


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

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


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

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

正在加载...
取消
保存