浏览代码

Merge branch 'master' into LightUnits

/main
sebastienlagarde 6 年前
当前提交
7934a87a
共有 54 个文件被更改,包括 513 次插入659 次删除
  1. 4
      com.unity.render-pipelines.core/CoreRP/Editor/com.unity.render-pipelines.core.Editor.asmdef
  2. 16
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Common.hlsl
  3. 15
      com.unity.render-pipelines.core/CoreRP/Utilities/CoreUtils.cs
  4. 3
      com.unity.render-pipelines.core/CoreRP/com.unity.render-pipelines.core.Runtime.asmdef
  5. 5
      com.unity.render-pipelines.core/package.json
  6. 6
      com.unity.render-pipelines.high-definition/CHANGELOG.md
  7. 2
      com.unity.render-pipelines.high-definition/HDRP/Camera/HDCamera.cs
  8. 8
      com.unity.render-pipelines.high-definition/HDRP/Editor/BuildProcessors/HDRPreprocessShaders.cs
  9. 24
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Volumetric/DensityVolumeEditor.cs
  10. 21
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Volumetric/Texture3DCreationEditor.cs
  11. 7
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/LitShaderPreprocessor.cs
  12. 5
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/RenderPipelineSettingsUI.cs
  13. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedFrameSettings.cs
  14. 40
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedRenderPipelineSettings.cs
  15. 20
      com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/AtmosphericScattering/VolumetricFogEditor.cs
  16. 13
      com.unity.render-pipelines.high-definition/HDRP/HDRenderPipelineAsset.asset
  17. 18
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightDefinition.cs
  18. 254
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightDefinition.cs.hlsl
  19. 18
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightEvaluation.hlsl
  20. 36
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoop.cs
  21. 2
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoopDef.hlsl
  22. 8
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/VolumeProjection.hlsl
  23. 13
      com.unity.render-pipelines.high-definition/HDRP/Lighting/SphericalHarmonics.cs
  24. 2
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/DensityVolume.cs
  25. 21
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumeTextureAtlas.cs
  26. 133
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumeVoxelization.compute
  27. 81
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumetricLighting.compute
  28. 126
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumetricLighting.cs
  29. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs
  30. 28
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs.hlsl
  31. 20
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.hlsl
  32. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitReference.hlsl
  33. 46
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.hlsl
  34. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.compute
  35. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs
  36. 10
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDRenderPipeline.cs
  37. 15
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDUtils.cs
  38. 12
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/Settings/FrameSettings.cs
  39. 5
      com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/Settings/RenderPipelineSettings.cs
  40. 6
      com.unity.render-pipelines.high-definition/HDRP/ShaderConfig.cs
  41. 1
      com.unity.render-pipelines.high-definition/HDRP/ShaderConfig.cs.hlsl
  42. 2
      com.unity.render-pipelines.high-definition/HDRP/Sky/AtmosphericScattering/AtmosphericScattering.cs
  43. 4
      com.unity.render-pipelines.high-definition/HDRP/Sky/AtmosphericScattering/AtmosphericScattering.hlsl
  44. 22
      com.unity.render-pipelines.high-definition/HDRP/Sky/AtmosphericScattering/VolumetricFog.cs
  45. 2
      com.unity.render-pipelines.lightweight/CHANGELOG.md
  46. 11
      com.unity.render-pipelines.lightweight/LWRP/LightweightPipeline.cs
  47. 2
      com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Terrain/InputSurfaceGrass.hlsl
  48. 7
      com.unity.shadergraph/CHANGELOG.md
  49. 4
      com.unity.shadergraph/Editor/Data/Graphs/Vector1MaterialSlot.cs
  50. 4
      com.unity.shadergraph/Editor/Data/Graphs/Vector2MaterialSlot.cs
  51. 1
      com.unity.shadergraph/Editor/Data/Graphs/Vector3MaterialSlot.cs
  52. 3
      com.unity.shadergraph/.data/sphereMask.PNG
  53. 39
      com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/SphereMaskNode.cs
  54. 11
      com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/SphereMaskNode.cs.meta

4
com.unity.render-pipelines.core/CoreRP/Editor/com.unity.render-pipelines.core.Editor.asmdef


{
"name": "com.unity.render-pipelines.core.Editor",
"references": [
"com.unity.render-pipelines.core.Runtime",
"com.unity.postprocessing.Runtime",
"com.unity.postprocessing.Editor"
"com.unity.render-pipelines.core.Runtime"
],
"optionalUnityReferences": [],
"includePlatforms": [

16
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Common.hlsl


{
data ^= 1u << offset;
}
#ifndef INTRINSIC_WAVEREADFIRSTLANE
// Warning: for correctness, the argument's value must be the same across all lanes of the wave.

return ComputeTextureLOD(uv);
}
float ComputeTextureLOD(float3 Px, float3 Py, float3 Pz)
// LOD clamp is optional and happens outside the function.
float ComputeTextureLOD(float3 duvw_dx, float3 duvw_dy, float3 duvw_dz, float scale)
float d = max(dot(Px, Px), max(dot(Py, Py), dot(Pz, Pz)));
return max(0.0, 0.5 * log2(d));
float d = Max3(dot(duvw_dx, duvw_dx), dot(duvw_dy, duvw_dy), dot(duvw_dz, duvw_dz));
return 0.5 * log2(d * (scale * scale));
}

{
real dp3 = max(REAL_MIN, dot(inVec, inVec));
return inVec * rsqrt(dp3);
}
// Division which returns 1 for (inf/inf) and (0/0).
// If any of the input parameters are NaNs, the result is a NaN.
real SafeDiv(real numer, real denom)
{
return (numer != denom) ? numer / denom : 1;
}
// Generates a triangle in homogeneous clip space, s.t.

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


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

// we pass the first color target as the depth target. If it has 0 depth bits,
// no depth target ends up being bound.
DrawFullScreen(commandBuffer, material, colorBuffers, colorBuffers[0], properties, shaderPassId);
}
// Post-processing misc
public static bool IsPostProcessingActive(PostProcessLayer layer)
{
return layer != null
&& layer.enabled;
}
public static bool IsTemporalAntialiasingActive(PostProcessLayer layer)
{
return IsPostProcessingActive(layer)
&& layer.antialiasingMode == PostProcessLayer.Antialiasing.TemporalAntialiasing
&& layer.temporalAntialiasing.IsSupported();
}
// Color space utilities

3
com.unity.render-pipelines.core/CoreRP/com.unity.render-pipelines.core.Runtime.asmdef


{
"name": "com.unity.render-pipelines.core.Runtime",
"references": [
"com.unity.postprocessing.Runtime"
],
"optionalUnityReferences": [],
"includePlatforms": [],
"excludePlatforms": [],

5
com.unity.render-pipelines.core/package.json


"description": "Core library for Unity render pipelines.",
"version": "3.0.0-preview",
"unity": "2018.2",
"displayName": "Render Pipeline Core Library",
"dependencies": {
"com.unity.postprocessing": "2.0.7-preview"
}
"displayName": "Render Pipeline Core Library"
}

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


- Add PCSS shadow filter support (from SRP Core)
- Exposed shadow budget parameters in HDRP asset
- Add an option to generate an emissive mesh for area lights (currently rectangle light only). The mesh fits the size, intensity and color of the light.
- Add an option to the HDRP asset to increase the resolution of volumetric lighting.
### Changed
- Re-enable shadow mask mode in debug view

- Rename positionWS to positionRWS (Camera relative world position) at a lot of places (mainly in interpolator and FragInputs). In case of custom shader user will be required to update their code.
- Rename positionWS to positionRWS (Camera relative world position) at a lot of places (mainly in interpolator and FragInputs). In case of custom shader user will be required to update their code.
- Rename positionWS, capturePositionWS, proxyPositionWS, influencePositionWS to positionRWS, capturePositionRWS, proxyPositionRWS, influencePositionRWS (Camera relative world position) in LightDefinition struct.
- Improve the quality of trilinear filtering of density volume textures.
- Fix issue with forward opaque lit shader variant being removed by the shader preprocessor
## [2.0.4-preview]

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


// If TAA is enabled projMatrix will hold a jittered projection matrix. The original,
// non-jittered projection matrix can be accessed via nonJitteredProjMatrix.
bool taaEnabled = camera.cameraType == CameraType.Game &&
CoreUtils.IsTemporalAntialiasingActive(postProcessLayer) &&
HDUtils.IsTemporalAntialiasingActive(postProcessLayer) &&
m_frameSettings.enablePostprocess;
var nonJitteredCameraProj = camera.projectionMatrix;

8
com.unity.render-pipelines.high-definition/HDRP/Editor/BuildProcessors/HDRPreprocessShaders.cs


int inputShaderVariantCount = inputData.Count;
ShaderCompilerData workaround = inputData[0];
for (int i = 0; i < inputData.Count; ++i)
{
ShaderCompilerData input = inputData[i];

i--;
}
}
// Currently if a certain snippet is completely stripped (for example if you remove a whole pass) other passes might get broken
// To work around that, we make sure that we always have at least one variant.
// TODO: Remove this one it is fixed
if (inputData.Count == 0)
inputData.Add(workaround);
}
}
}

24
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Volumetric/DensityVolumeEditor.cs


[CustomEditor(typeof(DensityVolume))]
class DensityVolumeEditor : Editor
{
private static GUIContent albedoLabel = new GUIContent("Scattering Color");
private static GUIContent meanFreePathLabel = new GUIContent("Mean Free Path");
private static GUIContent volumeTextureLabel = new GUIContent("Volume Texture Mask");
private static GUIContent textureScrollLabel = new GUIContent("Texture Scroll Speed");
private static GUIContent textureTileLabel = new GUIContent("Texture Tiling Amount");
private static GUIContent textureSettingsTitle = new GUIContent("Volume Texture Settings");
static GUIContent s_AlbedoLabel = new GUIContent("Single Scattering Albedo", "Hue and saturation control the color of the fog (the wavelength of in-scattered light). Value controls scattering (0 = max absorption & no scattering, 1 = no absorption & max scattering).");
static GUIContent s_MeanFreePathLabel = new GUIContent("Mean Free Path", "Controls the density, which determines how far you can seen through the fog. It's the distance in meters at which 50% of background light is lost in the fog (due to absorption and out-scattering).");
static GUIContent s_VolumeTextureLabel = new GUIContent("Density Mask Texture");
static GUIContent s_TextureScrollLabel = new GUIContent("Texture Scroll Speed");
static GUIContent s_TextureTileLabel = new GUIContent("Texture Tiling Amount");
static GUIContent s_TextureSettingsTitle = new GUIContent("Volume Texture Settings");
private bool showTextureParams = false;

public override void OnInspectorGUI()
{
albedo.colorValue = EditorGUILayout.ColorField(albedoLabel, albedo.colorValue, true, false, false);
EditorGUILayout.PropertyField(meanFreePath, meanFreePathLabel);
albedo.colorValue = EditorGUILayout.ColorField(s_AlbedoLabel, albedo.colorValue, true, false, false);
EditorGUILayout.PropertyField(meanFreePath, s_MeanFreePathLabel);
showTextureParams = EditorGUILayout.Foldout(showTextureParams, textureSettingsTitle, true);
showTextureParams = EditorGUILayout.Foldout(showTextureParams, s_TextureSettingsTitle, true);
EditorGUILayout.PropertyField(volumeTexture, volumeTextureLabel);
EditorGUILayout.PropertyField(textureScroll, textureScrollLabel);
EditorGUILayout.PropertyField(textureTile, textureTileLabel);
EditorGUILayout.PropertyField(volumeTexture, s_VolumeTextureLabel);
EditorGUILayout.PropertyField(textureScroll, s_TextureScrollLabel);
EditorGUILayout.PropertyField(textureTile, s_TextureTileLabel);
EditorGUI.indentLevel--;
}

21
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Volumetric/Texture3DCreationEditor.cs


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///
/// MIT License ///
/// ///
/// Copyright (c) 2016 Rapha�l Ernaelsten (@RaphErnaelsten) ///
/// ///
/// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), ///
/// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, ///
/// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: ///
/// ///
/// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ///
/// ///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ///
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ///
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS ///
/// IN THE SOFTWARE. ///
/// ///
/// PLEASE CONSIDER CREDITING AURA IN YOUR PROJECTS. IF RELEVANT, USE THE UNMODIFIED LOGO PROVIDED IN THE "LICENSE" FOLDER. ///
/// ///
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using UnityEngine;
using System.Collections.Generic;

7
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/LitShaderPreprocessor.cs


return true;
}
if (!hdrpAsset.renderPipelineSettings.supportOnlyForward)
// TODO: add an option to say we are using only the deferred shader variant (for Lit)
//if (0)
if (isForwardPass && !inputData.shaderKeywordSet.IsEnabled(m_DebugDisplay))
return true;
//if (isForwardPass && !inputData.shaderKeywordSet.IsEnabled(m_DebugDisplay))
// return true;
}
}

5
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/RenderPipelineSettingsUI.cs


EditorGUILayout.PropertyField(d.supportOnlyForward, _.GetContent("Support Only Forward|Remove all the memory and shader variant of GBuffer. The renderer can be switch to deferred anymore."));
EditorGUILayout.PropertyField(d.supportMotionVectors, _.GetContent("Support Motion Vectors|Motion vector are use for Motion Blur, TAA, temporal re-projection of various effect like SSR."));
EditorGUILayout.PropertyField(d.supportStereo, _.GetContent("Support Stereo Rendering"));
EditorGUILayout.PropertyField(d.enableUltraQualitySSS, _.GetContent("Increase SSS Sample Count|This allow better SSS quality. Warning: Slow feature, don't use for game."));
EditorGUILayout.PropertyField(d.supportVolumetric, _.GetContent("Support volumetric|Enable memory and shader variant for volumetric."));
EditorGUILayout.PropertyField(d.increaseSssSampleCount, _.GetContent("Increase SSS Sample Count|This allows for better SSS quality. Warning: high performance cost, do not enable on consoles."));
EditorGUILayout.PropertyField(d.supportVolumetrics, _.GetContent("Support volumetrics|Enable memory and shader variant for volumetric."));
EditorGUILayout.PropertyField(d.increaseResolutionOfVolumetrics, _.GetContent("Increase resolution of volumetrics|Increase the resolution of volumetric lighting buffers. Warning: high performance cost, do not enable on consoles."));
EditorGUILayout.PropertyField(d.supportRuntimeDebugDisplay, _.GetContent("Support runtime debug display|Remove all debug display shader variant only in the player. Allow faster build."));
EditorGUILayout.PropertyField(d.supportDitheringCrossFade, _.GetContent("Support dithering cross fade|Remove all dithering cross fade shader variant only in the player. Allow faster build."));

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


enableSubsurfaceScattering = root.Find((FrameSettings d) => d.enableSubsurfaceScattering);
enableTransmission = root.Find((FrameSettings d) => d.enableTransmission);
enableAtmosphericScattering = root.Find((FrameSettings d) => d.enableAtmosphericScattering);
enableVolumetric = root.Find((FrameSettings d) => d.enableVolumetric);
enableVolumetric = root.Find((FrameSettings d) => d.enableVolumetrics);
diffuseGlobalDimmer = root.Find((FrameSettings d) => d.diffuseGlobalDimmer);
specularGlobalDimmer = root.Find((FrameSettings d) => d.specularGlobalDimmer);
enableForwardRenderingOnly = root.Find((FrameSettings d) => d.enableForwardRenderingOnly);

40
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedRenderPipelineSettings.cs


public SerializedProperty supportOnlyForward;
public SerializedProperty supportMotionVectors;
public SerializedProperty supportStereo;
public SerializedProperty enableUltraQualitySSS;
public SerializedProperty supportVolumetric;
[UnityEngine.Serialization.FormerlySerializedAs("enableUltraQualitySSS")]
public SerializedProperty increaseSssSampleCount;
[UnityEngine.Serialization.FormerlySerializedAs("supportVolumetric")]
public SerializedProperty supportVolumetrics;
public SerializedProperty increaseResolutionOfVolumetrics;
public SerializedProperty supportRuntimeDebugDisplay;
public SerializedProperty supportDitheringCrossFade;

{
this.root = root;
supportShadowMask = root.Find((RenderPipelineSettings s) => s.supportShadowMask);
supportSSR = root.Find((RenderPipelineSettings s) => s.supportSSR);
supportSSAO = root.Find((RenderPipelineSettings s) => s.supportSSAO);
supportDBuffer = root.Find((RenderPipelineSettings s) => s.supportDBuffer);
supportMSAA = root.Find((RenderPipelineSettings s) => s.supportMSAA);
MSAASampleCount = root.Find((RenderPipelineSettings s) => s.msaaSampleCount);
supportSubsurfaceScattering = root.Find((RenderPipelineSettings s) => s.supportSubsurfaceScattering);
supportOnlyForward = root.Find((RenderPipelineSettings s) => s.supportOnlyForward);
supportMotionVectors = root.Find((RenderPipelineSettings s) => s.supportMotionVectors);
supportStereo = root.Find((RenderPipelineSettings s) => s.supportStereo);
enableUltraQualitySSS = root.Find((RenderPipelineSettings s) => s.enableUltraQualitySSS);
supportVolumetric = root.Find((RenderPipelineSettings s) => s.supportVolumetric);
supportRuntimeDebugDisplay = root.Find((RenderPipelineSettings s) => s.supportRuntimeDebugDisplay);
supportDitheringCrossFade = root.Find((RenderPipelineSettings s) => s.supportDitheringCrossFade);
supportShadowMask = root.Find((RenderPipelineSettings s) => s.supportShadowMask);
supportSSR = root.Find((RenderPipelineSettings s) => s.supportSSR);
supportSSAO = root.Find((RenderPipelineSettings s) => s.supportSSAO);
supportDBuffer = root.Find((RenderPipelineSettings s) => s.supportDBuffer);
supportMSAA = root.Find((RenderPipelineSettings s) => s.supportMSAA);
MSAASampleCount = root.Find((RenderPipelineSettings s) => s.msaaSampleCount);
supportSubsurfaceScattering = root.Find((RenderPipelineSettings s) => s.supportSubsurfaceScattering);
supportOnlyForward = root.Find((RenderPipelineSettings s) => s.supportOnlyForward);
supportMotionVectors = root.Find((RenderPipelineSettings s) => s.supportMotionVectors);
supportStereo = root.Find((RenderPipelineSettings s) => s.supportStereo);
increaseSssSampleCount = root.Find((RenderPipelineSettings s) => s.increaseSssSampleCount);
supportVolumetrics = root.Find((RenderPipelineSettings s) => s.supportVolumetrics);
increaseResolutionOfVolumetrics = root.Find((RenderPipelineSettings s) => s.increaseResolutionOfVolumetrics);
supportRuntimeDebugDisplay = root.Find((RenderPipelineSettings s) => s.supportRuntimeDebugDisplay);
supportDitheringCrossFade = root.Find((RenderPipelineSettings s) => s.supportDitheringCrossFade);
shadowInitParams = new SerializedShadowInitParameters(root.Find((RenderPipelineSettings s) => s.shadowInitParams));
decalSettings = new SerializedGlobalDecalSettings(root.Find((RenderPipelineSettings s) => s.decalSettings));
shadowInitParams = new SerializedShadowInitParameters(root.Find((RenderPipelineSettings s) => s.shadowInitParams));
decalSettings = new SerializedGlobalDecalSettings(root.Find((RenderPipelineSettings s) => s.decalSettings));
}
}
}

20
com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/AtmosphericScattering/VolumetricFogEditor.cs


private SerializedDataParameter m_Albedo;
private SerializedDataParameter m_MeanFreePath;
private SerializedDataParameter m_Anisotropy;
private SerializedDataParameter m_GlobalLightProbeDimmer;
static GUIContent s_AlbedoLabel = new GUIContent("Single Scattering Albedo", "Hue and saturation control the color of the fog (the wavelength of in-scattered light). Value controls scattering (0 = max absorption & no scattering, 1 = no absorption & max scattering).");
static GUIContent s_MeanFreePathLabel = new GUIContent("Mean Free Path", "Controls the density, which determines how far you can seen through the fog. It's the distance in meters at which 50% of background light is lost in the fog (due to absorption and out-scattering).");
static GUIContent s_AnisotropyLabel = new GUIContent("Anisotropy", "Controls the angular distribution of scattered light. 0 is isotropic, 1 is forward scattering, -1 is backward scattering.");
static GUIContent s_GlobalLightProbeDimmerLabel = new GUIContent("Global Light Probe Dimmer", "Reduces the intensity of the global light probe.");
public override void OnEnable()
{

m_Albedo = Unpack(o.Find(x => x.albedo));
m_MeanFreePath = Unpack(o.Find(x => x.meanFreePath));
m_Anisotropy = Unpack(o.Find(x => x.anisotropy));
m_Albedo = Unpack(o.Find(x => x.albedo));
m_MeanFreePath = Unpack(o.Find(x => x.meanFreePath));
m_Anisotropy = Unpack(o.Find(x => x.anisotropy));
m_GlobalLightProbeDimmer = Unpack(o.Find(x => x.globalLightProbeDimmer));
PropertyField(m_Albedo);
PropertyField(m_MeanFreePath);
PropertyField(m_Anisotropy);
PropertyField(m_Albedo, s_AlbedoLabel);
PropertyField(m_MeanFreePath, s_MeanFreePathLabel);
PropertyField(m_Anisotropy, s_AnisotropyLabel);
PropertyField(m_GlobalLightProbeDimmer, s_GlobalLightProbeDimmerLabel);
}
}
}

13
com.unity.render-pipelines.high-definition/HDRP/HDRenderPipelineAsset.asset


m_Name: HDRenderPipelineAsset
m_EditorClassIdentifier:
version: 1
m_RenderPipelineResources: {fileID: 11400000, guid: 3ce144cff5783da45aa5d4fdc2da14b7,
type: 2}
m_RenderPipelineResources: {fileID: 11400000, guid: 3ce144cff5783da45aa5d4fdc2da14b7, type: 2}
m_FrameSettings:
enableShadow: 1
enableContactShadows: 1

enableTransmission: 1
enableAtmosphericScattering: 1
enableVolumetric: 1
enableVolumetrics: 1
diffuseGlobalDimmer: 1
specularGlobalDimmer: 1
enableForwardRenderingOnly: 0

supportSSAO: 1
supportSubsurfaceScattering: 1
supportOnlyForward: 0
enableUltraQualitySSS: 0
supportVolumetric: 1
increaseSssSampleCount: 0
supportVolumetrics: 1
increaseResolutionOfVolumetrics: 0
supportRuntimeDebugDisplay: 1
supportDitheringCrossFade: 1
supportDBuffer: 1

atlasWidth: 4096
atlasHeight: 4096
allowShaderVariantStripping: 1
diffusionProfileSettings: {fileID: 11400000, guid: 404820c4cf36ad944862fa59c56064f0,
type: 2}
diffusionProfileSettings: {fileID: 11400000, guid: 404820c4cf36ad944862fa59c56064f0, type: 2}

18
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightDefinition.cs


};
// These structures share between C# and hlsl need to be align on float4, so we pad them.
[GenerateHLSL]
[GenerateHLSL(PackingRules.Exact, false)]
public Vector3 positionWS;
public Vector3 positionRWS;
public Vector3 color;
public int cookieIndex; // -1 if unused
public float volumetricDimmer;

public float specularScale;
};
[GenerateHLSL]
[GenerateHLSL(PackingRules.Exact, false)]
public Vector3 positionWS;
public Vector3 positionRWS;
public Vector3 color;
public float rangeAttenuationScale;
public float rangeAttenuationBias;

public float shadowDimmer;
public Vector4 shadowMaskSelector; // Use with ShadowMask feature
public int nonLightmappedOnly; // Use with ShadowMask feature // TODO: make it a bool
public int nonLightmappedOnly; // Use with ShadowMask feature // TODO: make it a bool
public float minRoughness; // This is use to give a small "area" to punctual light, as if we have a light with a radius.
public float diffuseScale;
public float specularScale;

// It allow to have more coherence for the dynamic if in shader code.
// Users can also chose to not have any projection, in this case we use the property minProjectionDistance to minimize code change. minProjectionDistance is set to huge number
// that simulate effect of no shape projection
[GenerateHLSL]
[GenerateHLSL(PackingRules.Exact, false)]
public Vector3 capturePositionWS;
public Vector3 capturePositionRWS;
public EnvShapeType influenceShapeType;
// Box: extents = box extents

public float minProjectionDistance;
public Vector3 proxyPositionWS;
public Vector3 proxyPositionRWS;
public Vector3 influencePositionWS;
public Vector3 influencePositionRWS;
public Vector3 influenceForward;
public Vector3 influenceUp;
public Vector3 influenceRight;

254
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightDefinition.cs.hlsl


// PackingRules = Exact
struct DirectionalLightData
{
float3 positionWS;
float3 positionRWS;
float3 color;
int cookieIndex;
float volumetricDimmer;

// PackingRules = Exact
struct LightData
{
float3 positionWS;
float3 positionRWS;
float3 color;
float rangeAttenuationScale;
float rangeAttenuationBias;

// PackingRules = Exact
struct EnvLightData
{
float3 capturePositionWS;
float3 capturePositionRWS;
float3 proxyPositionWS;
float3 proxyPositionRWS;
float3 influencePositionWS;
float3 influencePositionRWS;
float3 influenceForward;
float3 influenceUp;
float3 influenceRight;

float multiplier;
int envIndex;
};
//
// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.DirectionalLightData
//
float3 GetPositionWS(DirectionalLightData value)
{
return value.positionWS;
}
float3 GetColor(DirectionalLightData value)
{
return value.color;
}
int GetCookieIndex(DirectionalLightData value)
{
return value.cookieIndex;
}
float GetVolumetricDimmer(DirectionalLightData value)
{
return value.volumetricDimmer;
}
float3 GetRight(DirectionalLightData value)
{
return value.right;
}
float3 GetUp(DirectionalLightData value)
{
return value.up;
}
float3 GetForward(DirectionalLightData value)
{
return value.forward;
}
int GetTileCookie(DirectionalLightData value)
{
return value.tileCookie;
}
int GetShadowIndex(DirectionalLightData value)
{
return value.shadowIndex;
}
int GetContactShadowIndex(DirectionalLightData value)
{
return value.contactShadowIndex;
}
float4 GetShadowMaskSelector(DirectionalLightData value)
{
return value.shadowMaskSelector;
}
int GetNonLightmappedOnly(DirectionalLightData value)
{
return value.nonLightmappedOnly;
}
float GetDiffuseScale(DirectionalLightData value)
{
return value.diffuseScale;
}
float GetSpecularScale(DirectionalLightData value)
{
return value.specularScale;
}
//
// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.LightData
//
float3 GetPositionWS(LightData value)
{
return value.positionWS;
}
float3 GetColor(LightData value)
{
return value.color;
}
float GetRangeAttenuationScale(LightData value)
{
return value.rangeAttenuationScale;
}
float GetRangeAttenuationBias(LightData value)
{
return value.rangeAttenuationBias;
}
float GetAngleScale(LightData value)
{
return value.angleScale;
}
float GetAngleOffset(LightData value)
{
return value.angleOffset;
}
int GetCookieIndex(LightData value)
{
return value.cookieIndex;
}
int GetLightType(LightData value)
{
return value.lightType;
}
float3 GetRight(LightData value)
{
return value.right;
}
float3 GetUp(LightData value)
{
return value.up;
}
float3 GetForward(LightData value)
{
return value.forward;
}
int GetShadowIndex(LightData value)
{
return value.shadowIndex;
}
int GetContactShadowIndex(LightData value)
{
return value.contactShadowIndex;
}
float GetShadowDimmer(LightData value)
{
return value.shadowDimmer;
}
float4 GetShadowMaskSelector(LightData value)
{
return value.shadowMaskSelector;
}
int GetNonLightmappedOnly(LightData value)
{
return value.nonLightmappedOnly;
}
float GetMinRoughness(LightData value)
{
return value.minRoughness;
}
float GetDiffuseScale(LightData value)
{
return value.diffuseScale;
}
float GetSpecularScale(LightData value)
{
return value.specularScale;
}
float2 GetSize(LightData value)
{
return value.size;
}
float GetVolumetricDimmer(LightData value)
{
return value.volumetricDimmer;
}
//
// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.EnvLightData
//
float3 GetCapturePositionWS(EnvLightData value)
{
return value.capturePositionWS;
}
int GetInfluenceShapeType(EnvLightData value)
{
return value.influenceShapeType;
}
float3 GetProxyExtents(EnvLightData value)
{
return value.proxyExtents;
}
float GetMinProjectionDistance(EnvLightData value)
{
return value.minProjectionDistance;
}
float3 GetProxyPositionWS(EnvLightData value)
{
return value.proxyPositionWS;
}
float3 GetProxyForward(EnvLightData value)
{
return value.proxyForward;
}
float3 GetProxyUp(EnvLightData value)
{
return value.proxyUp;
}
float3 GetProxyRight(EnvLightData value)
{
return value.proxyRight;
}
float3 GetInfluencePositionWS(EnvLightData value)
{
return value.influencePositionWS;
}
float3 GetInfluenceForward(EnvLightData value)
{
return value.influenceForward;
}
float3 GetInfluenceUp(EnvLightData value)
{
return value.influenceUp;
}
float3 GetInfluenceRight(EnvLightData value)
{
return value.influenceRight;
}
float3 GetInfluenceExtents(EnvLightData value)
{
return value.influenceExtents;
}
float GetUnused00(EnvLightData value)
{
return value.unused00;
}
float3 GetBlendDistancePositive(EnvLightData value)
{
return value.blendDistancePositive;
}
float3 GetBlendDistanceNegative(EnvLightData value)
{
return value.blendDistanceNegative;
}
float3 GetBlendNormalDistancePositive(EnvLightData value)
{
return value.blendNormalDistancePositive;
}
float3 GetBlendNormalDistanceNegative(EnvLightData value)
{
return value.blendNormalDistanceNegative;
}
float3 GetBoxSideFadePositive(EnvLightData value)
{
return value.boxSideFadePositive;
}
float3 GetBoxSideFadeNegative(EnvLightData value)
{
return value.boxSideFadeNegative;
}
float GetWeight(EnvLightData value)
{
return value.weight;
}
float GetMultiplier(EnvLightData value)
{
return value.multiplier;
}
int GetEnvIndex(EnvLightData value)
{
return value.envIndex;
}
#endif

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


UNITY_BRANCH if (lightData.cookieIndex >= 0)
{
float3 lightToSample = positionWS - lightData.positionWS;
float3 lightToSample = positionWS - lightData.positionRWS;
float3 cookie = EvaluateCookie_Directional(lightLoopContext, lightData, lightToSample);
color *= cookie;

// Return L vector for punctual light (normalize surface to light), lightToSample (light to surface non normalize) and distances {d, d^2, 1/d, d_proj}
void GetPunctualLightVectors(float3 positionWS, LightData lightData, out float3 L, out float3 lightToSample, out float4 distances)
{
lightToSample = positionWS - lightData.positionWS;
lightToSample = positionWS - lightData.positionRWS;
int lightType = lightData.lightType;
distances.w = dot(lightToSample, lightData.forward);

attenuation = SmoothPunctualLightAttenuation(distances, lightData.rangeAttenuationScale, lightData.rangeAttenuationBias,
lightData.angleScale, lightData.angleOffset);
#if (SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET != 0)
#endif
// Projector lights always have cookies, so we can perform clipping inside the if().
UNITY_BRANCH if (lightData.cookieIndex >= 0)

if (influenceShapeType == ENVSHAPETYPE_SPHERE)
{
projectionDistance = IntersectSphereProxy(lightData, dirPS, positionPS);
// We can reuse dist calculate in LS directly in WS as there is no scaling. Also the offset is already include in lightData.capturePositionWS
float3 capturePositionWS = lightData.capturePositionWS;
R = (positionWS + projectionDistance * R) - capturePositionWS;
// We can reuse dist calculate in LS directly in WS as there is no scaling. Also the offset is already include in lightData.capturePositionRWS
R = (positionWS + projectionDistance * R) - lightData.capturePositionRWS;
weight = InfluenceSphereWeight(lightData, normalWS, positionWS, positionIS, dirIS);
}

// No need to normalize for fetching cubemap
// We can reuse dist calculate in LS directly in WS as there is no scaling. Also the offset is already include in lightData.capturePositionWS
float3 capturePositionWS = lightData.capturePositionWS;
R = (positionWS + projectionDistance * R) - capturePositionWS;
// We can reuse dist calculate in LS directly in WS as there is no scaling. Also the offset is already include in lightData.capturePositionRWS
R = (positionWS + projectionDistance * R) - lightData.capturePositionRWS;
weight = InfluenceBoxWeight(lightData, normalWS, positionWS, positionIS, dirIS);
}

// Compute the distance from the light to the back face of the object along the light direction.
float distBackFaceToLight = GetPunctualShadowClosestDistance( lightLoopContext.shadowContext, s_linear_clamp_sampler,
posInput.positionWS, lightData.shadowIndex, L, lightData.positionWS);
posInput.positionWS, lightData.shadowIndex, L, lightData.positionRWS);
// Our subsurface scattering models use the semi-infinite planar slab assumption.
// Therefore, we need to find the thickness along the normal.

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


// Rescale for cookies and windowing.
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.positionWS = light.light.transform.position;
directionalLightData.positionRWS = light.light.transform.position;
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.

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

lightData.size = new Vector2(additionalLightData.shapeWidth, additionalLightData.shapeHeight);
}
float distanceToCamera = (lightData.positionWS - camera.transform.position).magnitude;
float distanceToCamera = (lightData.positionRWS - camera.transform.position).magnitude;
float distanceFade = ComputeLinearDistanceFade(distanceToCamera, additionalLightData.fadeDistance);
float lightScale = additionalLightData.lightDimmer * distanceFade;

lightData.shadowMaskSelector.x = -1.0f;
lightData.nonLightmappedOnly = 0;
}
// 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);

// Then Culling side
var range = lightDimensions.z;
var lightToWorld = light.localToWorld;
Vector3 positionWS = lightData.positionWS;
Vector3 positionWS = lightData.positionRWS;
Vector3 positionVS = worldToView.MultiplyPoint(positionWS);
Matrix4x4 lightToView = worldToView * lightToWorld;

envLightData.influenceRight = influenceToWorld.GetColumn(0).normalized;
envLightData.influenceUp = influenceToWorld.GetColumn(1).normalized;
envLightData.influenceForward = influenceToWorld.GetColumn(2).normalized;
envLightData.capturePositionWS = capturePosition;
envLightData.influencePositionWS = influenceToWorld.GetColumn(3);
envLightData.capturePositionRWS = capturePosition;
envLightData.influencePositionRWS = influenceToWorld.GetColumn(3);
envLightData.envIndex = envIndex;

envLightData.proxyRight = proxyToWorld.GetColumn(0).normalized;
envLightData.proxyUp = proxyToWorld.GetColumn(1).normalized;
envLightData.proxyForward = proxyToWorld.GetColumn(2).normalized;
envLightData.proxyPositionWS = proxyToWorld.GetColumn(3);
envLightData.proxyPositionRWS = proxyToWorld.GetColumn(3);
m_lightList.envLights.Add(envLightData);
return true;

// Caution: 'DirectionalLightData.positionWS' is camera-relative after this point.
int last = m_lightList.directionalLights.Count - 1;
DirectionalLightData lightData = m_lightList.directionalLights[last];
lightData.positionWS -= camPosWS;
lightData.positionRWS -= camPosWS;
m_lightList.directionalLights[last] = lightData;
}
}

// Caution: 'LightData.positionWS' is camera-relative after this point.
int last = m_lightList.lights.Count - 1;
LightData lightData = m_lightList.lights[last];
lightData.positionWS -= camPosWS;
lightData.positionRWS -= camPosWS;
m_lightList.lights[last] = lightData;
}
}

// to allow the preceding code to work with the absolute world space coordinates.
if (ShaderConfig.s_CameraRelativeRendering != 0)
{
// Caution: 'EnvLightData.positionWS' is camera-relative after this point.
// Caution: 'EnvLightData.positionRWS' is camera-relative after this point.
envLightData.capturePositionWS -= camPosWS;
envLightData.influencePositionWS -= camPosWS;
envLightData.proxyPositionWS -= camPosWS;
envLightData.capturePositionRWS -= camPosWS;
envLightData.influencePositionRWS -= camPosWS;
envLightData.proxyPositionRWS -= camPosWS;
m_lightList.envLights[last] = envLightData;
}
}

cmd.SetGlobalTexture(HDShaderIDs._DeferredShadowTexture, RuntimeUtilities.whiteTexture);
return;
}
using (new ProfilingSample(cmd, "Deferred Directional Shadow", CustomSamplerId.TPDeferredDirectionalShadow.GetSampler()))
{
Vector4 lightDirection = Vector4.zero;

}
else
kernel = s_deferredDirectionalShadowKernel;
// We use the .w component of the direction/position vectors to choose in the shader the
// light direction of the contact shadows (direction light direction or (pixel position - light position))
if (m_CurrentSunLight != null)

}
if (m_DominantLightIndex != -1)
{
lightPosition = m_DominantLightData.positionWS;
lightPosition = m_DominantLightData.positionRWS;
lightPosition.w = 1;
lightDirection.w = 0;
}

2
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoopDef.hlsl


output.influenceForward = float3(0.0, 0.0, 1.0);
output.influenceUp = float3(0.0, 1.0, 0.0);
output.influenceRight = float3(1.0, 0.0, 0.0);
output.influencePositionWS = float3(0.0, 0.0, 0.0);
output.influencePositionRWS = float3(0.0, 0.0, 0.0);
output.weight = 1.0;
output.multiplier = 1.0;

8
com.unity.render-pipelines.high-definition/HDRP/Lighting/Reflection/VolumeProjection.hlsl


float3 WorldToProxyPosition(EnvLightData lightData, float3x3 worldToPS, float3 positionWS)
{
float3 positionPS = positionWS - lightData.proxyPositionWS;
float3 positionPS = positionWS - lightData.proxyPositionRWS;
positionPS = mul(positionPS, worldToPS).xyz;
return positionPS;
}

#if defined(ENVMAP_FEATURE_INFLUENCENORMAL)
float insideInfluenceNormalVolume = lengthPositionLS <= (lightData.influenceExtents.x - lightData.blendNormalDistancePositive.x) ? 1.0 : 0.0;
float insideWeight = InfluenceFadeNormalWeight(normalWS, normalize(positionWS - lightData.capturePositionWS));
float insideWeight = InfluenceFadeNormalWeight(normalWS, normalize(positionWS - lightData.capturePositionRWS));
alpha *= insideInfluenceNormalVolume ? 1.0 : insideWeight;
#endif

float3 belowPositiveInfluenceNormalVolume = positiveDistance / max(0.0001, lightData.blendNormalDistancePositive);
float3 aboveNegativeInfluenceNormalVolume = negativeDistance / max(0.0001, lightData.blendNormalDistanceNegative);
float insideInfluenceNormalVolume = all(belowPositiveInfluenceNormalVolume >= 1.0) && all(aboveNegativeInfluenceNormalVolume >= 1.0) ? 1.0 : 0;
float insideWeight = InfluenceFadeNormalWeight(normalWS, normalize(positionWS - lightData.capturePositionWS));
float insideWeight = InfluenceFadeNormalWeight(normalWS, normalize(positionWS - lightData.capturePositionRWS));
alpha *= insideInfluenceNormalVolume ? 1.0 : insideWeight;
#endif

float3 WorldToInfluencePosition(EnvLightData lightData, float3x3 worldToIS, float3 positionWS)
{
float3 positionIS = positionWS - lightData.influencePositionWS;
float3 positionIS = positionWS - lightData.influencePositionRWS;
positionIS = mul(positionIS, worldToIS).xyz;
return positionIS;
}

13
com.unity.render-pipelines.high-definition/HDRP/Lighting/SphericalHarmonics.cs


return sh;
}
public static SphericalHarmonicsL2 RescaleCoefficients(SphericalHarmonicsL2 sh, float scalar)
{
for (int c = 0; c < 3; c++)
{
for (int i = 0; i < 9; i++)
{
sh[c, i] *= scalar;
}
}
return sh;
}
// Packs coefficients so that we can use Peter-Pike Sloan's shader code.
// Does not perform premultiplication with coefficients of SH basis functions.
// See SetSHEMapConstants() in "Stupid Spherical Harmonics Tricks".

2
com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/DensityVolume.cs


[AddComponentMenu("Rendering/Density Volume", 1100)]
public class DensityVolume : MonoBehaviour
{
public DensityVolumeParameters parameters = new DensityVolumeParameters(Color.grey, 10.0f, 0.0f);
public DensityVolumeParameters parameters = new DensityVolumeParameters(Color.white, 10.0f, 0.0f);
private Texture3D previousVolumeMask = null;

21
com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumeTextureAtlas.cs


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///
/// MIT License ///
/// ///
/// Copyright (c) 2016 Rapha�l Ernaelsten (@RaphErnaelsten) ///
/// ///
/// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), ///
/// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, ///
/// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: ///
/// ///
/// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ///
/// ///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ///
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ///
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS ///
/// IN THE SOFTWARE. ///
/// ///
/// PLEASE CONSIDER CREDITING AURA IN YOUR PROJECTS. IF RELEVANT, USE THE UNMODIFIED LOGO PROVIDED IN THE "LICENSE" FOLDER. ///
/// ///
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using Unity.Collections.LowLevel.Unsafe;

133
com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumeVoxelization.compute


// Definitions
//--------------------------------------------------------------------------------------------------
#pragma kernel VolumeVoxelizationBruteforce VolumeVoxelization=VolumeVoxelizationBruteforce LIGHTLOOP_SINGLE_PASS
#pragma kernel VolumeVoxelizationClustered VolumeVoxelization=VolumeVoxelizationClustered LIGHTLOOP_TILE_PASS USE_CLUSTERED_LIGHTLIST
#pragma kernel VolumeVoxelizationBruteforceMQ VolumeVoxelization=VolumeVoxelizationBruteforceMQ VL_PRESET_MQ LIGHTLOOP_SINGLE_PASS
#pragma kernel VolumeVoxelizationClusteredMQ VolumeVoxelization=VolumeVoxelizationClusteredMQ VL_PRESET_MQ LIGHTLOOP_TILE_PASS USE_CLUSTERED_LIGHTLIST
#pragma kernel VolumeVoxelizationBruteforceHQ VolumeVoxelization=VolumeVoxelizationBruteforceHQ VL_PRESET_HQ LIGHTLOOP_SINGLE_PASS
#pragma kernel VolumeVoxelizationClusteredHQ VolumeVoxelization=VolumeVoxelizationClusteredHQ VL_PRESET_HQ LIGHTLOOP_TILE_PASS USE_CLUSTERED_LIGHTLIST
#include "../../ShaderPass/ShaderPass.cs.hlsl"
#define SHADERPASS SHADERPASS_VOLUME_VOXELIZATION
#include "../../ShaderConfig.cs.hlsl"
#if (SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET == 1)
#ifdef VL_PRESET_MQ
#define VBUFFER_TILE_SIZE 8
#define VBUFFER_SLICE_COUNT 64
#else
#define VBUFFER_TILE_SIZE 8
#endif
#ifdef VL_PRESET_HQ
#define VBUFFER_TILE_SIZE 4
#define VBUFFER_SLICE_COUNT 128
#define VBUFFER_TILE_SIZE 4
#include "../../ShaderPass/ShaderPass.cs.hlsl"
#define SHADERPASS SHADERPASS_VOLUME_VOXELIZATION
//--------------------------------------------------------------------------------------------------
// Included headers

#include "../../ShaderVariables.hlsl"
#include "VolumetricLighting.cs.hlsl"
#define UNITY_MATERIAL_VOLUMETRIC // Define before including Lighting.hlsl and Material.hlsl
#include "../Lighting.hlsl" // Includes Material.hlsl
#define UNITY_MATERIAL_VOLUMETRIC // Define before including Lighting.hlsl and Material.hlsl
#include "../Lighting.hlsl" // Includes Material.hlsl
#pragma only_renderers d3d11 ps4 xboxone vulkan metal

float4 _VBufferSampleOffset; // Not used by this shader
float _CornetteShanksConstant; // Not used by this shader
uint _NumVisibleDensityVolumes;
float3 _VolumeMaskDimensions; //x = 1/totalTextures , y = 1/textureSize, z = textureSize
float4 _VolumeMaskDimensions; //x = 1/numTextures , y = width, z = depth = width * numTextures, w = maxLod
float SampleVolumeMask(DensityVolumeData volumeData, float3 voxelCenterUV, float3 VxUV, float3 VyUV, float3 VzUV)
float SampleVolumeMask(DensityVolumeData volumeData, float3 voxelCenterUVW, float3 duvw_dx, float3 duvw_dy, float3 duvw_dz)
float offset = volumeData.textureIndex * _VolumeMaskDimensions.x;
float clampBorder = 0.5f * _VolumeMaskDimensions.y;
// Scale and bias the UVWs and then take fractional part, will be in [0,1] range.
voxelCenterUVW = frac(voxelCenterUVW * volumeData.textureTiling + volumeData.textureScroll);
float rcpNumTextures = _VolumeMaskDimensions.x;
float textureWidth = _VolumeMaskDimensions.y;
float textureDepth = _VolumeMaskDimensions.z;
float maxLod = _VolumeMaskDimensions.w;
//scale and bias the UVs and then take fractional part, will be in [0,1] range
voxelCenterUV = frac(voxelCenterUV * volumeData.textureTiling + volumeData.textureScroll);
float offset = volumeData.textureIndex * rcpNumTextures;
voxelCenterUVW.z = voxelCenterUVW.z * rcpNumTextures + offset;
voxelCenterUV.z = voxelCenterUV.z * _VolumeMaskDimensions.x;
voxelCenterUV.z += offset;
// TODO: expose the LoD bias parameter.
float lod = ComputeTextureLOD(duvw_dx, duvw_dy, duvw_dz, textureWidth);
lod = clamp(lod, 0, maxLod);
voxelCenterUV.z = clamp(voxelCenterUV.z, offset + clampBorder, offset + _VolumeMaskDimensions.x - clampBorder);
// TODO: bugfix.
// Note that this clamping to edge doesn't quite work.
// First of all, the distance to the edge should depend on the LoD.
// Secondly, for trilinear filtering, which of the two LoDs should you choose to compute the distance to the edge?
// If you use floor(lod), the lower LoD may cause a leak across the edge from the neighbor texture.
// If you use ceil(lod), the upper LoD effectively loses a texel at the border, which may break tileable textures.
// For now, we choose the second option.
// We support texture filtering across the wrap in Z in neither case.
int textureSize = (int)textureDepth;
int mipSize = textureSize >> (int)ceil(lod);
float halfTexelSize = 0.5f * rcp(mipSize);
voxelCenterUVW.z = clamp(voxelCenterUVW.z, offset + halfTexelSize, offset + rcpNumTextures - halfTexelSize);
float lod = ComputeTextureLOD(VxUV * _VolumeMaskDimensions.z, VyUV * _VolumeMaskDimensions.z, VzUV * _VolumeMaskDimensions.z);
float maskValue = SAMPLE_TEXTURE3D_LOD(_VolumeMaskAtlas, s_linear_clamp_sampler, voxelCenterUV, lod).a;
return maskValue;
return SAMPLE_TEXTURE3D_LOD(_VolumeMaskAtlas, s_trilinear_clamp_sampler, voxelCenterUVW, lod).a;
}

float n = _VBufferDepthDecodingParams.x + _VBufferDepthDecodingParams.z;
float z0 = n; // Start the computation from the near plane
float de = rcp(VBUFFER_SLICE_COUNT); // Log-encoded distance between slices
float z0 = n; // Start the computation from the near plane
float de = _VBufferSliceCount.y; // Log-encoded distance between slices
#ifdef USE_CLUSTERED_LIGHTLIST
// The voxel can overlap up to 2 light clusters along Z, so we have to iterate over both.

LIGHTCATEGORY_DENSITY_VOLUME, volumeStarts[0], volumeCounts[0]);
#endif // USE_CLUSTERED_LIGHTLIST
#if defined(SHADER_API_METAL)
[fastopt]
for (uint slice = 0; slice < VBUFFER_SLICE_COUNT; slice++)
#else
uint sliceCountHack = max(VBUFFER_SLICE_COUNT, (uint)_VBufferDepthEncodingParams.w); // Prevent unrolling...
// TODO: replace 'sliceCountHack' with VBUFFER_SLICE_COUNT when the shader compiler bug is fixed.
for (uint slice = 0; slice < sliceCountHack; slice++)
#endif
for (uint slice = 0; slice < (uint)_VBufferSliceCount.x; slice++)
{
uint3 voxelCoord = uint3(posInput.positionSS, slice);

float z = z0 + halfDZ;
float3 voxelCenterWS = rayOriginWS + z * rayUnDirWS; // Works due to the length of of the dir
// Dimensions of the voxel as we step along the ray.
float3 voxelRightSize = z * voxelAxisRight;
float3 voxelUpSize = z * voxelAxisUp;
float3 voxelDepthSize = halfDZ * voxelAxisForward;
// TODO: define a function ComputeGlobalFogCoefficients(float3 voxelCenterWS),
// which allows procedural definition of extinction and scattering.
float3 voxelScattering = _GlobalScattering;

{
#endif // USE_CLUSTERED_LIGHTLIST
OrientedBBox obb = _VolumeBounds[volumeIndex];
const OrientedBBox obb = _VolumeBounds[volumeIndex];
float3x3 obbFrame = float3x3(obb.right, obb.up, cross(obb.up, obb.right));
float3 obbExtents = float3(obb.extentX, obb.extentY, obb.extentZ);
const float3x3 obbFrame = float3x3(obb.right, obb.up, cross(obb.up, obb.right));
const float3 obbExtents = float3(obb.extentX, obb.extentY, obb.extentZ);
float3 voxelCenterBS = mul(voxelCenterWS - obb.center, transpose(obbFrame));
float3 voxelCenterUV = (voxelCenterBS / obbExtents);
const float3 voxelCenterBS = mul(voxelCenterWS - obb.center, transpose(obbFrame));
const float3 voxelCenterCS = (voxelCenterBS / obbExtents);
const float3 voxelAxisRightBS = mul(voxelAxisRight, transpose(obbFrame));
const float3 voxelAxisUpBS = mul(voxelAxisUp, transpose(obbFrame));
const float3 voxelAxisForwardBS = mul(voxelAxisForward, transpose(obbFrame));
#if SOFT_VOXELIZATION
// We need to determine which is the face closest to 'voxelCenterBS'.

// We have determined the normal of the closest face.
// We now have to construct the diagonal of the voxel with the longest extent along this normal.
float3 minDiagPointBS, maxDiagPointBS;
float3 voxelAxisRightBS = mul(voxelAxisRight, transpose(obbFrame));
float3 voxelAxisUpBS = mul(voxelAxisUp, transpose(obbFrame));
float3 voxelAxisForwardBS = mul(voxelAxisForward, transpose(obbFrame));
// Start at the center of the voxel.
minDiagPointBS = maxDiagPointBS = voxelCenterBS;

#else // SOFT_VOXELIZATION
bool overlap = abs(voxelCenterUV.x) <= 1 &&
abs(voxelCenterUV.y) <= 1 &&
abs(voxelCenterUV.z) <= 1;
bool overlap = Max3(abs(voxelCenterCS.x), abs(voxelCenterCS.y), abs(voxelCenterCS.z)) <= 1;
float overlapFraction = overlap ? 1 : 0;

{
float scatteringAndExtinctionMask = 1.0f;
float densityMask = 1.0f;
float3 voxelRightSizeBS = mul(voxelRightSize, transpose(obbFrame));
float3 voxelRightSizeUV = (voxelRightSizeBS / obbExtents);
float3 voxelUpSizeBS = mul(voxelUpSize, transpose(obbFrame));
float3 voxelUpSizeUV = (voxelUpSizeBS / obbExtents);
float3 voxelDepthSizeBS = mul(voxelDepthSize, transpose(obbFrame));
float3 voxelDepthSizeUV = (voxelDepthSizeBS / obbExtents);
// We divide extents (half-sizes) by extents here, obtaining full-sized gradients.
float3 voxelGradRightUVW = z * voxelAxisRightBS / obbExtents;
float3 voxelGradUpUVW = z * voxelAxisUpBS / obbExtents;
float3 voxelGradForwardUVW = halfDZ * voxelAxisForwardBS / obbExtents;
float3 voxelCenterUVW = voxelCenterCS * 0.5 + 0.5;
scatteringAndExtinctionMask = SampleVolumeMask(_VolumeData[volumeIndex], voxelCenterUV * 0.5 + 0.5, voxelRightSizeUV, voxelUpSizeUV, voxelDepthSizeUV);
densityMask = SampleVolumeMask(_VolumeData[volumeIndex], voxelCenterUVW, voxelGradRightUVW, voxelGradUpUVW, voxelGradForwardUVW);
voxelScattering += overlapFraction * _VolumeData[volumeIndex].scattering * scatteringAndExtinctionMask;
voxelExtinction += overlapFraction * _VolumeData[volumeIndex].extinction * scatteringAndExtinctionMask;
voxelScattering += overlapFraction * _VolumeData[volumeIndex].scattering * densityMask;
voxelExtinction += overlapFraction * _VolumeData[volumeIndex].extinction * densityMask;
}
#ifndef USE_CLUSTERED_LIGHTLIST

float3 upDirWS = mul(-float3(upCoord, 1), (float3x3)_VBufferCoordToViewDirWS);
// Compute the axes of the voxel. These are not normalized, but rather computed to scale with Z.
// This coordinate system is generally not orthogonal.
float3 voxelAxisForward = centerDirWS;
float3 voxelAxisUp = 0.5 * (upDirWS - centerDirWS);
float3 voxelAxisRight = 0.5 * (centerDirWS - leftDirWS);

81
com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumetricLighting.compute


// Definitions
//--------------------------------------------------------------------------------------------------
#pragma kernel VolumetricLightingBruteforce VolumetricLighting=VolumetricLightingBruteforce ENABLE_REPROJECTION=0 LIGHTLOOP_SINGLE_PASS
#pragma kernel VolumetricLightingBruteforceReproj VolumetricLighting=VolumetricLightingBruteforceReproj ENABLE_REPROJECTION=1 LIGHTLOOP_SINGLE_PASS
#pragma kernel VolumetricLightingClustered VolumetricLighting=VolumetricLightingClustered ENABLE_REPROJECTION=0 LIGHTLOOP_TILE_PASS USE_CLUSTERED_LIGHTLIST
#pragma kernel VolumetricLightingClusteredReproj VolumetricLighting=VolumetricLightingClusteredReproj ENABLE_REPROJECTION=1 LIGHTLOOP_TILE_PASS USE_CLUSTERED_LIGHTLIST
#pragma kernel VolumetricLightingBruteforceMQ VolumetricLighting=VolumetricLightingBruteforceMQ VL_PRESET_MQ ENABLE_REPROJECTION=0 LIGHTLOOP_SINGLE_PASS
#pragma kernel VolumetricLightingBruteforceReprojMQ VolumetricLighting=VolumetricLightingBruteforceReprojMQ VL_PRESET_MQ ENABLE_REPROJECTION=1 LIGHTLOOP_SINGLE_PASS
#pragma kernel VolumetricLightingClusteredMQ VolumetricLighting=VolumetricLightingClusteredMQ VL_PRESET_MQ ENABLE_REPROJECTION=0 LIGHTLOOP_TILE_PASS USE_CLUSTERED_LIGHTLIST
#pragma kernel VolumetricLightingClusteredReprojMQ VolumetricLighting=VolumetricLightingClusteredReprojMQ VL_PRESET_MQ ENABLE_REPROJECTION=1 LIGHTLOOP_TILE_PASS USE_CLUSTERED_LIGHTLIST
#pragma kernel VolumetricLightingBruteforceHQ VolumetricLighting=VolumetricLightingBruteforceHQ VL_PRESET_HQ ENABLE_REPROJECTION=0 LIGHTLOOP_SINGLE_PASS
#pragma kernel VolumetricLightingBruteforceReprojHQ VolumetricLighting=VolumetricLightingBruteforceReprojHQ VL_PRESET_HQ ENABLE_REPROJECTION=1 LIGHTLOOP_SINGLE_PASS
#pragma kernel VolumetricLightingClusteredHQ VolumetricLighting=VolumetricLightingClusteredHQ VL_PRESET_HQ ENABLE_REPROJECTION=0 LIGHTLOOP_TILE_PASS USE_CLUSTERED_LIGHTLIST
#pragma kernel VolumetricLightingClusteredReprojHQ VolumetricLighting=VolumetricLightingClusteredReprojHQ VL_PRESET_HQ ENABLE_REPROJECTION=1 LIGHTLOOP_TILE_PASS USE_CLUSTERED_LIGHTLIST
#define SHADOW_USE_ONLY_VIEW_BASED_BIASING 1 // We don't use normal biasing as it is not available when doing volumetric
#include "../../ShaderPass/ShaderPass.cs.hlsl"
#define SHADERPASS SHADERPASS_VOLUMETRIC_LIGHTING
#include "../../ShaderConfig.cs.hlsl"
#if (SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET == 1)
#ifdef VL_PRESET_MQ
#define VBUFFER_TILE_SIZE 8
#define VBUFFER_SLICE_COUNT 64
#else
#define VBUFFER_TILE_SIZE 8
#endif
#ifdef VL_PRESET_HQ
#define VBUFFER_TILE_SIZE 4
#define VBUFFER_SLICE_COUNT 128
#define VBUFFER_TILE_SIZE 4
#define SUPPORT_PUNCTUAL_LIGHTS 1 // Punctual lights contribute to fog lighting
#define GROUP_SIZE_1D 8
#define GROUP_SIZE_1D 8
#define SUPPORT_PUNCTUAL_LIGHTS 1 // Punctual lights contribute to fog lighting
#define SHADOW_USE_ONLY_VIEW_BASED_BIASING 1 // We don't use normal biasing as it is not available when doing volumetric
#if (SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET != 0) // Switch between the full and the empty shader
#include "../../ShaderPass/ShaderPass.cs.hlsl"
#define SHADERPASS SHADERPASS_VOLUMETRIC_LIGHTING
//--------------------------------------------------------------------------------------------------
// Included headers

#include "VolumetricLighting.cs.hlsl"
#include "VBuffer.hlsl"
#define UNITY_MATERIAL_VOLUMETRIC // Define before including Lighting.hlsl and Material.hlsl
#include "../Lighting.hlsl" // Includes Material.hlsl
#define UNITY_MATERIAL_VOLUMETRIC // Define before including Lighting.hlsl and Material.hlsl
#include "../Lighting.hlsl" // Includes Material.hlsl
#include "../LightEvaluation.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal switch

float3 coneAxisY = lenMul * light.up;
sampleLight = IntersectRayCone(ray.originWS, ray.jitterDirWS,
light.positionWS, light.forward,
light.positionRWS, light.forward,
coneAxisX, coneAxisY,
t0, t1, tEntr, tExit);
}

float hackMinDistSq = Sq(dt * (0.5 / 7));
float t, distSq, rcpPdf;
ImportanceSamplePunctualLight(rndVal, light.positionWS,
ImportanceSamplePunctualLight(rndVal, light.positionRWS,
ray.originWS, ray.jitterDirWS,
tEntr, tExit, t, distSq, rcpPdf,
hackMinDistSq);

float3 lightToSample = posInput.positionWS - light.positionWS;
float3 lightToSample = posInput.positionWS - light.positionRWS;
float distRcp = rsqrt(distSq);
float dist = distSq * distRcp;
float distProj = dot(lightToSample, light.forward);

// and any temporal instability of anisotropy causes causes visible jitter.
// In order to stabilize the image, we use the voxel center for all
// anisotropy-related calculations.
float3 centerL = light.positionWS - centerWS;
float3 centerL = light.positionRWS - centerWS;
float cosTheta = dot(centerL, ray.centerDirWS) * rsqrt(dot(centerL, centerL));
float phase = CornetteShanksPhasePartVarying(anisotropy, cosTheta);

// 'light.right' and 'light.up' vectors are pre-scaled on the CPU by (2/w) and (2/h).
float3x3 rotMat = float3x3(light.right, light.up, light.forward);
float3 o = mul(rotMat, ray.originWS - light.positionWS);
float3 o = mul(rotMat, ray.originWS - light.positionRWS);
float3 d = mul(rotMat, ray.jitterDirWS);
float range = light.size.x;

posInput.positionWS = GetPointAtDistance(ray, t);
float3 L = -light.forward;
float3 lightToSample = posInput.positionWS - light.positionWS;
float3 lightToSample = posInput.positionWS - light.positionRWS;
float distProj = dot(lightToSample, light.forward);
float4 distances = float4(1, 1, 1, distProj);

// and any temporal instability of anisotropy causes causes visible jitter.
// In order to stabilize the image, we use the voxel center for all
// anisotropy-related calculations.
float3 centerL = light.positionWS - centerWS;
float3 centerL = light.positionRWS - centerWS;
float cosTheta = dot(centerL, ray.centerDirWS) * rsqrt(dot(centerL, centerL));
float phase = CornetteShanksPhasePartVarying(anisotropy, cosTheta);

PositionInputs posInput, DualRay ray)
{
const float n = _VBufferDepthDecodingParams.x + _VBufferDepthDecodingParams.z;
const float z0 = n; // Start integration from the near plane
const float de = rcp(VBUFFER_SLICE_COUNT); // Log-encoded distance between slices
const float z0 = n; // Start integration from the near plane
const float de = _VBufferSliceCount.y; // Log-encoded distance between slices
float t0 = ConvertLinearDepthToJitterRayDist(ray, z0);

lightClusters[0] = GetLightClusterIndex(posInput.tileCoord, z0);
#endif // USE_CLUSTERED_LIGHTLIST
#if defined(SHADER_API_METAL)
[fastopt]
for (uint slice = 0; slice < VBUFFER_SLICE_COUNT; slice++)
#else
uint sliceCountHack = max(VBUFFER_SLICE_COUNT, (uint)_VBufferDepthEncodingParams.w); // Prevent unrolling...
// TODO: replace 'sliceCountHack' with VBUFFER_SLICE_COUNT when the shader compiler bug is fixed.
for (uint slice = 0; slice < sliceCountHack; slice++)
#endif
for (uint slice = 0; slice < (uint)_VBufferSliceCount.x; slice++)
{
uint3 voxelCoord = uint3(posInput.positionSS, slice);

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

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


[GenerateHLSL]
public struct DensityVolumeData
{
public Vector3 scattering; // [0, 1], prefer sRGB
public float extinction;// [0, 1], prefer sRGB
public Vector3 scattering; // [0, 1]
public float extinction; // [0, 1]
public int textureIndex;//
public int textureIndex;
public Vector3 textureScroll;
public static DensityVolumeData GetNeutralValues()

data.scattering = Vector3.zero;
data.extinction = 0;
data.textureIndex = -1;
data.scattering = Vector3.zero;
data.extinction = 0;
data.textureIndex = -1;
data.textureTiling = Vector3.one;
data.textureScroll = Vector3.zero;

public enum VolumetricLightingPreset
{
Off,
Normal,
Ultra,
Medium,
High,
Count
} // enum VolumetricLightingPreset

}
} // struct Parameters
public VolumetricLightingPreset preset { get { return (VolumetricLightingPreset)Math.Min(ShaderConfig.s_VolumetricLightingPreset, (int)VolumetricLightingPreset.Count); } }
public VolumetricLightingPreset preset = VolumetricLightingPreset.Off;
static ComputeShader m_VolumeVoxelizationCS = null;
static ComputeShader m_VolumetricLightingCS = null;

RTHandleSystem.RTHandle m_DensityBufferHandle;
RTHandleSystem.RTHandle m_LightingBufferHandle;
// Do we support volumetric or not?
bool m_supportVolumetric = false;
// Is the feature globally disabled?
bool m_supportVolumetrics = false;
m_supportVolumetric = asset.renderPipelineSettings.supportVolumetric;
m_supportVolumetrics = asset.renderPipelineSettings.supportVolumetrics;
if (!m_supportVolumetric)
if (!m_supportVolumetrics)
preset = asset.renderPipelineSettings.increaseResolutionOfVolumetrics ? VolumetricLightingPreset.High :
VolumetricLightingPreset.Medium;
m_VolumeVoxelizationCS = asset.renderPipelineResources.volumeVoxelizationCS;
m_VolumetricLightingCS = asset.renderPipelineResources.volumetricLightingCS;

{
// Note: Here we can't test framesettings as they are not initialize yet
// TODO: Here we allocate history even for camera that may not use volumetric
if (!m_supportVolumetric)
if (!m_supportVolumetrics)
return;
// Start with the same parameters for both frames. Then update them one by one every frame.

// The results are undefined otherwise.
public void UpdatePerCameraData(HDCamera hdCamera)
{
if (!hdCamera.frameSettings.enableVolumetric)
if (!hdCamera.frameSettings.enableVolumetrics)
return;
var parameters = ComputeVBufferParameters(hdCamera, false);

{
switch (preset)
{
case VolumetricLightingPreset.Normal:
case VolumetricLightingPreset.Medium:
case VolumetricLightingPreset.Ultra:
case VolumetricLightingPreset.High:
return 4;
case VolumetricLightingPreset.Off:
return 0;

{
switch (preset)
{
case VolumetricLightingPreset.Normal:
case VolumetricLightingPreset.Medium:
case VolumetricLightingPreset.Ultra:
case VolumetricLightingPreset.High:
return 128;
case VolumetricLightingPreset.Off:
return 0;

return depthParams;
}
void SetPreconvolvedAmbientLightProbe(CommandBuffer cmd, float anisotropy)
void SetPreconvolvedAmbientLightProbe(CommandBuffer cmd, float dimmer, float anisotropy)
probeSH = SphericalHarmonicMath.RescaleCoefficients(probeSH, dimmer);
ZonalHarmonicsL2 phaseZH = ZonalHarmonicsL2.GetCornetteShanksPhaseFunction(anisotropy);
SphericalHarmonicsL2 finalSH = SphericalHarmonicMath.PremultiplyCoefficients(SphericalHarmonicMath.Convolve(probeSH, phaseZH));

public void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd, uint frameIndex)
{
if (!hdCamera.frameSettings.enableVolumetric)
return;
if (visualEnvironment.fogType != FogType.Volumetric)
if (!hdCamera.frameSettings.enableVolumetrics || visualEnvironment.fogType != FogType.Volumetric)
{
// Set the neutral black texture.
cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, CoreUtils.blackVolumeTexture);

// Get the interpolated anisotropy value.
var fog = VolumeManager.instance.stack.GetComponent<VolumetricFog>();
SetPreconvolvedAmbientLightProbe(cmd, fog.anisotropy);
SetPreconvolvedAmbientLightProbe(cmd, fog.globalLightProbeDimmer, fog.anisotropy);
var currFrameParams = hdCamera.vBufferParams[0];
var prevFrameParams = hdCamera.vBufferParams[1];

{
DensityVolumeList densityVolumes = new DensityVolumeList();
if (!hdCamera.frameSettings.enableVolumetric)
if (!hdCamera.frameSettings.enableVolumetrics)
return densityVolumes;
var visualEnvironment = VolumeManager.instance.stack.GetComponent<VisualEnvironment>();

public void VolumeVoxelizationPass(HDCamera hdCamera, CommandBuffer cmd, uint frameIndex, DensityVolumeList densityVolumes)
{
if (!hdCamera.frameSettings.enableVolumetric)
if (!hdCamera.frameSettings.enableVolumetrics)
return;
var visualEnvironment = VolumeManager.instance.stack.GetComponent<VisualEnvironment>();

{
int numVisibleVolumes = m_VisibleVolumeBounds.Count;
if (numVisibleVolumes == 0)
{
// Clear the render target instead of running the shader.
// Note: the clear must take the global fog into account!
// CoreUtils.SetRenderTarget(cmd, vBuffer.GetDensityBuffer(), ClearFlag.Color, CoreUtils.clearColorAllBlack);
// return;
// Clearing 3D textures does not seem to work!
// Use the workaround by running the full shader with 0 density
}
bool highQuality = preset == VolumetricLightingPreset.High;
int kernel = m_VolumeVoxelizationCS.FindKernel(enableClustered ? "VolumeVoxelizationClustered"
: "VolumeVoxelizationBruteforce");
int kernel;
if (highQuality)
{
kernel = m_VolumeVoxelizationCS.FindKernel(enableClustered ? "VolumeVoxelizationClusteredHQ"
: "VolumeVoxelizationBruteforceHQ");
}
else
{
kernel = m_VolumeVoxelizationCS.FindKernel(enableClustered ? "VolumeVoxelizationClusteredMQ"
: "VolumeVoxelizationBruteforceMQ");
}
var frameParams = hdCamera.vBufferParams[0];
Vector4 resolution = frameParams.resolution;

Matrix4x4 transform = HDUtils.ComputePixelCoordToWorldSpaceViewDirectionMatrix(vFoV, resolution, hdCamera.viewMatrix, false);
Texture3D volumeAtlas = DensityVolumeManager.manager.volumeAtlas.volumeAtlas;
Vector3 volumeAtlasDimensions = new Vector3(0.0f, 0.0f, 0.0f);
Vector4 volumeAtlasDimensions = new Vector4(0.0f, 0.0f, 0.0f, 0.0f);
volumeAtlasDimensions.y = 1.0f / volumeAtlas.width;
volumeAtlasDimensions.z = volumeAtlas.width;
volumeAtlasDimensions.y = volumeAtlas.width;
volumeAtlasDimensions.z = volumeAtlas.depth;
volumeAtlasDimensions.w = Mathf.Log(volumeAtlas.width, 2); // Max LoD
}
else
{

public void VolumetricLightingPass(HDCamera hdCamera, CommandBuffer cmd, uint frameIndex)
{
if (!hdCamera.frameSettings.enableVolumetric)
if (!hdCamera.frameSettings.enableVolumetrics)
return;
var visualEnvironment = VolumeManager.instance.stack.GetComponent<VisualEnvironment>();

using (new ProfilingSample(cmd, "Volumetric Lighting"))
{
// Only available in the Play Mode because all the frame counters in the Edit Mode are broken.
bool highQuality = preset == VolumetricLightingPreset.High;
if (enableReprojection)
if (highQuality)
kernel = m_VolumetricLightingCS.FindKernel(enableClustered ? "VolumetricLightingClusteredReproj"
: "VolumetricLightingBruteforceReproj");
if (enableReprojection)
{
kernel = m_VolumetricLightingCS.FindKernel(enableClustered ? "VolumetricLightingClusteredReprojHQ"
: "VolumetricLightingBruteforceReprojHQ");
}
else
{
kernel = m_VolumetricLightingCS.FindKernel(enableClustered ? "VolumetricLightingClusteredHQ"
: "VolumetricLightingBruteforceHQ");
}
kernel = m_VolumetricLightingCS.FindKernel(enableClustered ? "VolumetricLightingClustered"
: "VolumetricLightingBruteforce");
if (enableReprojection)
{
kernel = m_VolumetricLightingCS.FindKernel(enableClustered ? "VolumetricLightingClusteredReprojMQ"
: "VolumetricLightingBruteforceReprojMQ");
}
else
{
kernel = m_VolumetricLightingCS.FindKernel(enableClustered ? "VolumetricLightingClusteredMQ"
: "VolumetricLightingBruteforceMQ");
}
}
var frameParams = hdCamera.vBufferParams[0];

// TODO: set 'm_VolumetricLightingPreset'.
// TODO: set the constant buffer data only once.
cmd.SetComputeMatrixParam(m_VolumetricLightingCS, HDShaderIDs._VBufferCoordToViewDirWS, transform);
cmd.SetComputeVectorParam(m_VolumetricLightingCS, HDShaderIDs._VBufferSampleOffset, offset);
cmd.SetComputeFloatParam(m_VolumetricLightingCS, HDShaderIDs._CornetteShanksConstant, CornetteShanksPhasePartConstant(fog.anisotropy));
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferDensity, m_DensityBufferHandle);// Read
cmd.SetComputeMatrixParam( m_VolumetricLightingCS, HDShaderIDs._VBufferCoordToViewDirWS, transform);
cmd.SetComputeVectorParam( m_VolumetricLightingCS, HDShaderIDs._VBufferSampleOffset, offset);
cmd.SetComputeFloatParam( m_VolumetricLightingCS, HDShaderIDs._CornetteShanksConstant, CornetteShanksPhasePartConstant(fog.anisotropy));
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferDensity, m_DensityBufferHandle); // Read
cmd.SetComputeTextureParam(m_VolumetricLightingCS, kernel, HDShaderIDs._VBufferLightingIntegral, m_LightingBufferHandle); // Write
if (enableReprojection)
{

4
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs


sRGBFlags = m_sRGBFlags;
}
}
// normal to world only uses 3x3 for actual matrix so some data is packed in the unused space
// blend:
// float decalBlend = decalData.normalToWorld[0][3];

// float2 uvScale = float2(decalData.normalToWorld[3][0], decalData.normalToWorld[3][1]);
// float2 uvBias = float2(decalData.normalToWorld[3][2], decalData.normalToWorld[3][3]);
[GenerateHLSL]
[GenerateHLSL(PackingRules.Exact, false)]
public struct DecalData
{
public Matrix4x4 worldToDecal;

28
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs.hlsl


};
//
// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.DecalData
//
float4x4 GetWorldToDecal(DecalData value)
{
return value.worldToDecal;
}
float4x4 GetNormalToWorld(DecalData value)
{
return value.normalToWorld;
}
float4 GetDiffuseScaleBias(DecalData value)
{
return value.diffuseScaleBias;
}
float4 GetNormalScaleBias(DecalData value)
{
return value.normalScaleBias;
}
float4 GetMaskScaleBias(DecalData value)
{
return value.maskScaleBias;
}
float4 GetBaseColor(DecalData value)
{
return value.baseColor;
}
//
// Debug functions
//
void GetGeneratedDecalSurfaceDataDebug(uint paramId, DecalSurfaceData decalsurfacedata, inout float3 result, inout bool needLinearToSRGB)

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


float len = lightData.size.x;
float3 T = lightData.right;
float3 unL = lightData.positionWS - positionWS;
float3 unL = lightData.positionRWS - positionWS;
// Pick the major axis of the ellipsoid.
float3 axis = lightData.right;

lightData.specularScale *= intensity;
// Translate the light s.t. the shaded point is at the origin of the coordinate system.
lightData.positionWS -= positionWS;
lightData.positionRWS -= positionWS;
float3 P1 = lightData.positionWS - T * (0.5 * len);
float3 P2 = lightData.positionWS + T * (0.5 * len);
float3 P1 = lightData.positionRWS - T * (0.5 * len);
float3 P2 = lightData.positionRWS + T * (0.5 * len);
// Rotate the endpoints into the local coordinate system.
P1 = mul(P1, transpose(preLightData.orthoBasisViewNormal));

IntegrateBSDF_AreaRef(V, positionWS, preLightData, lightData, bsdfData,
lighting.diffuse, lighting.specular);
#else
float3 unL = lightData.positionWS - positionWS;
float3 unL = lightData.positionRWS - positionWS;
if (dot(lightData.forward, unL) >= 0.0001)
{

lightData.specularScale *= intensity;
// Translate the light s.t. the shaded point is at the origin of the coordinate system.
lightData.positionWS -= positionWS;
lightData.positionRWS -= positionWS;
lightVerts[0] = lightData.positionWS + lightData.right * halfWidth + lightData.up * halfHeight;
lightVerts[1] = lightData.positionWS + lightData.right * halfWidth + lightData.up * -halfHeight;
lightVerts[2] = lightData.positionWS + lightData.right * -halfWidth + lightData.up * -halfHeight;
lightVerts[3] = lightData.positionWS + lightData.right * -halfWidth + lightData.up * halfHeight;
lightVerts[0] = lightData.positionRWS + lightData.right * halfWidth + lightData.up * halfHeight;
lightVerts[1] = lightData.positionRWS + lightData.right * halfWidth + lightData.up * -halfHeight;
lightVerts[2] = lightData.positionRWS + lightData.right * -halfWidth + lightData.up * -halfHeight;
lightVerts[3] = lightData.positionRWS + lightData.right * -halfWidth + lightData.up * halfHeight;
// Rotate the endpoints into the local coordinate system.
lightVerts = mul(lightVerts, transpose(preLightData.orthoBasisViewNormal));

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


const float len = lightData.size.x;
const float3 T = lightData.right;
const float3 P1 = lightData.positionWS - T * (0.5 * len);
const float3 P1 = lightData.positionRWS - T * (0.5 * len);
const float dt = len * rcp(sampleCount);
const float off = 0.5 * dt;

u = frac(u + randNum);
// Lights in Unity point backward.
float4x4 localToWorld = float4x4(float4(lightData.right, 0.0), float4(lightData.up, 0.0), float4(-lightData.forward, 0.0), float4(lightData.positionWS, 1.0));
float4x4 localToWorld = float4x4(float4(lightData.right, 0.0), float4(lightData.up, 0.0), float4(-lightData.forward, 0.0), float4(lightData.positionRWS, 1.0));
switch (lightData.lightType)
{

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


float3 vLayerEnergyCoeff[NB_VLAYERS];
// TODOENERGY
// For now since FGD fetches aren't used in compute adding (instead we do non integrated
// Fresnel( ) evaluations and 1 - Fresnel( ) which is wrong, the former only ok for analytical
// lights for the top interface for R12), we will use these for FGD fetches but keep them
// For now since FGD fetches aren't used in compute adding (instead we do non integrated
// Fresnel( ) evaluations and 1 - Fresnel( ) which is wrong, the former only ok for analytical
// lights for the top interface for R12), we will use these for FGD fetches but keep them
// for BSDF( ) eval for analytical lights since the later don't use FGD terms.

//float topIor = bsdfData.coatIor;
// TODO:
// We will avoid using coatIor directly as with the fake refraction, it can cause TIR
// which even when handled in EvalIridescence (tested), doesn't look pleasing and
// which even when handled in EvalIridescence (tested), doesn't look pleasing and
// creates a discontinuity.
float scale = clamp((1.0-bsdfData.coatPerceptualRoughness), 0.0, 1.0);
float topIor = lerp(1.0001, bsdfData.coatIor, scale);

float theta[NB_NORMALS];
float2 uv[TOTAL_NB_LOBES];
// These 2 cases will generate the same code when no dual normal maps since COAT_NORMAL_IDX == BASE_NORMAL_IDX == 0,
// These 2 cases will generate the same code when no dual normal maps since COAT_NORMAL_IDX == BASE_NORMAL_IDX == 0,
// and one will be pruned out:
theta[COAT_NORMAL_IDX] = FastACosPos(NdotV[COAT_NORMAL_IDX]);
theta[BASE_NORMAL_IDX] = FastACosPos(NdotV[BASE_NORMAL_IDX]);

preLightData.TdotV = TdotV;
preLightData.BdotV = BdotV;
#endif
// perceptualRoughness is use as input and output here
float3 outNormal;
float outPerceptualRoughness;

if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_IRIDESCENCE))
{
float3 fresnelIridescent = preLightData.fresnelIridforCalculatingFGD;
#ifdef IRIDESCENCE_RECOMPUTE_PERLIGHT
float topIor = 1.0; // default air on top.
fresnelIridescent = EvalIridescence(topIor, savedLdotH, bsdfData.iridescenceThickness, bsdfData.fresnel0);

float NdotV = ClampNdotV(unclampedNdotV);
float LdotV = dot(L, V);
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
// TODOENERGYDIFFUSE:
// TODOENERGYDIFFUSE:
// but we would need to balance it with the term used from e_Ti0 == preLightData.diffuseEnergy, as
// but we would need to balance it with the term used from e_Ti0 == preLightData.diffuseEnergy, as
// If we use the same term, we could just apply it in the end to diffuse light since coat can't produce diffuse lighting,
// so diffuse lighting from the base interface should all have the term applied. (Then, we would need to make sure the
// If we use the same term, we could just apply it in the end to diffuse light since coat can't produce diffuse lighting,
// so diffuse lighting from the base interface should all have the term applied. (Then, we would need to make sure the
// energy term is separate from diffuseFGD.) But the terms are not the same:
//
// Even without energy conservation, preLightData.diffuseEnergyTransmitted should still != preLightData.diffuseEnergy

float len = lightData.size.x;
float3 T = lightData.right;
float3 unL = lightData.positionWS - positionWS;
float3 unL = lightData.positionRWS - positionWS;
// Pick the major axis of the ellipsoid.
float3 axis = lightData.right;

lightData.specularScale *= intensity;
// Translate the light s.t. the shaded point is at the origin of the coordinate system.
lightData.positionWS -= positionWS;
lightData.positionRWS -= positionWS;
float3 P1 = lightData.positionWS - T * (0.5 * len);
float3 P2 = lightData.positionWS + T * (0.5 * len);
float3 P1 = lightData.positionRWS - T * (0.5 * len);
float3 P2 = lightData.positionRWS + T * (0.5 * len);
// Rotate the endpoints into the local coordinate system.
float3 localP1 = mul(P1, transpose(preLightData.orthoBasisViewNormal[BASE_NORMAL_IDX]));

ltcValue *= lightData.diffuseScale;
// TODOENERGYDIFFUSE: In Lit with Lambert, there's no diffuseFGD, it is one. In our case, we also
// need a diffuse energy term when vlayered. See preLightData.diffuseEnergyTransmitted
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse += bsdfData.transmittance * ltcValue;

IntegrateBSDF_AreaRef(V, positionWS, preLightData, lightData, bsdfData,
lighting.diffuse, lighting.specular);
#else
float3 unL = lightData.positionWS - positionWS;
float3 unL = lightData.positionRWS - positionWS;
if (dot(lightData.forward, unL) >= 0.0001)
{

lightData.specularScale *= intensity;
// Translate the light s.t. the shaded point is at the origin of the coordinate system.
lightData.positionWS -= positionWS;
lightData.positionRWS -= positionWS;
lightVerts[0] = lightData.positionWS + lightData.right * halfWidth + lightData.up * halfHeight;
lightVerts[1] = lightData.positionWS + lightData.right * halfWidth + lightData.up * -halfHeight;
lightVerts[2] = lightData.positionWS + lightData.right * -halfWidth + lightData.up * -halfHeight;
lightVerts[3] = lightData.positionWS + lightData.right * -halfWidth + lightData.up * halfHeight;
lightVerts[0] = lightData.positionRWS + lightData.right * halfWidth + lightData.up * halfHeight;
lightVerts[1] = lightData.positionRWS + lightData.right * halfWidth + lightData.up * -halfHeight;
lightVerts[2] = lightData.positionRWS + lightData.right * -halfWidth + lightData.up * -halfHeight;
lightVerts[3] = lightData.positionRWS + lightData.right * -halfWidth + lightData.up * halfHeight;
// Rotate the endpoints into the local coordinate system.
float4x3 localLightVerts = mul(lightVerts, transpose(preLightData.orthoBasisViewNormal[BASE_NORMAL_IDX]));

4
com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.compute


// Definitions
//--------------------------------------------------------------------------------------------------
#pragma kernel SubsurfaceScatteringQualityNormal SubsurfaceScattering=SubsurfaceScatteringQualityNormal SSS_ENABLE_NEAR_FIELD=0
#pragma kernel SubsurfaceScatteringQualityUltra SubsurfaceScattering=SubsurfaceScatteringQualityUltra SSS_ENABLE_NEAR_FIELD=1
#pragma kernel SubsurfaceScatteringMQ SubsurfaceScattering=SubsurfaceScatteringMQ SSS_ENABLE_NEAR_FIELD=0
#pragma kernel SubsurfaceScatteringHQ SubsurfaceScattering=SubsurfaceScatteringHQ SSS_ENABLE_NEAR_FIELD=1
// #pragma enable_d3d11_debug_symbols
// TODO: use sharp load hoisting on PS4.

2
com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs


public void Build(HDRenderPipelineAsset hdAsset)
{
// Disney SSS (compute + combine)
string kernelName = hdAsset.renderPipelineSettings.enableUltraQualitySSS ? "SubsurfaceScatteringQualityUltra" : "SubsurfaceScatteringQualityNormal";
string kernelName = hdAsset.renderPipelineSettings.increaseSssSampleCount ? "SubsurfaceScatteringHQ" : "SubsurfaceScatteringMQ";
m_SubsurfaceScatteringCS = hdAsset.renderPipelineResources.subsurfaceScatteringCS;
m_SubsurfaceScatteringKernel = m_SubsurfaceScatteringCS.FindKernel(kernelName);
m_CombineLightingPass = CoreUtils.CreateEngineMaterial(hdAsset.renderPipelineResources.combineLighting);

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


m_DbufferManager.CreateBuffers();
m_SSSBufferManager.InitSSSBuffers(m_GbufferManager, m_Asset.renderPipelineSettings);
m_NormalBufferManager.InitNormalBuffers(m_GbufferManager, m_Asset.renderPipelineSettings);
m_NormalBufferManager.InitNormalBuffers(m_GbufferManager, m_Asset.renderPipelineSettings);
m_CameraColorBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, enableRandomWrite: true, enableMSAA: true, name: "CameraColor");
m_CameraSssDiffuseLightingBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.RGB111110Float, sRGB: false, enableRandomWrite: true, enableMSAA: true, name: "CameraSSSDiffuseLighting");

var postProcessLayer = camera.GetComponent<PostProcessLayer>();
// Disable post process if we enable debug mode or if the post process layer is disabled
if (m_CurrentDebugDisplaySettings.IsDebugDisplayRemovePostprocess() || !CoreUtils.IsPostProcessingActive(postProcessLayer))
if (m_CurrentDebugDisplaySettings.IsDebugDisplayRemovePostprocess() || !HDUtils.IsPostProcessingActive(postProcessLayer))
{
currentFrameSettings.enablePostprocess = false;
}

using (new ProfilingSample(cmd, m_DbufferManager.EnableDBUffer ? "Depth Prepass (deferred) force by DBuffer" : "Depth Prepass (deferred)", CustomSamplerId.DepthPrepass.GetSampler()))
{
cmd.DisableShaderKeyword("WRITE_NORMAL_BUFFER"); // Note: This only disable the output of normal buffer for Lit shader, not the other shader that don't use multicompile
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraDepthStencilBuffer);
// First deferred material

else
{
HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer);
if ((hdCamera.frameSettings.enableDBuffer) && (DecalSystem.m_DecalDatasCount > 0)) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
// decal datas count is 0 if no decals affect transparency
if ((hdCamera.frameSettings.enableDBuffer) && (DecalSystem.m_DecalDatasCount > 0)) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
// decal datas count is 0 if no decals affect transparency
{
DecalSystem.instance.SetAtlas(cmd); // for clustered decals
}

15
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/HDUtils.cs


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

{
var additionalCameraData = camera.GetComponent<HDAdditionalCameraData>();
return camera.cameraType == CameraType.Preview && ((additionalCameraData == null) || (additionalCameraData && !additionalCameraData.isEditorCameraPreview));
}
// Post-processing misc
public static bool IsPostProcessingActive(PostProcessLayer layer)
{
return layer != null
&& layer.enabled;
}
public static bool IsTemporalAntialiasingActive(PostProcessLayer layer)
{
return IsPostProcessingActive(layer)
&& layer.antialiasingMode == PostProcessLayer.Antialiasing.TemporalAntialiasing
&& layer.temporalAntialiasing.IsSupported();
}
}
}

12
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/Settings/FrameSettings.cs


public bool enableSubsurfaceScattering = true;
public bool enableTransmission = true; // Caution: this is only for debug, it doesn't save the cost of Transmission execution
public bool enableAtmosphericScattering = true;
public bool enableVolumetric = true;
public bool enableVolumetrics = true;
// Setup by system
public float diffuseGlobalDimmer = 1.0f;

frameSettings.enableSubsurfaceScattering = this.enableSubsurfaceScattering;
frameSettings.enableTransmission = this.enableTransmission;
frameSettings.enableAtmosphericScattering = this.enableAtmosphericScattering;
frameSettings.enableVolumetric = this.enableVolumetric;
frameSettings.enableVolumetrics = this.enableVolumetrics;
frameSettings.diffuseGlobalDimmer = this.diffuseGlobalDimmer;
frameSettings.specularGlobalDimmer = this.specularGlobalDimmer;

if (!CoreUtils.IsSceneViewFogEnabled(camera))
aggregate.enableAtmosphericScattering = false;
// Volumetric are disabled if there is no atmospheric scattering
aggregate.enableVolumetric = srcFrameSettings.enableVolumetric && renderPipelineSettings.supportVolumetric && aggregate.enableAtmosphericScattering;
aggregate.enableVolumetrics = srcFrameSettings.enableVolumetrics && renderPipelineSettings.supportVolumetrics && aggregate.enableAtmosphericScattering;
aggregate.enableVolumetric = false;
aggregate.enableVolumetrics = false;
// We have to fall back to forward-only rendering when scene view is using wireframe rendering mode
// as rendering everything in wireframe + deferred do not play well together

aggregate.enableSSR = false;
aggregate.enableSSAO = false;
aggregate.enableAtmosphericScattering = false;
aggregate.enableVolumetric = false;
aggregate.enableVolumetrics = false;
aggregate.enableTransparentPrepass = false;
aggregate.enableMotionVectors = false;
aggregate.enableObjectMotionVectors = false;

new DebugUI.BoolField { displayName = "Enable Contact Shadows", getter = () => frameSettings.enableContactShadows, setter = value => frameSettings.enableContactShadows = value },
new DebugUI.BoolField { displayName = "Enable ShadowMask", getter = () => frameSettings.enableShadowMask, setter = value => frameSettings.enableShadowMask = value },
new DebugUI.BoolField { displayName = "Enable Atmospheric Scattering", getter = () => frameSettings.enableAtmosphericScattering, setter = value => frameSettings.enableAtmosphericScattering = value },
new DebugUI.BoolField { displayName = " Enable volumetric", getter = () => frameSettings.enableVolumetric, setter = value => frameSettings.enableVolumetric = value },
new DebugUI.BoolField { displayName = "Enable volumetrics", getter = () => frameSettings.enableVolumetrics, setter = value => frameSettings.enableVolumetrics = value },
}
}
});

5
com.unity.render-pipelines.high-definition/HDRP/RenderPipeline/Settings/RenderPipelineSettings.cs


public bool supportSubsurfaceScattering = true;
[FormerlySerializedAs("supportForwardOnly")]
public bool supportOnlyForward = false;
public bool enableUltraQualitySSS = false;
public bool supportVolumetric = true;
public bool increaseSssSampleCount = false;
public bool supportVolumetrics = true;
public bool increaseResolutionOfVolumetrics = false;
// reduce variant
public bool supportRuntimeDebugDisplay = true;

6
com.unity.render-pipelines.high-definition/HDRP/ShaderConfig.cs


public enum ShaderOptions
{
CameraRelativeRendering = 1, // Rendering sets the origin of the world to the position of the primary (scene view) camera
UseDisneySSS = 1, // Allow to chose between Burley Normalized Diffusion (Multi + Fix direction single scattering) or Jimenez diffusion approximation (Multiscattering only - More blurry) for Subsurface scattering
VolumetricLightingPreset = 1 // 0 = disabled, 1 = normal, 2 = ultra
UseDisneySSS = 1 // Allow to chose between Burley Normalized Diffusion (Multi + Fix direction single scattering) or Jimenez diffusion approximation (Multiscattering only - More blurry) for Subsurface scattering
};
// Note: #define can't be use in include file in C# so we chose this way to configure both C# and hlsl

public const int k_UseDisneySSS = (int)ShaderOptions.UseDisneySSS;
public static int s_UseDisneySSS = (int)ShaderOptions.UseDisneySSS;
public const int k_VolumetricLightingPreset = (int)ShaderOptions.VolumetricLightingPreset;
public static int s_VolumetricLightingPreset = (int)ShaderOptions.VolumetricLightingPreset;
}
}

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


//
#define SHADEROPTIONS_CAMERA_RELATIVE_RENDERING (1)
#define SHADEROPTIONS_USE_DISNEY_SSS (1)
#define SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET (1)
#endif

2
com.unity.render-pipelines.high-definition/HDRP/Sky/AtmosphericScattering/AtmosphericScattering.cs


// In case volumetric lighting is enabled, we need to make sure that all rendering passes
// (not just the atmospheric scattering one) receive neutral parameters.
if (hdCamera.frameSettings.enableVolumetric)
if (hdCamera.frameSettings.enableVolumetrics)
{
var data = DensityVolumeData.GetNeutralValues();

4
com.unity.render-pipelines.high-definition/HDRP/Sky/AtmosphericScattering/AtmosphericScattering.hlsl


#include "../../ShaderVariables.hlsl"
#include "../../Lighting/Volumetrics/VBuffer.hlsl"
#if (SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET != 0)
#endif
CBUFFER_START(AtmosphericScattering)
int _AtmosphericScatteringType;

}
case FOGTYPE_VOLUMETRIC:
{
#if (SHADEROPTIONS_VOLUMETRIC_LIGHTING_PRESET != 0)
float4 volFog = SampleVolumetricLighting(TEXTURE3D_PARAM(_VBufferLighting, s_linear_clamp_sampler),
posInput.positionNDC,
posInput.linearDepth,

fogFactor = 1 - volFog.a; // Opacity from transmittance
fogColor = volFog.rgb * min(rcp(fogFactor), FLT_MAX); // Un-premultiply, clamp to avoid (0 * INF = NaN)
#endif
break;
}
}

22
com.unity.render-pipelines.high-definition/HDRP/Sky/AtmosphericScattering/VolumetricFog.cs


{
public class VolumetricFog : AtmosphericScattering
{
public ColorParameter albedo = new ColorParameter(new Color(0.5f, 0.5f, 0.5f));
public MinFloatParameter meanFreePath = new MinFloatParameter(1000000.0f, 1.0f);
public ClampedFloatParameter anisotropy = new ClampedFloatParameter(0.0f, -1.0f, 1.0f);
public ColorParameter albedo = new ColorParameter(Color.white);
public MinFloatParameter meanFreePath = new MinFloatParameter(1000000.0f, 1.0f);
public ClampedFloatParameter anisotropy = new ClampedFloatParameter(0.0f, -1.0f, 1.0f);
public ClampedFloatParameter globalLightProbeDimmer = new ClampedFloatParameter(1.0f, 0.0f, 1.0f);
public override void Override(VolumeComponent state, float interpFactor)
public override void Override(VolumeComponent state, float lerpFactor)
{
VolumetricFog other = state as VolumetricFog;

float otherExtinction = VolumeRenderingUtils.ExtinctionFromMeanFreePath(other.meanFreePath);
Vector3 otherScattering = VolumeRenderingUtils.ScatteringFromExtinctionAndAlbedo(otherExtinction, (Vector3)(Vector4)other.albedo.value);
float blendExtinction = Mathf.Lerp(otherExtinction, thisExtinction, interpFactor);
Vector3 blendScattering = Vector3.Lerp(otherScattering, thisScattering, interpFactor);
float blendAsymmetry = Mathf.Lerp(other.anisotropy, anisotropy, interpFactor);
float blendExtinction = Mathf.Lerp(otherExtinction, thisExtinction, lerpFactor);
Vector3 blendScattering = Vector3.Lerp(otherScattering, thisScattering, lerpFactor);
float blendAsymmetry = Mathf.Lerp(other.anisotropy, anisotropy, lerpFactor);
float blendDimmer = Mathf.Lerp(other.globalLightProbeDimmer, globalLightProbeDimmer, lerpFactor);
blendAlbedo.a = 1.0f;
if (meanFreePath.overrideState)

if (anisotropy.overrideState)
{
other.anisotropy.value = blendAsymmetry;
}
if (globalLightProbeDimmer.overrideState)
{
other.globalLightProbeDimmer.value = blendDimmer;
}
}

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


- Updated the UI for the Lighweight pipeline asset.
### Fixed
- PS4 compiler error
- Fixed VR multiview rendering by forcing MSAA to be off. There's a current issue in engine that breaks MSAA and Texture2DArray.
- Fixed UnityPerDraw CB layout
- GLCore compute buffer compiler error
- Occlusion strength not being applied on LW standard shaders

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


cameraData.isSceneViewCamera = camera.cameraType == CameraType.SceneView;
cameraData.isOffscreenRender = camera.targetTexture != null && !cameraData.isSceneViewCamera;
cameraData.isStereoEnabled = IsStereoEnabled(camera);
#if !UNITY_SWITCH
// TODO: There's currently an issue in engine side that breaks MSAA with texture2DArray.
// for now we force msaa disabled when using texture2DArray. This fixes VR multiple and single pass instanced modes.
if (cameraData.isStereoEnabled && XRSettings.eyeTextureDesc.dimension == TextureDimension.Tex2DArray)
cameraData.msaaSamples = 1;
#endif
cameraData.isHdrEnabled = camera.allowHDR && pipelineAsset.supportsHDR;
cameraData.postProcessLayer = camera.GetComponent<PostProcessLayer>();

if (cameraData.isStereoEnabled)
{
cameraData.renderScale = XRSettings.eyeTextureResolutionScale;
} else
}
else
#endif
{
cameraData.renderScale = pipelineAsset.renderScale;

2
com.unity.render-pipelines.lightweight/LWRP/ShaderLibrary/Terrain/InputSurfaceGrass.hlsl


vertex.xz -= waveMove.xz * _WaveAndDistance.z;
// apply color animation
half3 waveColor = lerp (0.5, _WavingTint.rgb, lighting);
half3 waveColor = lerp (real3(0.5, 0.5, 0.5), _WavingTint.rgb, lighting);
// Fade the grass out before detail distance.
// Saturate because Radeon HD drivers on OS X 10.4.10 don't saturate vertex colors properly.

7
com.unity.shadergraph/CHANGELOG.md


This adds gradient functionality via two new nodes. The Sample Gradient node samples a gradient given a Time parameter. You can define this gradient on the Gradient slot control view. The Gradient Asset node defines a gradient that can be sampled by multiple Sample Gradient nodes using different Time parameters.
### Sphere Mask Node
![](.data/sphereMask.png)
With this node, you can create a sphere mask. Indicate the starting coordinate and center point. The sphere mask uses these with the **Radius** and **Hardness** parameters. Sphere mask functionality works in both 2D and 3D spaces, and is based on the vector coordinates in the **Coords and Center** input.
### Texture3D and Texture2D Array
![](.data/texture_nodes.png)

- Deserialization of subgraphs now works correctly.
- Sub graphs are now suffixed with (sub), so you can tell them apart from other nodes.
- The preview of a node does not obstruct the selection outliner anymore.
- You can now copy, paste, and duplicate sub-graph nodes with vector type input ports.
- If the current render pipeline is not compatible, master nodes now display an error badge.
- The preview shader now only considers the current render pipeline. Because of this there is less code to compile, and therefore the preview shader will compile faster.
- When you rename a shader graph or sub shader graph locally on your disk, the title of the Shader Graph window, black board, and preview also updates.

4
com.unity.shadergraph/Editor/Data/Graphs/Vector1MaterialSlot.cs


[SerializeField]
float m_DefaultValue;
[SerializeField]
{}
{
}
public Vector1MaterialSlot(
int slotId,

4
com.unity.shadergraph/Editor/Data/Graphs/Vector2MaterialSlot.cs


[SerializeField]
Vector2 m_DefaultValue;
[SerializeField]
{}
{
}
public Vector2MaterialSlot(
int slotId,

1
com.unity.shadergraph/Editor/Data/Graphs/Vector3MaterialSlot.cs


[SerializeField]
private Vector3 m_DefaultValue;
[SerializeField]
string[] m_Labels;
public Vector3MaterialSlot()

3
com.unity.shadergraph/.data/sphereMask.PNG


version https://git-lfs.github.com/spec/v1
oid sha256:8df3a610b0b2a3f8d3b6a2b9ddb563c3a74e682055b53bc728ac7f795870d9ad
size 91474

39
com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/SphereMaskNode.cs


using System.Reflection;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Title("Math", "Vector", "Sphere Mask")]
public class SphereMaskNode : CodeFunctionNode
{
public SphereMaskNode()
{
name = "Sphere Mask";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Sphere-Mask-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("SphereMask", BindingFlags.Static | BindingFlags.NonPublic);
}
static string SphereMask(
[Slot(0, Binding.None)] DynamicDimensionVector Coords,
[Slot(1, Binding.None, 0.5f, 0.5f, 0.5f, 0.5f)] DynamicDimensionVector Center,
[Slot(2, Binding.None, 0.1f, 0.1f, 0.1f, 0.1f)] Vector1 Radius,
[Slot(3, Binding.None, 0.8f, 0.8f, 0.8f, 0.8f)] Vector1 Hardness,
[Slot(4, Binding.None)] out DynamicDimensionVector Out)
{
return
@"
{
Out = 1 - saturate((distance(Coords, Center) - Radius) / (1 - Hardness));
}
";
}
}
}

11
com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/SphereMaskNode.cs.meta


fileFormatVersion: 2
guid: 6b31e904eeb9a604b9145c218287ad1e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存