浏览代码

Merge branch 'master' of https://github.com/Unity-Technologies/ScriptableRenderPipeline into gpu_terrain. Will fix merge afterwards.

/main
Yao Xiaoling 6 年前
当前提交
7ba05ba9
共有 5552 个文件被更改,包括 2850 次插入2115 次删除
  1. 24
      .gitignore
  2. 17
      .gitmodules
  3. 18
      README.md
  4. 164
      build.py
  5. 42
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalUI.cs
  6. 43
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalProjectorComponentEditor.cs
  7. 6
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/DiffusionProfile/DiffusionProfileSettingsEditor.cs
  8. 49
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Unlit/UnlitsToHDUnlitUpgrader.cs
  9. 10
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Unlit/UnlitUI.cs
  10. 50
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Unlit/BaseUnlitUI.cs
  11. 90
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs
  12. 42
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/LitUI.cs
  13. 184
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/BaseLitUI.cs
  14. 386
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/StackLit/StackLitUI.cs
  15. 63
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/StackLit/BaseMaterialUI.cs
  16. 9
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/LayeredLit/LayeredLitUI.cs
  17. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDBaseEditor.cs
  18. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDEditorCLI.cs
  19. 44
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDEditorUtils.cs
  20. 6
      com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/VisualEnvironmentEditor.cs
  21. 6
      com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/SkySettingsEditor.cs
  22. 9
      com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/BakingSkyEditor.cs
  23. 22
      com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/AtmosphericScattering/VolumetricFogEditor.cs
  24. 4
      com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/AtmosphericScattering/LinearFogEditor.cs
  25. 6
      com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/AtmosphericScattering/AtmosphericScatteringEditor.cs
  26. 3
      com.unity.render-pipelines.high-definition/HDRP/Editor/com.unity.render-pipelines.high-definition.Editor.asmdef
  27. 99
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipelineResources/ReflectionProbesPreview.shader
  28. 14
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDShaderIncludePaths.cs
  29. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/BaseUI.cs
  30. 6
      com.unity.render-pipelines.high-definition/HDRP/Editor/Shadows/HDShadowSettingsEditor.cs
  31. 4
      com.unity.render-pipelines.high-definition/HDRP/Editor/Shadows/ContactShadowsEditor.cs
  32. 27
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/ShadowInitParametersUI.cs
  33. 9
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedShadowInitParameters.cs
  34. 44
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedRenderPipelineSettings.cs
  35. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedLightLoopSettings.cs
  36. 4
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedHDRenderPipelineAsset.cs
  37. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedGlobalLightLoopSettings.cs
  38. 22
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedGlobalDecalSettings.cs
  39. 8
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedFrameSettings.cs
  40. 77
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/RenderPipelineSettingsUI.cs
  41. 12
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/LightLoopSettingsUI.cs
  42. 17
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/GlobalLightLoopSettingsUI.cs
  43. 33
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/GlobalDecalSettingsUI.cs
  44. 85
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/FrameSettingsUI.cs
  45. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Camera/SerializedHDCamera.cs
  46. 105
      com.unity.render-pipelines.high-definition/HDRP/Editor/Camera/HDCameraUI.cs
  47. 5
      com.unity.render-pipelines.high-definition/HDRP/Editor/Camera/HDCameraEditor.cs
  48. 10
      com.unity.render-pipelines.high-definition/HDRP/Editor/Camera/HDCameraEditor.Handlers.cs
  49. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/SerializedReflectionProxyVolumeComponent.cs
  50. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/SerializedProxyVolume.cs
  51. 50
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/SerializedInfluenceVolume.cs
  52. 11
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/ReflectionProxyVolumeComponentUI.cs
  53. 20
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/ProxyVolumeUI.cs
  54. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/ProxyVolumeEditor.cs
  55. 56
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.cs
  56. 167
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Handles.cs
  57. 26
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Gizmos.cs
  58. 153
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Drawers.cs
  59. 10
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/SerializedPlanarReflectionProbe.cs
  60. 50
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/SerializedHDReflectionProbe.cs
  61. 38
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/ScreenSpaceRefractionEditor.cs
  62. 11
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.cs
  63. 138
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Handles.cs
  64. 186
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeUI.Drawers.cs
  65. 12
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/PlanarReflectionProbeEditor.cs
  66. 39
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.cs
  67. 396
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeUI.Drawers.cs
  68. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditorUtility.cs
  69. 9
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs
  70. 10
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Preview.cs
  71. 382
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDReflectionProbeEditor.Handles.cs
  72. 6
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDCubemapInspector.cs
  73. 16
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/EditorReflectionSystemGUI.cs
  74. 18
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/EditorReflectionSystem.cs
  75. 378
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightEditor.cs
  76. 9
      com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/HDLightEditor.Styles.cs
  77. 8
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDAssetFactory.cs
  78. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/BuildProcessors/HDRPreprocessShaders.cs.meta
  79. 102
      com.unity.render-pipelines.high-definition/HDRP/Editor/BuildProcessors/HDRPreprocessShaders.cs
  80. 2
      com.unity.render-pipelines.high-definition/HDRP/Editor/BuildProcessors/HDRPPreprocessBuild.cs.meta
  81. 4
      com.unity.render-pipelines.high-definition/HDRP/Editor/BuildProcessors/HDRPPreprocessBuild.cs
  82. 8
      com.unity.render-pipelines.high-definition/HDRP/Material/Builtin/BuiltinData.hlsl
  83. 18
      com.unity.render-pipelines.high-definition/HDRP/Material/Builtin/BuiltinData.cs.hlsl
  84. 6
      com.unity.render-pipelines.high-definition/HDRP/Material/Builtin/BuiltinData.cs
  85. 70
      com.unity.render-pipelines.high-definition/HDRP/Material/GGXConvolution/RuntimeFilterIBL.cs
  86. 18
      com.unity.render-pipelines.high-definition/HDRP/Material/DiffusionProfile/DiffusionProfileSettings.cs
  87. 3
      com.unity.render-pipelines.high-definition/HDRP/Material/GBufferManager.cs
  88. 17
      com.unity.render-pipelines.high-definition/HDRP/Material/MaterialUtilities.hlsl
  89. 14
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/ShaderPass/DecalSharePass.hlsl
  90. 208
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalUtilities.hlsl
  91. 5
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalProperties.hlsl
  92. 60
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalData.hlsl
  93. 58
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.shader
  94. 51
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.hlsl
  95. 33
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs.hlsl
  96. 39
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.cs
  97. 10
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DBufferManager.cs
  98. 22
      com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs
  99. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.shader
  100. 114
      com.unity.render-pipelines.high-definition/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl

24
.gitignore


artifacts/**
build/**
DataSource/*
Library/*
obj/*
Temp/*
[Aa]rtifacts/
[Bb]uild/
[Ll]ibrary/
[Oo]bj/
[Tt]emp/
[Ss]treaming[Aa]ssets/
[Aa]ctual[Ii]mages/
[Ll]og/
[Aa]ctual[Ii]mages.meta
[Ss]treaming[Aa]ssets.meta
.vs
.vscode
.idea
.DS_Store
*.aspx
*.browser

*.sublime-workspace
*.suo
*.userprefs
.npmrc
ShaderGraph/DebugOutput.meta
ShaderGraph/DebugOutput/**
ShaderGraph/Testing/IntegrationTests/.Failed
TestProjects/ShaderGraph/ProjectSettings/ProjectVersion.txt

17
.gitmodules


[submodule "PostProcessing"]
path = PostProcessing
url = https://github.com/Unity-Technologies/PostProcessing
[submodule "com.unity.postprocessing"]
path = com.unity.postprocessing
url = https://github.com/Unity-Technologies/PostProcessing.git
[submodule "ShaderGraph"]
path = ShaderGraph
url = https://github.com/Unity-Technologies/ShaderGraph
[submodule "Tests/UTF_Core"]
path = Tests/UTF_Core
url = https://github.com/Unity-Technologies/UTF_Core.git
[submodule "Tests/UTF_Tests_HDRP"]
path = Tests/UTF_Tests_HDRP
url = https://github.com/Unity-Technologies/UTF_Tests_HDRP.git

18
README.md


## NOTE: We are migrating reported issues to fogbugz. Please log issues there.
The Scriptable Render Pipeline (SRP) is a new Unity feature in active development. SRP has been designed to give artists and developers the tools they need to create modern, high-fidelity graphics in Unity. Including a built-in Lightweight Render Pipeline for use on all platforms, and a High Definition Render Pipeline (HDRP) for use on compute shader compatible platforms. We hope to release both of these versions in beta with Unity version 2018.1.
The Scriptable Render Pipeline (SRP) is a new Unity feature in active development. SRP has been designed to give artists and developers the tools they need to create modern, high-fidelity graphics in Unity. Including a built-in Lightweight Render Pipeline for use on all platforms, and a High Definition Render Pipeline (HDRP) for use on compute shader compatible platforms. These features are available in Unity 2018.1+.
We are committed to an open and transparent development process, and as such you are welcome to take a look around if you are really curious, but we cannot provide support for this feature yet.
We are committed to an open and transparent development process, and as such you are welcome to take a look around if you are really curious.
This feature is currently a work in progress. We cannot promise that features will work as expected in their current state. Some features may change or be removed before we move to a full release.
This feature is currently in preview. Some features may change or be removed before we move to a full release.
[Lightweight Pipeline Blogpost](https://blogs.unity3d.com/2018/02/21/the-lightweight-render-pipeline-optimizing-real-time-performance/)

__Note: The Master branch is our current development branch and may not work on the latest publicly available version of Unity. You should always use the latest release tag and latest Unity beta version for testing purposes.__
To use the latest version of the SRP, follow the instructions below:
This repository consists of a folder that needs to be placed in the Assets\ folder of your Unity project. We recommend creating a new project to test SRP. Do not clone this repo into an existing project unless you want to break it, or unless you are updating to a newer version of the SRP repo. Your project's `packages.json` file (in either `UnityPackageManager/` or `Packages/`) does not have a dependency on any of the packages in this repository or the contained submodules.
This repository consists of a folder that should be cloned outside the Assets\ folder of your Unity project. We recommend creating a new project to test SRP. Do not clone this repo into an existing project unless you want to break it, or unless you are updating to a newer version of the SRP repo.
After cloning you will need to edit your project's `packages.json` file (in either `UnityPackageManager/` or `Packages/`) to point to the SRP submodules you wish to use. See: https://github.com/Unity-Technologies/ScriptableRenderPipeline/blob/build/automation/TestProjects/GraphicsTests/Packages/manifest.json
This will link your project to the specific version of SRP you have cloned.
You can use the GitHub desktop app to clone the latest version of the SRP repo or you can use GitHub console commands.

3. Enter the following URL: https://github.com/Unity-Technologies/ScriptableRenderPipeline
4. Click the __Choose…__ button to navigate to your project’s Asset folder.
4. Click the __Choose…__ button to navigate to your project’s base folder.
5. Click the __Clone__ button.
After the repo has been cloned you will need to run the following console commands from the ScriptableRenderPipeline folder:

Enter the following commands in your console application of choice:
```
> cd <Path to your Unity project>/Assets
> cd <Path to your Unity project>
> git clone https://github.com/Unity-Technologies/ScriptableRenderPipeline
> cd ScriptableRenderPipeline
> git checkout Unity-2018.1.0b2 (or the latest tag)

164
build.py


#!/usr/bin/python -B
import os
import json
import platform
import shutil
import subprocess
import textwrap
sub_packages = {}
sub_package_folders = {}
publish_order = []
("com.unity.render-pipelines.core", os.path.join("ScriptableRenderPipeline", "Core")),
("com.unity.render-pipelines.high-definition", os.path.join("ScriptableRenderPipeline", "HDRenderPipeline")),
("com.unity.render-pipelines.lightweight", os.path.join("ScriptableRenderPipeline", "LightweightPipeline"))
("com.unity.render-pipelines.core", os.path.join("com.unity.render-pipelines.core")),
("com.unity.render-pipelines.lightweight", os.path.join("com.unity.render-pipelines.lightweight")),
("com.unity.render-pipelines.high-definition", os.path.join("com.unity.render-pipelines.high-definition")),
("com.unity.shadergraph", os.path.join("com.unity.shadergraph")),
("com.unity.postprocessing", os.path.join("com.unity.postprocessing")),
("com.unity.testframework.graphics", os.path.join("com.unity.testframework.graphics")),
def prepare(logger):
file_path = os.path.join("./ScriptableRenderPipeline", "master-package.json")
if os.path.isfile(file_path):
logger.info("Found master package file: {}".format(file_path))
with open(file_path) as file:
try:
master_package = json.load(file)
except json.JSONDecodeError as e:
logger.critical(e)
exit(1)
potential_folders = master_package["subPackages"] if "subPackages" in master_package else []
for item in potential_folders:
file_path = os.path.join("./ScriptableRenderPipeline", item, "sub-package.json")
if os.path.isfile(file_path):
logger.info("Found sub-package file: {}".format(file_path))
with open(file_path) as file:
try:
sub_package = json.load(file)
sub_packages[sub_package["name"]] = sub_package
sub_package_folders[sub_package["name"]
] = os.path.join("./ScriptableRenderPipeline", item)
except json.JSONDecodeError as e:
logger.critical("Error: {}".format(e))
if not sub_packages:
logger.critical("Error: No sub-packages found.")
exit(1)
if "version" not in master_package:
logger.critical("Master package must contain a \"version\" field")
exit(1)
print("Propagating master package version to sub-packages")
for sub_package in sub_packages.values():
sub_package["version"] = master_package["version"]
if "unity" in master_package:
print("Propagating master package Unity version to sub-packages")
for sub_package in sub_packages.values():
sub_package["unity"] = master_package["unity"]
if "dependencies" in master_package and master_package["dependencies"]:
print("Propagating shared dependencies:")
for name, version in master_package["dependencies"].items():
logger.info(" {}@{}".format(name, version))
for sub_package in sub_packages.values():
if "dependencies" not in sub_package or not sub_package["dependencies"]:
sub_package["dependencies"] = {}
for name, version in master_package["dependencies"].items():
sub_package["dependencies"][name] = version
logger.info("Creating dependency tree:")
dependency_list = {}
dependency_tree = {}
for i, sub_package in enumerate(sub_packages.values()):
dependency_list[sub_package["name"]] = {}
for i, sub_package in enumerate(sub_packages.values()):
if "subDependencies" in sub_package and sub_package["subDependencies"]:
for dependency in sub_package["subDependencies"]:
dependency_list[dependency][sub_package["name"]
] = dependency_list[sub_package["name"]]
else:
dependency_tree[sub_package["name"]
] = dependency_list[sub_package["name"]]
if not dependency_tree:
logger.critical("Dependency tree is empty. You might have a circular reference.")
exit(1)
def print_dependency_tree(tree, indent):
for key, sub_tree in tree.items():
print(key, " " * indent)
print_dependency_tree(sub_tree, indent + 1)
print_dependency_tree(dependency_tree, 1)
logger.info("Creating publish order:")
visited = set()
def fill_publish_order(tree):
for key, sub_tree in tree.items():
if key not in visited:
publish_order.append(key)
fill_publish_order(sub_tree)
fill_publish_order(dependency_tree)
for name in publish_order:
logger.info(" {}".format(name))
print "Resolving dependencies between sub-packages:"
for sub_package in sub_packages.values():
if "dependencies" not in sub_package or not sub_package["dependencies"]:
sub_package["dependencies"] = {}
if "subDependencies" in sub_package and sub_package["subDependencies"]:
logger.info(" {}:".format(sub_package["name"]))
for sub_dependency in sub_package["subDependencies"]:
sub_package["dependencies"][sub_dependency] = master_package["version"]
logger.info(" {}@{}".format(sub_dependency,
sub_package["dependencies"][sub_dependency]))
del sub_package["subDependencies"]
logger.info("Writing package files:")
for name in publish_order:
sub_package = sub_packages[name]
package_path = os.path.join(sub_package_folders[name], "package.json")
logger.info(" {}:".format(package_path))
with open(package_path, 'w') as file:
json.dump(sub_package, file, indent=4, sort_keys=True)
import unity_package_build
for name in publish_order:
package_path = os.path.join(sub_package_folders[name])
unity_package_build.copy_file_to_project("LICENSE.md", ".", package_path, logger)
unity_package_build.copy_file_to_project("CHANGELOG.md", ".", package_path, logger)
def cleanup(logger):
logger.info("Reverting temporary file changes:")
files = []
for name in publish_order:
folder = sub_package_folders[name]
files.append(os.path.join(folder, "package.json"))
for file in files:
logger.info(" {}".format(file))
subprocess.call(["git", "checkout", file], cwd=".")
# Prepare an empty project for editor tests
def prepare_editor_test_project(repo_path, project_path, logger):
import unity_package_build
dest_path = os.path.join(project_path, "Assets", "ScriptableRenderLoop")
unity_package_build.copy_path_to_project("ImageTemplates", repo_path, dest_path, logger)
unity_package_build.copy_path_to_project("Tests", repo_path, dest_path, logger)
unity_package_build.copy_file_to_project("SRPMARKER", repo_path, dest_path, logger)
unity_package_build.copy_file_to_project("SRPMARKER.meta", repo_path, dest_path, logger)
unity_package_build.copy_file_to_project("ImageTemplates.meta", repo_path, dest_path, logger)
unity_package_build.copy_file_to_project("Tests.meta", repo_path, dest_path, logger)
def test_packages_list():
return [
"com.unity.render-pipelines.core",
"com.unity.render-pipelines.lightweight",
"com.unity.render-pipelines.high-definition",
"com.unity.shadergraph",
"com.unity.postprocessing"
]
try:
import unity_package_build
build_log = unity_package_build.setup()

42
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalUI.cs


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

{
public static string InputsText = "Inputs";
public static GUIContent baseColorText = new GUIContent("Base Color + Blend", "Albedo (RGB) and Blend Factor (A)");
public static GUIContent baseColorText = new GUIContent("Albedo (RGB) and Blend Factor (A)", "Albedo (RGB) and Blend Factor (A)");
public static GUIContent baseColorText2 = new GUIContent("Blend Factor (A)", "Blend Factor (A)");
public static GUIContent maskMapText = new GUIContent("Mask Map - M(R), AO(G), D(B), S(A)", "Mask map");
public static GUIContent maskMapText = new GUIContent("Mask Map - M(R), AO(G), D(B), S(A)", "Mask map");
public static GUIContent BlendText = new GUIContent("Decal Blend", "Whole decal blend");
public static GUIContent AlbedoModeText = new GUIContent("Albedo contribution", "Base color + Blend, Blend only");
protected MaterialProperty baseColor = new MaterialProperty();
protected const string kBaseColor = "_BaseColor";
protected MaterialProperty maskMap = new MaterialProperty();
protected const string kMaskMap = "_MaskMap";
protected MaterialProperty maskMap = new MaterialProperty();
protected const string kMaskMap = "_MaskMap";
protected MaterialProperty albedoMode = new MaterialProperty();
protected const string kAlbedoMode = "_AlbedoMode";
protected MaterialEditor m_MaterialEditor;

void FindMaterialProperties(MaterialProperty[] props)
{
baseColor = FindProperty(kBaseColor, props);
maskMap = FindProperty(kMaskMap, props);
maskMap = FindProperty(kMaskMap, props);
albedoMode = FindProperty(kAlbedoMode, props);
CoreUtils.SetKeyword(material, "_ALBEDOCONTRIBUTION", material.GetFloat(kAlbedoMode) == 1.0f);
CoreUtils.SetKeyword(material, "_MASKMAP", material.GetTexture(kMaskMap));
CoreUtils.SetKeyword(material, "_MASKMAP", material.GetTexture(kMaskMap));
}
protected void SetupMaterialKeywordsAndPassInternal(Material material)

public void ShaderPropertiesGUI(Material material)
{

EditorGUILayout.LabelField(Styles.InputsText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText, baseColorMap);
m_MaterialEditor.ShaderProperty(albedoMode, Styles.AlbedoModeText);
if (material.GetFloat(kAlbedoMode) == 1.0f)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText, baseColorMap, baseColor);
}
else
{
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText2, baseColorMap, baseColor);
}
m_MaterialEditor.TexturePropertySingleLine(Styles.maskMapText, maskMap);
m_MaterialEditor.TexturePropertySingleLine(Styles.maskMapText, maskMap);
}
if (EditorGUI.EndChangeCheck())

// We should always do this call at the end
m_MaterialEditor.serializedObject.ApplyModifiedProperties();
}
}
}

43
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Decal/DecalProjectorComponentEditor.cs


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

private SerializedProperty m_MaterialProperty;
private SerializedProperty m_DrawDistanceProperty;
private SerializedProperty m_FadeScaleProperty;
private SerializedProperty m_UVScaleProperty;
private SerializedProperty m_UVBiasProperty;
private SerializedProperty m_AffectsTransparencyProperty;
public class DecalBoundsHandle : BoxBoundsHandle
public class DecalBoundsHandle : BoxBoundsHandle
{
protected override Bounds OnHandleChanged(HandleDirection handle, Bounds boundsOnClick, Bounds newBounds)
{

public Vector3 m_Translation;
public Vector3 m_Scale;
}
private DecalBoundsHandle m_Handle = new DecalBoundsHandle();
private void OnEnable()

m_MaterialEditor = (MaterialEditor)CreateEditor(m_DecalProjectorComponent.Mat);
m_DecalProjectorComponent.OnMaterialChange += OnMaterialChange;
m_DecalProjectorComponent.OnMaterialChange += OnMaterialChange;
m_UVScaleProperty = serializedObject.FindProperty("m_UVScale");
m_UVBiasProperty = serializedObject.FindProperty("m_UVBias");
m_AffectsTransparencyProperty = serializedObject.FindProperty("m_AffectsTransparency");
private void OnDisable()
{
m_DecalProjectorComponent.OnMaterialChange -= OnMaterialChange;
}
private void OnDisable()
{
m_DecalProjectorComponent.OnMaterialChange -= OnMaterialChange;
}
public void OnMaterialChange()
{
// Update material editor with the new material
m_MaterialEditor = (MaterialEditor)CreateEditor(m_DecalProjectorComponent.Mat);
}
public void OnMaterialChange()
{
// Update material editor with the new material
m_MaterialEditor = (MaterialEditor)CreateEditor(m_DecalProjectorComponent.Mat);
}
void OnSceneGUI()
{

Handles.color = Color.white;
// decal mesh is centered at (0, -0.5, 0)
// zero out the local scale in the matrix so that handle code gives us back the actual scale
Handles.matrix = Matrix4x4.TRS(m_DecalProjectorComponent.transform.position, m_DecalProjectorComponent.transform.rotation, Vector3.one) * Matrix4x4.Translate(new Vector3(0.0f, -0.5f* m_DecalProjectorComponent.transform.localScale.y, 0.0f));
// pass in the scale
Handles.matrix = Matrix4x4.TRS(m_DecalProjectorComponent.transform.position, m_DecalProjectorComponent.transform.rotation, Vector3.one) * Matrix4x4.Translate(new Vector3(0.0f, -0.5f * m_DecalProjectorComponent.transform.localScale.y, 0.0f));
// pass in the scale
m_DecalProjectorComponent.transform.Translate(m_Handle.m_Translation);
m_DecalProjectorComponent.transform.Translate(m_Handle.m_Translation);
m_DecalProjectorComponent.transform.localScale = m_Handle.m_Scale;
Repaint();
}

}
}
public override void OnInspectorGUI()
{

EditorGUILayout.PropertyField(m_DrawDistanceProperty);
EditorGUILayout.Slider(m_FadeScaleProperty, 0.0f, 1.0f, new GUIContent("Fade scale"));
EditorGUILayout.PropertyField(m_UVScaleProperty);
EditorGUILayout.PropertyField(m_UVBiasProperty);
EditorGUILayout.PropertyField(m_AffectsTransparencyProperty);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();

6
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/DiffusionProfile/DiffusionProfileSettingsEditor.cs


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

internal Profile()
{
profileRT = new RenderTexture(256, 256, 0, RenderTextureFormat.DefaultHDR);
transmittanceRT = new RenderTexture( 16, 256, 0, RenderTextureFormat.DefaultHDR);
transmittanceRT = new RenderTexture(16, 256, 0, RenderTextureFormat.DefaultHDR);
}
internal void Release()

var scatterDist1 = profile.scatterDistance1.colorValue;
var scatterDist2 = profile.scatterDistance2.colorValue;
float rMax = Mathf.Max(scatterDist1.r, scatterDist1.g, scatterDist1.b,
scatterDist2.r, scatterDist2.g, scatterDist2.b);
scatterDist2.r, scatterDist2.g, scatterDist2.b);
var stdDev1 = s * (Vector4)scatterDist1;
var stdDev2 = s * (Vector4)scatterDist2;
m_ProfileMaterial.SetVector(HDShaderIDs._StdDev1, stdDev1);

49
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Unlit/UnlitsToHDUnlitUpgrader.cs


using UnityEngine;
using UnityEngine;
public class UnlitsToHDUnlitUpgrader : MaterialUpgrader
{
string Unlit_Color = "Unlit/Color";
//string Unlit_Texture = "Unlit/Texture";
string Unlit_Transparent = "Unlit/Transparent";
string Unlit_Cutout = "Unlit/Transparent Cutout";
public class UnlitsToHDUnlitUpgrader : MaterialUpgrader
{
string Unlit_Color = "Unlit/Color";
//string Unlit_Texture = "Unlit/Texture";
string Unlit_Transparent = "Unlit/Transparent";
string Unlit_Cutout = "Unlit/Transparent Cutout";
public UnlitsToHDUnlitUpgrader(string sourceShaderName, string destShaderName, MaterialFinalizer finalizer = null)
public UnlitsToHDUnlitUpgrader(string sourceShaderName, string destShaderName, MaterialFinalizer finalizer = null)
if (sourceShaderName == Unlit_Color)
RenameColor("_Color", "_UnlitColor");
else // all other unlit have a texture
RenameTexture("_MainTex", "_UnlitColorMap");
if (sourceShaderName == Unlit_Color)
RenameColor("_Color", "_UnlitColor");
else // all other unlit have a texture
RenameTexture("_MainTex", "_UnlitColorMap");
if (sourceShaderName == Unlit_Cutout)
{
RenameFloat("_Cutoff", "_AlphaCutoff");
SetFloat("_AlphaCutoffEnable", 1f);
}
else
SetFloat("_AlphaCutoffEnable", 0f);
if (sourceShaderName == Unlit_Cutout)
{
RenameFloat("_Cutoff", "_AlphaCutoff");
SetFloat("_AlphaCutoffEnable", 1f);
}
else
SetFloat("_AlphaCutoffEnable", 0f);
SetFloat("_SurfaceType", (sourceShaderName == Unlit_Transparent)? 1f : 0f );
}
SetFloat("_SurfaceType", (sourceShaderName == Unlit_Transparent) ? 1f : 0f);
}
public override void Convert(Material srcMaterial, Material dstMaterial)
public override void Convert(Material srcMaterial, Material dstMaterial)
{
//dstMaterial.hideFlags = HideFlags.DontUnloadUnusedAsset;

}
}
}
}
}

10
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Unlit/UnlitUI.cs


public static GUIContent colorText = new GUIContent("Color", "Color");
public static GUIContent emissiveText = new GUIContent("Emissive Color", "Emissive");
public static GUIContent emissiveIntensityText = new GUIContent("Emissive Intensity", "Emissive");
}
protected MaterialProperty color = null;

protected const string kEmissiveColor = "_EmissiveColor";
protected MaterialProperty emissiveColorMap = null;
protected const string kEmissiveColorMap = "_EmissiveColorMap";
protected MaterialProperty emissiveIntensity = null;
protected const string kEmissiveIntensity = "_EmissiveIntensity";
override protected void FindMaterialProperties(MaterialProperty[] props)
{

emissiveColor = FindProperty(kEmissiveColor, props);
emissiveColorMap = FindProperty(kEmissiveColorMap, props);
emissiveIntensity = FindProperty(kEmissiveIntensity, props);
}
protected override void MaterialPropertiesGUI(Material material)

m_MaterialEditor.TexturePropertySingleLine(Styles.emissiveText, emissiveColorMap, emissiveColor);
m_MaterialEditor.TextureScaleOffsetProperty(emissiveColorMap);
m_MaterialEditor.ShaderProperty(emissiveIntensity, Styles.emissiveIntensityText);
var surfaceTypeValue = (SurfaceType)surfaceType.floatValue;
if (surfaceTypeValue == SurfaceType.Transparent)

protected override void VertexAnimationPropertiesGUI()
{
protected override bool ShouldEmissionBeEnabled(Material mat)
protected override bool ShouldEmissionBeEnabled(Material material)
return mat.GetFloat(kEmissiveIntensity) > 0.0f;
return (material.GetColor(kEmissiveColor) != Color.black) || material.GetTexture(kEmissiveColorMap);
}
protected override void SetupMaterialKeywordsAndPassInternal(Material material)

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


// See comment in LitProperties.hlsl
const string kEmissionColor = "_EmissionColor";
protected virtual SurfaceType defaultSurfaceType { get { return SurfaceType.Opaque; } }
protected virtual bool showBlendModePopup { get { return true; } }
bool m_ShowBlendModePopup = true;
protected virtual bool showBlendModePopup { get { return m_ShowBlendModePopup; } }
// The following set of functions are call by the ShaderGraph
// It will allow to display our common parameters + setup keyword correctly for them

protected virtual void FindBaseMaterialProperties(MaterialProperty[] props)
{
// Everything is optional (except surface type) so users that derive from this class can decide what they expose or not
surfaceType = FindProperty(kSurfaceType, props, false);
surfaceType = FindProperty(kSurfaceType, props);
alphaCutoffEnable = FindProperty(kAlphaCutoffEnabled, props, false);
alphaCutoff = FindProperty(kAlphaCutoff, props, false);

enableMotionVectorForVertexAnimation = FindProperty(kEnableMotionVectorForVertexAnimation, props, false);
}
protected SurfaceType surfaceTypeValue
{
get { return surfaceType != null ? (SurfaceType)surfaceType.floatValue : defaultSurfaceType; }
}
if (surfaceType != null)
{
EditorGUI.showMixedValue = surfaceType.hasMixedValue;
var mode = (SurfaceType)surfaceType.floatValue;
EditorGUI.BeginChangeCheck();
mode = (SurfaceType)EditorGUILayout.Popup(StylesBaseUnlit.surfaceTypeText, (int)mode, StylesBaseUnlit.surfaceTypeNames);
if (EditorGUI.EndChangeCheck())
{
m_MaterialEditor.RegisterPropertyChangeUndo("Surface Type");
surfaceType.floatValue = (float)mode;
}
EditorGUI.showMixedValue = surfaceType.hasMixedValue;
var mode = (SurfaceType)surfaceType.floatValue;
EditorGUI.showMixedValue = false;
EditorGUI.BeginChangeCheck();
mode = (SurfaceType)EditorGUILayout.Popup(StylesBaseUnlit.surfaceTypeText, (int)mode, StylesBaseUnlit.surfaceTypeNames);
if (EditorGUI.EndChangeCheck())
{
m_MaterialEditor.RegisterPropertyChangeUndo("Surface Type");
surfaceType.floatValue = (float)mode;
EditorGUI.showMixedValue = false;
}
private void BlendModePopup()

EditorGUI.indentLevel++;
SurfaceTypePopup();
if (surfaceTypeValue == SurfaceType.Transparent)
if ((SurfaceType)surfaceType.floatValue == SurfaceType.Transparent)
{
if (blendMode != null && showBlendModePopup)
BlendModePopup();

// With transparent object and few specific materials like Hair, we need more control on the cutoff to apply
// This allow to get a better sorting (with prepass), better shadow (better silhouettes fidelity) etc...
if (surfaceTypeValue == SurfaceType.Transparent)
if ((SurfaceType)surfaceType.floatValue == SurfaceType.Transparent)
{
if (alphaCutoffShadow != null)
{

EditorGUI.indentLevel--;
}
if (transparentBackfaceEnable != null && (surfaceTypeValue == SurfaceType.Transparent))
if (transparentBackfaceEnable != null && ((SurfaceType)surfaceType.floatValue == SurfaceType.Transparent))
if (transparentSortPriority != null && (surfaceTypeValue == SurfaceType.Transparent))
if (transparentSortPriority != null && ((SurfaceType)surfaceType.floatValue == SurfaceType.Transparent))
{
EditorGUI.BeginChangeCheck();
m_MaterialEditor.ShaderProperty(transparentSortPriority, StylesBaseUnlit.transparentSortPriorityText);

bool alphaTestEnable = material.HasProperty(kAlphaCutoffEnabled) && material.GetFloat(kAlphaCutoffEnabled) > 0.0f;
CoreUtils.SetKeyword(material, "_ALPHATEST_ON", alphaTestEnable);
SurfaceType surfaceType = material.HasProperty(kSurfaceType) ? (SurfaceType)material.GetFloat(kSurfaceType) : SurfaceType.Opaque;
SurfaceType surfaceType = (SurfaceType)material.GetFloat(kSurfaceType);
CoreUtils.SetKeyword(material, "_SURFACE_TYPE_TRANSPARENT", surfaceType == SurfaceType.Transparent);
bool enableBlendModePreserveSpecularLighting = (surfaceType == SurfaceType.Transparent) && material.HasProperty(kEnableBlendModePreserveSpecularLighting) && material.GetFloat(kEnableBlendModePreserveSpecularLighting) > 0.0f;

material.SetInt("_DistortionBlurSrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DistortionBlurDstBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DistortionBlurBlendOp", (int)UnityEngine.Rendering.BlendOp.Max);
break;
break;
case 1: // Multiply
material.SetInt("_DistortionSrcBlend", (int)UnityEngine.Rendering.BlendMode.DstColor);

// A material's GI flag internally keeps track of whether emission is enabled at all, it's enabled but has no effect
// or is enabled and may be modified at runtime. This state depends on the values of the current flag and emissive color.
// The fixup routine makes sure that the material is in the correct state if/when changes are made to the mode or color.
if (material.HasProperty(kEmissionColor))
material.SetColor(kEmissionColor, Color.white); // kEmissionColor must always be white to allow our own material to control the GI (this allow to fallback from builtin unity to our system).
// as it happen with old material that it isn't the case, we force it.
MaterialEditor.FixupEmissiveFlag(material);
// Commented out for now because unfortunately we used the hard coded property names used by the GI system for our own parameters

90
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs


using UnityEngine;
using UnityEngine;
public class StandardsToHDLitMaterialUpgrader : MaterialUpgrader
{
public class StandardsToHDLitMaterialUpgrader : MaterialUpgrader
{
public StandardsToHDLitMaterialUpgrader(string sourceShaderName, string destShaderName, MaterialFinalizer finalizer = null)
public StandardsToHDLitMaterialUpgrader(string sourceShaderName, string destShaderName, MaterialFinalizer finalizer = null)
{
RenameShader(sourceShaderName, destShaderName, finalizer);

// Metallic
bool hasMetallic = false;
Texture metallicMap = Texture2D.blackTexture;
if ( (srcMaterial.shader.name == Standard) || (srcMaterial.shader.name == Standard_Rough) )
Texture metallicMap = TextureCombiner.TextureFromColor(Color.black);
if ((srcMaterial.shader.name == Standard) || (srcMaterial.shader.name == Standard_Rough))
// Convert _Metallic value from Gamma to Linear
float metallicValue = Mathf.Pow(srcMaterial.GetFloat("_Metallic"), 2.2f);
dstMaterial.SetFloat("_Metallic", metallicValue);
hasMetallic = srcMaterial.GetTexture("_MetallicGlossMap") != null;
if (hasMetallic)
{

{
float metallicValue = Mathf.Pow(srcMaterial.GetFloat("_Metallic"), 2.2f); // Convert _Metallic value from Gamma to Linear
dstMaterial.SetFloat("_Metallic", metallicValue);
metallicMap = TextureCombiner.TextureFromColor(Color.white * metallicValue);
metallicMap = TextureCombiner.TextureFromColor(Color.white);
}
}

if (hasOcclusion) occlusionMap = TextureCombiner.GetTextureSafe(srcMaterial, "_OcclusionMap", Color.white);
dstMaterial.SetFloat("_AORemapMin", 1f - srcMaterial.GetFloat("_OcclusionStrength"));
// Detail Mask
bool hasDetailMask = srcMaterial.GetTexture("_DetailMask") != null;

// Smoothness
bool hasSmoothness = false;
Texture2D smoothnessMap = TextureCombiner.TextureFromColor(Color.grey);
Texture2D smoothnessMap = TextureCombiner.TextureFromColor(Color.white);
dstMaterial.SetFloat("_SmoothnessRemapMax", srcMaterial.GetFloat("_Glossiness"));
if (srcMaterial.shader.name == Standard_Rough)
{

{
string smoothnessTextureChannel = "_MainTex";
if ( srcMaterial.GetFloat("_SmoothnessTextureChannel") == 0 )
if (srcMaterial.GetFloat("_SmoothnessTextureChannel") == 0)
smoothnessMap = (Texture2D) srcMaterial.GetTexture( smoothnessTextureChannel );
smoothnessMap = (Texture2D)srcMaterial.GetTexture(smoothnessTextureChannel);
if (smoothnessMap != null)
{
hasSmoothness = true;

}
else
{
smoothnessMap = TextureCombiner.TextureFromColor(Color.white * srcMaterial.GetFloat("_Glossiness"));
smoothnessMap = TextureCombiner.TextureFromColor(Color.white);
if ( hasMetallic || hasOcclusion || hasDetailMask || hasSmoothness )
if (hasMetallic || hasOcclusion || hasDetailMask || hasSmoothness)
metallicMap, 0, // R: Metallic from red
occlusionMap, 1, // G: Occlusion from green
detailMaskMap, 3, // B: Detail Mask from alpha
smoothnessMap, (srcMaterial.shader.name == Standard_Rough)?-4:3 // A: Smoothness Texture from inverse greyscale for roughness setup, or alpha
);
dstMaterial.SetFloat("_Metallic", 1f); // Force _Metallic value to 1, to use the value stored in the mask map without modification
metallicMap, 0, // R: Metallic from red
occlusionMap, 1, // G: Occlusion from green
detailMaskMap, 3, // B: Detail Mask from alpha
smoothnessMap, (srcMaterial.shader.name == Standard_Rough) ? -4 : 3 // A: Smoothness Texture from inverse greyscale for roughness setup, or alpha
);
maskMapPath = maskMapPath.Remove(maskMapPath.Length-4) + "_MaskMap.png";
maskMap = maskMapCombiner.Combine( maskMapPath );
maskMapPath = maskMapPath.Remove(maskMapPath.Length - 4) + "_MaskMap.png";
maskMap = maskMapCombiner.Combine(maskMapPath);
dstMaterial.SetFloat("_AORemapMin", 1f - srcMaterial.GetFloat("_OcclusionStrength"));
if (srcMaterial.GetTexture("_SpecGlossMap") != null ) dstMaterial.SetColor("_SpecularColor", Color.white);
if (srcMaterial.GetTexture("_SpecGlossMap") != null) dstMaterial.SetColor("_SpecularColor", Color.white);
}
// ---------- Height Map ----------

// ---------- Detail Map ----------
bool hasDetailAlbedo = srcMaterial.GetTexture("_DetailAlbedoMap") != null;
bool hasDetailNormal = srcMaterial.GetTexture("_DetailNormalMap") != null;
if ( hasDetailAlbedo || hasDetailNormal )
if (hasDetailAlbedo || hasDetailNormal)
TextureCombiner.GetTextureSafe(srcMaterial, "_DetailAlbedoMap", Color.grey), 4, // Albedo (overlay)
TextureCombiner.GetTextureSafe(srcMaterial, "_DetailNormalMap", Color.grey), 1, // Normal Y
TextureCombiner.midGrey, 1, // Smoothness
TextureCombiner.GetTextureSafe(srcMaterial, "_DetailNormalMap", Color.grey), 0 // Normal X
);
TextureCombiner.GetTextureSafe(srcMaterial, "_DetailAlbedoMap", Color.grey), 4, // Albedo (overlay)
TextureCombiner.GetTextureSafe(srcMaterial, "_DetailNormalMap", Color.grey), 1, // Normal Y
TextureCombiner.midGrey, 1, // Smoothness
TextureCombiner.GetTextureSafe(srcMaterial, "_DetailNormalMap", Color.grey), 0 // Normal X
);
detailMapPath = detailMapPath.Remove(detailMapPath.Length-4) + "_DetailMap.png";
detailMap = detailCombiner.Combine( detailMapPath );
detailMapPath = detailMapPath.Remove(detailMapPath.Length - 4) + "_DetailMap.png";
detailMap = detailCombiner.Combine(detailMapPath);
dstMaterial.SetTexture("_DetailMap", detailMap);
}

break;
}
// Emission: Convert the HDR emissive color to ldr color + intensity
float intensity = Mathf.Max(hdrEmission.r, Mathf.Max(hdrEmission.g, hdrEmission.b));
if (intensity > 1f)
{
hdrEmission.r /= intensity;
hdrEmission.g /= intensity;
hdrEmission.b /= intensity;
}
else
intensity = 1f;
intensity = Mathf.Pow(intensity, 2.2f); // Gamma to Linear conversion
dstMaterial.SetColor("_EmissiveColor", hdrEmission);
dstMaterial.SetFloat("_EmissiveIntensity", intensity);
dstMaterial.SetColor("_EmissiveColor", (srcMaterial.GetFloat("_EmissionEnabled") != 0)?hdrEmission: Color.black);
}
}
}

42
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/LitUI.cs


public static GUIContent baseColorText = new GUIContent("Base Color + Opacity", "Albedo (RGB) and Opacity (A)");
public static GUIContent smoothnessMapChannelText = new GUIContent("Smoothness Source", "Smoothness texture and channel");
public static GUIContent metallicText = new GUIContent("Metallic", "Metallic scale factor");
public static GUIContent smoothnessText = new GUIContent("Smoothness", "Smoothness scale factor");
public static GUIContent smoothnessRemappingText = new GUIContent("Smoothness Remapping", "Smoothness remapping");

// Emissive
public static string emissiveLabelText = "Emissive Inputs";
public static GUIContent emissiveText = new GUIContent("Emissive Color", "Emissive");
public static GUIContent emissiveIntensityText = new GUIContent("Emissive Intensity", "Emissive");
public static GUIContent emissiveText = new GUIContent("Emissive Color", "Emissive Color (linear RGB) in nits unit");
public static GUIContent albedoAffectEmissiveText = new GUIContent("Albedo Affect Emissive", "Specifies whether or not the emissive color is multiplied by the albedo.");
public static GUIContent normalMapSpaceWarning = new GUIContent("Object space normal can't be use with triplanar mapping.");

public static GUIContent refractionSSRayModelText = new GUIContent("SSRay Model", "Screen Space Ray Model");
public static GUIContent refractionProjectionModelText = new GUIContent("SSRay Model", "Screen Space Ray Model");
public static GUIContent refractionIorText = new GUIContent("Index of refraction", "Index of refraction");
public static GUIContent refractionThicknessText = new GUIContent("Refraction Thickness", "Thickness for rough refraction");
public static GUIContent refractionThicknessMultiplierText = new GUIContent("Refraction Thickness multiplier (m)", "Thickness multiplier");

protected const string kEmissiveColor = "_EmissiveColor";
protected MaterialProperty emissiveColorMap = null;
protected const string kEmissiveColorMap = "_EmissiveColorMap";
protected MaterialProperty emissiveIntensity = null;
protected const string kEmissiveIntensity = "_EmissiveIntensity";
protected MaterialProperty albedoAffectEmissive = null;
protected const string kAlbedoAffectEmissive = "_AlbedoAffectEmissive";
protected MaterialProperty UVEmissive = null;

protected const string kThicknessMultiplier = "_ThicknessMultiplier";
protected MaterialProperty refractionModel = null;
protected const string kRefractionModel = "_RefractionModel";
protected MaterialProperty refractionSSRayModel = null;
protected const string kRefractionSSRayModel = "_RefractionSSRayModel";
protected MaterialProperty ssrefractionProjectionModel = null;
protected const string kSSRefractionProjectionModel = "_SSRefractionProjectionModel";
protected override bool showBlendModePopup
{

emissiveColorMode = FindProperty(kEmissiveColorMode, props);
emissiveColor = FindProperty(kEmissiveColor, props);
emissiveColorMap = FindProperty(kEmissiveColorMap, props);
emissiveIntensity = FindProperty(kEmissiveIntensity, props);
albedoAffectEmissive = FindProperty(kAlbedoAffectEmissive, props);
UVEmissive = FindProperty(kUVEmissive, props);

// Transparency
refractionModel = FindProperty(kRefractionModel, props, false);
refractionSSRayModel = FindProperty(kRefractionSSRayModel, props, false);
ssrefractionProjectionModel = FindProperty(kSSRefractionProjectionModel, props, false);
transmittanceColor = FindProperty(kTransmittanceColor, props, false);
transmittanceColorMap = FindProperty(kTransmittanceColorMap, props, false);
atDistance = FindProperty(kATDistance, props, false);

}
}
}
protected void ShaderIridescenceInputGUI()
{
m_MaterialEditor.TexturePropertySingleLine(Styles.iridescenceMaskText, iridescenceMaskMap, iridescenceMask);

else
{
// Allow the user to set the constant value of thickness if no thickness map is provided.
m_MaterialEditor.TexturePropertySingleLine(Styles.iridescenceThicknessMapText, iridescenceThicknessMap, iridescenceThickness);
m_MaterialEditor.TexturePropertySingleLine(Styles.iridescenceThicknessMapText, iridescenceThicknessMap, iridescenceThickness);
}
}

protected override void UpdateDisplacement()
{
for(int i = 0; i < m_LayerCount; ++i)
for (int i = 0; i < m_LayerCount; ++i)
{
UpdateDisplacement(i);
}

else
{
HeightmapParametrization parametrization = (HeightmapParametrization)heightParametrization[layerIndex].floatValue;
if(parametrization == HeightmapParametrization.MinMax)
if (parametrization == HeightmapParametrization.MinMax)
{
float offset = heightOffset[layerIndex].floatValue;
float amplitude = (heightMax[layerIndex].floatValue - heightMin[layerIndex].floatValue);

m_MaterialEditor.ShaderProperty(metallic[layerIndex], Styles.metallicText);
}
if(maskMap[layerIndex].textureValue == null)
if (maskMap[layerIndex].textureValue == null)
{
m_MaterialEditor.ShaderProperty(smoothness[layerIndex], Styles.smoothnessText);
}

}
DisplacementMode displaceMode = (DisplacementMode)displacementMode.floatValue;
if(displaceMode != DisplacementMode.None || showHeightMap)
if (displaceMode != DisplacementMode.None || showHeightMap)
{
EditorGUI.BeginChangeCheck();
m_MaterialEditor.TexturePropertySingleLine(Styles.heightMapText, heightMap[layerIndex]);

else
{
m_MaterialEditor.ShaderProperty(heightParametrization[layerIndex], Styles.heightMapParametrization);
if(!heightParametrization[layerIndex].hasMixedValue)
if (!heightParametrization[layerIndex].hasMixedValue)
{
HeightmapParametrization parametrization = (HeightmapParametrization)heightParametrization[layerIndex].floatValue;
if (parametrization == HeightmapParametrization.MinMax)

}
EditorGUI.indentLevel--;
var surfaceTypeValue = (SurfaceType)surfaceType.floatValue;
if (surfaceTypeValue == SurfaceType.Transparent
&& refractionModel != null)
{

var mode = (Lit.RefractionModel)refractionModel.floatValue;
if (mode != Lit.RefractionModel.None)
{
m_MaterialEditor.ShaderProperty(refractionSSRayModel, Styles.refractionSSRayModelText);
m_MaterialEditor.ShaderProperty(ssrefractionProjectionModel, Styles.refractionProjectionModelText);
m_MaterialEditor.ShaderProperty(ior, Styles.refractionIorText);
blendMode.floatValue = (float)BlendMode.Alpha;

EditorGUI.indentLevel--;
}
m_MaterialEditor.ShaderProperty(emissiveIntensity, Styles.emissiveIntensityText);
m_MaterialEditor.ShaderProperty(albedoAffectEmissive, Styles.albedoAffectEmissiveText);
EditorGUI.indentLevel--;
}

m_MaterialEditor.ShaderProperty(enableSpecularOcclusion, Styles.enableSpecularOcclusionText);
}
protected override bool ShouldEmissionBeEnabled(Material mat)
protected override bool ShouldEmissionBeEnabled(Material material)
return mat.GetFloat(kEmissiveIntensity) > 0.0f;
return (material.GetColor(kEmissiveColor) != Color.black) || material.GetTexture(kEmissiveColorMap);
}
protected override void SetupMaterialKeywordsAndPassInternal(Material material)

CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SPECULAR_COLOR", materialId == BaseLitGUI.MaterialId.LitSpecular);
var refractionModelValue = (Lit.RefractionModel)material.GetFloat(kRefractionModel);
var refractionSSRayModelValue = (Lit.RefractionSSRayModel)material.GetFloat(kRefractionSSRayModel);
var refractionProjectionModelValue = (Lit.ProjectionModel)material.GetFloat(kSSRefractionProjectionModel);
CoreUtils.SetKeyword(material, "_REFRACTION_SSRAY_PROXY", (refractionSSRayModelValue == Lit.RefractionSSRayModel.Proxy) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_REFRACTION_SSRAY_HIZ", (refractionSSRayModelValue == Lit.RefractionSSRayModel.HiZ) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_REFRACTION_SSRAY_PROXY", (refractionProjectionModelValue == Lit.ProjectionModel.Proxy) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_REFRACTION_SSRAY_HIZ", (refractionProjectionModelValue == Lit.ProjectionModel.HiZ) && canHaveRefraction);
}
}
} // namespace UnityEditor

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


public static GUIContent windShiverDirectionalityText = new GUIContent("Shiver Directionality");
public static GUIContent supportDBufferText = new GUIContent("Enable Decal", "Allow to specify if the material can receive decal or not");
public static GUIContent enableGeometricSpecularAAText = new GUIContent("Enable geometric specular AA", "This reduce specular aliasing on highly dense mesh (Particularly useful when they don't use normal map)");
public static GUIContent specularAAScreenSpaceVarianceText = new GUIContent("Screen space variance", "Allow to control the strength of the specular AA reduction. Higher mean more blurry result and less aliasing");
public static GUIContent specularAAThresholdText = new GUIContent("Threshold", "Allow to limit the effect of specular AA reduction. 0 mean don't apply reduction, higher value mean allow higher reduction");
}
public enum DoubleSidedNormalMode

// Decal
protected MaterialProperty supportDBuffer = null;
protected const string kSupportDBuffer = "_SupportDBuffer";
protected MaterialProperty enableGeometricSpecularAA = null;
protected const string kEnableGeometricSpecularAA = "_EnableGeometricSpecularAA";
protected MaterialProperty specularAAScreenSpaceVariance = null;
protected const string kSpecularAAScreenSpaceVariance = "_SpecularAAScreenSpaceVariance";
protected MaterialProperty specularAAThreshold = null;
protected const string kSpecularAAThreshold = "_SpecularAAThreshold";
protected override void FindBaseMaterialProperties(MaterialProperty[] props)
{

depthOffsetEnable = FindProperty(kDepthOffsetEnable, props, false);
depthOffsetEnable = FindProperty(kDepthOffsetEnable, props);
materialID = FindProperty(kMaterialID, props, false);
transmissionEnable = FindProperty(kTransmissionEnable, props, false);
materialID = FindProperty(kMaterialID, props);
transmissionEnable = FindProperty(kTransmissionEnable, props);
displacementMode = FindProperty(kDisplacementMode, props, false);
displacementLockObjectScale = FindProperty(kDisplacementLockObjectScale, props, false);
displacementLockTilingScale = FindProperty(kDisplacementLockTilingScale, props, false);
displacementMode = FindProperty(kDisplacementMode, props);
displacementLockObjectScale = FindProperty(kDisplacementLockObjectScale, props);
displacementLockTilingScale = FindProperty(kDisplacementLockTilingScale, props);
ppdMinSamples = FindProperty(kPpdMinSamples, props, false);
ppdMaxSamples = FindProperty(kPpdMaxSamples, props, false);
ppdLodThreshold = FindProperty(kPpdLodThreshold, props, false);
ppdPrimitiveLength = FindProperty(kPpdPrimitiveLength, props, false);
ppdPrimitiveWidth = FindProperty(kPpdPrimitiveWidth, props, false);
invPrimScale = FindProperty(kInvPrimScale, props, false);
ppdMinSamples = FindProperty(kPpdMinSamples, props);
ppdMaxSamples = FindProperty(kPpdMaxSamples, props);
ppdLodThreshold = FindProperty(kPpdLodThreshold, props);
ppdPrimitiveLength = FindProperty(kPpdPrimitiveLength, props);
ppdPrimitiveWidth = FindProperty(kPpdPrimitiveWidth, props);
invPrimScale = FindProperty(kInvPrimScale, props);
// tessellation specific, silent if not found
tessellationMode = FindProperty(kTessellationMode, props, false);

tessellationBackFaceCullEpsilon = FindProperty(kTessellationBackFaceCullEpsilon, props, false);
// Wind
windEnable = FindProperty(kWindEnabled, props, false);
windInitialBend = FindProperty(kWindInitialBend, props, false);
windStiffness = FindProperty(kWindStiffness, props, false);
windDrag = FindProperty(kWindDrag, props, false);
windShiverDrag = FindProperty(kWindShiverDrag, props, false);
windShiverDirectionality = FindProperty(kWindShiverDirectionality, props, false);
windEnable = FindProperty(kWindEnabled, props);
windInitialBend = FindProperty(kWindInitialBend, props);
windStiffness = FindProperty(kWindStiffness, props);
windDrag = FindProperty(kWindDrag, props);
windShiverDrag = FindProperty(kWindShiverDrag, props);
windShiverDirectionality = FindProperty(kWindShiverDirectionality, props);
// specular AA
enableGeometricSpecularAA = FindProperty(kEnableGeometricSpecularAA, props, false);
specularAAScreenSpaceVariance = FindProperty(kSpecularAAScreenSpaceVariance, props, false);
specularAAThreshold = FindProperty(kSpecularAAThreshold, props, false);
}
void TessellationModePopup()

EditorGUI.indentLevel--;
}
if (materialID != null)
{
m_MaterialEditor.ShaderProperty(materialID, StylesBaseLit.materialIDText);
m_MaterialEditor.ShaderProperty(materialID, StylesBaseLit.materialIDText);
if ((int)materialID.floatValue == (int)BaseLitGUI.MaterialId.LitSSS)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(transmissionEnable, StylesBaseLit.transmissionEnableText);
EditorGUI.indentLevel--;
}
if ((int)materialID.floatValue == (int)BaseLitGUI.MaterialId.LitSSS)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(transmissionEnable, StylesBaseLit.transmissionEnableText);
EditorGUI.indentLevel--;
if (enableMotionVectorForVertexAnimation != null)
m_MaterialEditor.ShaderProperty(enableMotionVectorForVertexAnimation, StylesBaseUnlit.enableMotionVectorForVertexAnimationText);
m_MaterialEditor.ShaderProperty(enableGeometricSpecularAA, StylesBaseLit.enableGeometricSpecularAAText);
if (displacementMode != null)
if (enableGeometricSpecularAA.floatValue > 0.0)
EditorGUI.BeginChangeCheck();
m_MaterialEditor.ShaderProperty(displacementMode, StylesBaseLit.displacementModeText);
if (EditorGUI.EndChangeCheck())
{
UpdateDisplacement();
}
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(specularAAScreenSpaceVariance, StylesBaseLit.specularAAScreenSpaceVarianceText);
m_MaterialEditor.ShaderProperty(specularAAThreshold, StylesBaseLit.specularAAThresholdText);
EditorGUI.indentLevel--;
}
if ((DisplacementMode)displacementMode.floatValue != DisplacementMode.None)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(displacementLockObjectScale, StylesBaseLit.lockWithObjectScaleText);
m_MaterialEditor.ShaderProperty(displacementLockTilingScale, StylesBaseLit.lockWithTilingRateText);
EditorGUI.indentLevel--;
}
m_MaterialEditor.ShaderProperty(enableMotionVectorForVertexAnimation, StylesBaseUnlit.enableMotionVectorForVertexAnimationText);
if ((DisplacementMode)displacementMode.floatValue == DisplacementMode.Pixel)
{
EditorGUILayout.Space();
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(ppdMinSamples, StylesBaseLit.ppdMinSamplesText);
m_MaterialEditor.ShaderProperty(ppdMaxSamples, StylesBaseLit.ppdMaxSamplesText);
ppdMinSamples.floatValue = Mathf.Min(ppdMinSamples.floatValue, ppdMaxSamples.floatValue);
m_MaterialEditor.ShaderProperty(ppdLodThreshold, StylesBaseLit.ppdLodThresholdText);
m_MaterialEditor.ShaderProperty(ppdPrimitiveLength, StylesBaseLit.ppdPrimitiveLength);
ppdPrimitiveLength.floatValue = Mathf.Max(0.01f, ppdPrimitiveLength.floatValue);
m_MaterialEditor.ShaderProperty(ppdPrimitiveWidth, StylesBaseLit.ppdPrimitiveWidth);
ppdPrimitiveWidth.floatValue = Mathf.Max(0.01f, ppdPrimitiveWidth.floatValue);
invPrimScale.vectorValue = new Vector4(1.0f / ppdPrimitiveLength.floatValue, 1.0f / ppdPrimitiveWidth.floatValue); // Precompute
m_MaterialEditor.ShaderProperty(depthOffsetEnable, StylesBaseLit.depthOffsetEnableText);
EditorGUI.indentLevel--;
}
EditorGUI.BeginChangeCheck();
m_MaterialEditor.ShaderProperty(displacementMode, StylesBaseLit.displacementModeText);
if (EditorGUI.EndChangeCheck())
{
UpdateDisplacement();
}
if ((DisplacementMode)displacementMode.floatValue != DisplacementMode.None)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(displacementLockObjectScale, StylesBaseLit.lockWithObjectScaleText);
m_MaterialEditor.ShaderProperty(displacementLockTilingScale, StylesBaseLit.lockWithTilingRateText);
EditorGUI.indentLevel--;
}
if ((DisplacementMode)displacementMode.floatValue == DisplacementMode.Pixel)
{
EditorGUILayout.Space();
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(ppdMinSamples, StylesBaseLit.ppdMinSamplesText);
m_MaterialEditor.ShaderProperty(ppdMaxSamples, StylesBaseLit.ppdMaxSamplesText);
ppdMinSamples.floatValue = Mathf.Min(ppdMinSamples.floatValue, ppdMaxSamples.floatValue);
m_MaterialEditor.ShaderProperty(ppdLodThreshold, StylesBaseLit.ppdLodThresholdText);
m_MaterialEditor.ShaderProperty(ppdPrimitiveLength, StylesBaseLit.ppdPrimitiveLength);
ppdPrimitiveLength.floatValue = Mathf.Max(0.01f, ppdPrimitiveLength.floatValue);
m_MaterialEditor.ShaderProperty(ppdPrimitiveWidth, StylesBaseLit.ppdPrimitiveWidth);
ppdPrimitiveWidth.floatValue = Mathf.Max(0.01f, ppdPrimitiveWidth.floatValue);
invPrimScale.vectorValue = new Vector4(1.0f / ppdPrimitiveLength.floatValue, 1.0f / ppdPrimitiveWidth.floatValue); // Precompute
m_MaterialEditor.ShaderProperty(depthOffsetEnable, StylesBaseLit.depthOffsetEnableText);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;

protected override void VertexAnimationPropertiesGUI()
{
if (windEnable == null)
return;
EditorGUILayout.LabelField(StylesBaseLit.vertexAnimation, EditorStyles.boldLabel);
EditorGUI.indentLevel++;

// Set the reference value for the stencil test.
int stencilRef = (int)StencilLightingUsage.RegularLighting;
if (material.HasProperty(kMaterialID) && (int)material.GetFloat(kMaterialID) == (int)BaseLitGUI.MaterialId.LitSSS)
if ((int)material.GetFloat(kMaterialID) == (int)BaseLitGUI.MaterialId.LitSSS)
{
stencilRef = (int)StencilLightingUsage.SplitLighting;
}

material.SetInt(kStencilRefMV, (int)HDRenderPipeline.StencilBitMask.ObjectVelocity);
material.SetInt(kStencilWriteMaskMV, (int)HDRenderPipeline.StencilBitMask.ObjectVelocity);
if (material.HasProperty(kDisplacementMode))
{
bool enableDisplacement = (DisplacementMode)material.GetFloat(kDisplacementMode) != DisplacementMode.None;
bool enableVertexDisplacement = (DisplacementMode)material.GetFloat(kDisplacementMode) == DisplacementMode.Vertex;
bool enablePixelDisplacement = (DisplacementMode)material.GetFloat(kDisplacementMode) == DisplacementMode.Pixel;
bool enableTessellationDisplacement = ((DisplacementMode)material.GetFloat(kDisplacementMode) == DisplacementMode.Tessellation) && material.HasProperty(kTessellationMode);
CoreUtils.SetKeyword(material, "_VERTEX_DISPLACEMENT", enableVertexDisplacement);
CoreUtils.SetKeyword(material, "_PIXEL_DISPLACEMENT", enablePixelDisplacement);
// Only set if tessellation exist
CoreUtils.SetKeyword(material, "_TESSELLATION_DISPLACEMENT", enableTessellationDisplacement);
bool enableDisplacement = (DisplacementMode)material.GetFloat(kDisplacementMode) != DisplacementMode.None;
bool enableVertexDisplacement = (DisplacementMode)material.GetFloat(kDisplacementMode) == DisplacementMode.Vertex;
bool enablePixelDisplacement = (DisplacementMode)material.GetFloat(kDisplacementMode) == DisplacementMode.Pixel;
bool enableTessellationDisplacement = ((DisplacementMode)material.GetFloat(kDisplacementMode) == DisplacementMode.Tessellation) && material.HasProperty(kTessellationMode);
bool displacementLockObjectScale = material.GetFloat(kDisplacementLockObjectScale) > 0.0;
bool displacementLockTilingScale = material.GetFloat(kDisplacementLockTilingScale) > 0.0;
// Tessellation reuse vertex flag.
CoreUtils.SetKeyword(material, "_VERTEX_DISPLACEMENT_LOCK_OBJECT_SCALE", displacementLockObjectScale && (enableVertexDisplacement || enableTessellationDisplacement));
CoreUtils.SetKeyword(material, "_PIXEL_DISPLACEMENT_LOCK_OBJECT_SCALE", displacementLockObjectScale && enablePixelDisplacement);
CoreUtils.SetKeyword(material, "_DISPLACEMENT_LOCK_TILING_SCALE", displacementLockTilingScale && enableDisplacement);
CoreUtils.SetKeyword(material, "_VERTEX_DISPLACEMENT", enableVertexDisplacement);
CoreUtils.SetKeyword(material, "_PIXEL_DISPLACEMENT", enablePixelDisplacement);
// Only set if tessellation exist
CoreUtils.SetKeyword(material, "_TESSELLATION_DISPLACEMENT", enableTessellationDisplacement);
// Depth offset is only enabled if per pixel displacement is
bool depthOffsetEnable = (material.GetFloat(kDepthOffsetEnable) > 0.0f) && enablePixelDisplacement;
CoreUtils.SetKeyword(material, "_DEPTHOFFSET_ON", depthOffsetEnable);
}
bool displacementLockObjectScale = material.GetFloat(kDisplacementLockObjectScale) > 0.0;
bool displacementLockTilingScale = material.GetFloat(kDisplacementLockTilingScale) > 0.0;
// Tessellation reuse vertex flag.
CoreUtils.SetKeyword(material, "_VERTEX_DISPLACEMENT_LOCK_OBJECT_SCALE", displacementLockObjectScale && (enableVertexDisplacement || enableTessellationDisplacement));
CoreUtils.SetKeyword(material, "_PIXEL_DISPLACEMENT_LOCK_OBJECT_SCALE", displacementLockObjectScale && enablePixelDisplacement);
CoreUtils.SetKeyword(material, "_DISPLACEMENT_LOCK_TILING_SCALE", displacementLockTilingScale && enableDisplacement);
bool windEnabled = material.HasProperty(kWindEnabled) && material.GetFloat(kWindEnabled) > 0.0f;
bool windEnabled = material.GetFloat(kWindEnabled) > 0.0f;
// Depth offset is only enabled if per pixel displacement is
bool depthOffsetEnable = (material.GetFloat(kDepthOffsetEnable) > 0.0f) && enablePixelDisplacement;
CoreUtils.SetKeyword(material, "_DEPTHOFFSET_ON", depthOffsetEnable);
if (material.HasProperty(kTessellationMode))
{

// Use negation so we don't create keyword by default
CoreUtils.SetKeyword(material, "_DISABLE_DBUFFER", material.GetFloat(kSupportDBuffer) == 0.0);
CoreUtils.SetKeyword(material, "_ENABLE_GEOMETRIC_SPECULAR_AA", material.GetFloat(kEnableGeometricSpecularAA) == 1.0);
}
static public void SetupBaseLitMaterialPass(Material material)

386
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/StackLit/StackLitUI.cs


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

protected const string k_MetallicMap = "_MetallicMap";
protected const string k_MetallicMapUV = "_MetallicMapUV";
protected const string k_Smoothness1 = "_SmoothnessA";
protected const string k_Smoothness1Map = "_SmoothnessAMap";
protected const string k_Smoothness1MapUV = "_SmoothnessAMapUV";
protected const string k_DielectricIor = "_DielectricIor";
protected const string k_SmoothnessA = "_SmoothnessA";
protected const string k_SmoothnessAMap = "_SmoothnessAMap";
protected const string k_SmoothnessAMapUV = "_SmoothnessAMapUV";
protected const string k_NormalMap = "_NormalMap";
protected const string k_NormalMapUV = "_NormalMapUV";

protected const string k_EmissiveColor = "_EmissiveColor";
protected const string k_EmissiveColorMap = "_EmissiveColorMap";
protected const string k_EmissiveColorMapUV = "_EmissiveColorMapUV";
protected const string k_EmissiveIntensity = "_EmissiveIntensity";
protected const string k_CoatEnable = "_CoatEnable";
protected const string k_EnableCoat = "_EnableCoat";
protected const string k_CoatSmoothnessMap = "_CoatSmoothnessMap";
protected const string k_CoatSmoothnessMapUV = "_CoatSmoothnessMapUV";
protected const string k_EnableCoatNormalMap = "_EnableCoatNormalMap";
protected const string k_CoatNormalMap = "_CoatNormalMap";
protected const string k_CoatNormalMapUV = "_CoatNormalMapUV";
protected const string k_CoatNormalScale = "_CoatNormalScale";
protected const string k_EnableSubsurfaceScattering = "_EnableSubsurfaceScattering";
protected const string k_DiffusionProfile = "_DiffusionProfile";
protected const string k_SubsurfaceMask = "_SubsurfaceMask";
protected const string k_SubsurfaceMaskMap = "_SubsurfaceMaskMap";

protected const string k_EnableTransmission = "_EnableTransmission";
protected const string k_Smoothness2 = "_SmoothnessB";
protected const string k_Smoothness2Map = "_SmoothnessBMap";
protected const string k_Smoothness2MapUV = "_SmoothnessBMapUV";
protected const string k_EnableDualSpecularLobe = "_EnableDualSpecularLobe";
protected const string k_SmoothnessB = "_SmoothnessB";
protected const string k_SmoothnessBMap = "_SmoothnessBMap";
protected const string k_SmoothnessBMapUV = "_SmoothnessBMapUV";
protected const string k_EnableAnisotropy = "_EnableAnisotropy";
protected const string k_AnisotropyMap = "_AnisotropyMap";
protected const string k_AnisotropyMapUV = "_AnisotropyMapUV";
//// transparency params
//protected MaterialProperty transmissionEnable = null;
//protected const string kTransmissionEnable = "_TransmissionEnable";
// Iridescence
protected const string k_EnableIridescence = "_EnableIridescence";
protected const string k_IridescenceIor = "_IridescenceIor";
protected const string k_IridescenceThickness = "_IridescenceThickness";
protected const string k_IridescenceThicknessMap = "_IridescenceThicknessMap";
protected const string k_IridescenceThicknessMapUV = "_IridescenceThicknessMapUV";
protected const string k_IridescenceMask = "_IridescenceMask";
protected const string k_IridescenceMaskMap = "_IridescenceMaskMap";
protected const string k_IridescenceMaskMapUV = "_IridescenceMaskMapUV";
// Details
protected const string k_EnableDetails = "_EnableDetails";
protected const string k_DetailMask = "_DetailMask";
protected const string k_DetailMaskMap = "_DetailMaskMap";
protected const string k_DetailMaskMapUV = "_DetailMaskMapUV";
protected const string k_DetailSmoothness = "_DetailSmoothness";
protected const string k_DetailSmoothnessScale = "_DetailSmoothnessScale";
protected const string k_DetailSmoothnessMap = "_DetailSmoothnessMap";
protected const string k_DetailSmoothnessMapUV = "_DetailSmoothnessMapUV";
//protected MaterialProperty ior = null;
//protected const string kIor = "_Ior";
//protected MaterialProperty transmittanceColor = null;
//protected const string kTransmittanceColor = "_TransmittanceColor";
//protected MaterialProperty transmittanceColorMap = null;
//protected const string kTransmittanceColorMap = "_TransmittanceColorMap";
//protected MaterialProperty atDistance = null;
//protected const string kATDistance = "_ATDistance";
//protected MaterialProperty thicknessMultiplier = null;
//protected const string kThicknessMultiplier = "_ThicknessMultiplier";
//protected MaterialProperty refractionModel = null;
//protected const string kRefractionModel = "_RefractionModel";
//protected MaterialProperty refractionSSRayModel = null;
//protected const string kRefractionSSRayModel = "_RefractionSSRayModel";
protected const string k_DetailNormalMap = "_DetailNormalMap";
protected const string k_DetailNormalMapUV = "_DetailNormalMapUV";
protected const string k_DetailNormalScale = "_DetailNormalScale";
// Stencil is use to control lighting mode (regular, split lighting)
protected const string kStencilRef = "_StencilRef";
protected const string kStencilWriteMask = "_StencilWriteMask";
protected const string kStencilRefMV = "_StencilRefMV";
protected const string kStencilWriteMaskMV = "_StencilWriteMaskMV";
protected const string k_GeometricNormalFilteringEnabled = "_GeometricNormalFilteringEnabled";
protected const string k_TextureNormalFilteringEnabled = "_TextureNormalFilteringEnabled";
#endregion
// Add the properties into an array.

private Property EnableDetails;
private Property EnableSSS;
private Property EnableTransmission;
private Property EnableCoat;
private Property EnableCoatNormalMap;
private Property EnableAnisotropy;
private Property EnableDualSpecularLobe;
private Property EnableIridescence;
private Property EnableGeometricNormalFiltering;
private Property EnableTextureNormalFiltering;
public StackLitGUI()
{
_baseMaterialProperties = new GroupProperty(this, "_BaseMaterial", new BaseProperty[]

});
//
EnableDetails = new Property(this, k_EnableDetails, "Enable Details", "Enable Detail", true);
EnableSSS = new Property(this, k_EnableSubsurfaceScattering, "Enable Subsurface Scattering", "Enable Subsurface Scattering", true);
EnableTransmission = new Property(this, k_EnableTransmission, "Enable Transmission", "Enable Transmission", true);
EnableCoat = new Property(this, k_EnableCoat, "Enable Coat", "Enable coat layer with true vertical physically based BSDF mixing", true);
EnableCoatNormalMap = new Property(this, k_EnableCoatNormalMap, "Enable Coat Normal Map", "Enable separate top coat normal map", true);
EnableAnisotropy = new Property(this, k_EnableAnisotropy, "Enable Anisotropy", "Enable anisotropy, correct anisotropy for punctual light but very coarse approximated for reflection", true);
EnableDualSpecularLobe = new Property(this, k_EnableDualSpecularLobe, "Enable Dual Specular Lobe", "Enable a second specular lobe, aim to simulate a mix of a narrow and a haze lobe that better match measured material", true);
EnableIridescence = new Property(this, k_EnableIridescence, "Enable Iridescence", "Enable physically based iridescence layer", true);
EnableGeometricNormalFiltering = new Property(this, k_GeometricNormalFilteringEnabled, "Enable Geometric filtering", "Enable specular antialiasing", true);
EnableTextureNormalFiltering = new Property(this, k_TextureNormalFilteringEnabled, "Enable Texture filtering", "Require normal map to use _NA or _OSNA suffix for normal map name", true);
// All material properties
// All GroupPropery below need to define a
// [HideInInspector] _XXXShow("_XXXShow", Float) = 0.0 parameter in the StackLit.shader to work
new GroupProperty(this, "_MaterialFeatures", "Material Features", new BaseProperty[]
{
EnableDetails,
EnableDualSpecularLobe,
EnableAnisotropy,
EnableCoat,
EnableCoatNormalMap,
EnableIridescence,
EnableSSS,
EnableTransmission
}),
new TextureProperty(this, k_Smoothness1Map, k_Smoothness1, "Smoothness", "Smoothness", false, false),
// TODO: Special case for normal maps.
new TextureProperty(this, k_NormalMap, k_NormalScale, "Normal", "Normal Map", false, false, true),
//new TextureProperty(this, k_BaseColorMap, k_BaseColor, "Dielectric IoR", "Index of Refraction for Dielectric", false),
new Property(this, k_DielectricIor, "DieletricIor", "IOR use for dielectric material (i.e non metallic material)", false),
new TextureProperty(this, k_SmoothnessAMap, k_SmoothnessA, "Smoothness", "Smoothness", false, false),
new TextureProperty(this, k_NormalMap, k_NormalScale, "Normal", "Normal Map", true, false, true),
new GroupProperty(this, "_Emissive", "Emissive", new BaseProperty[]
new GroupProperty(this, "_Details", "Details", new BaseProperty[]
new TextureProperty(this, k_EmissiveColorMap, k_EmissiveColor, "Emissive Color", "Emissive", true, false),
new Property(this, k_EmissiveIntensity, "Emissive Intensity", "Emissive", false),
new Property(this, k_AlbedoAffectEmissive, "Albedo Affect Emissive", "Specifies whether or not the emissive color is multiplied by the albedo.", false),
}),
new TextureProperty(this, k_DetailMaskMap, "", "Detail Mask Map", "Detail Mask Map", false, false),
new TextureProperty(this, k_DetailNormalMap, k_DetailNormalScale, "Detail Normal Map", "Detail Normal Map Scale", true, false, true),
new TextureProperty(this, k_DetailSmoothnessMap, k_DetailSmoothnessScale, "Detail Smoothness", "Detail Smoothness", true, false),
}, _ => EnableDetails.BoolValue == true),
new GroupProperty(this, "_DualSpecularLobe", "Dual Specular Lobe", new BaseProperty[]
{
new TextureProperty(this, k_SmoothnessBMap, k_SmoothnessB, "Smoothness B", "Smoothness B", false, false),
new Property(this, k_LobeMix, "Lobe Mix", "Lobe Mix", false),
}, _ => EnableDualSpecularLobe.BoolValue == true),
new GroupProperty(this, "_Anisotropy", "Anisotropy", new BaseProperty[]
{
new Property(this, k_Anisotropy, "Anisotropy", "Anisotropy of base layer", false),
// TODO: Tangent map and rotation
}, _ => EnableAnisotropy.BoolValue == true),
new Property(this, "_CoatEnable", "Coat Enable", "Enable coat layer with true vertical physically based BSDF mixing", false),
new Property(this, "_CoatSmoothness", "Coat Smoothness", "Top layer smoothness", false),
new TextureProperty(this, k_CoatSmoothnessMap, k_CoatSmoothness, "Coat smoothness", "Coat smoothness", false),
new TextureProperty(this, k_CoatNormalMap, k_CoatNormalScale, "Coat Normal Map", "Coat Normal Map", true, false, true, _ => EnableCoatNormalMap.BoolValue == true),
}),
}, _ => EnableCoat.BoolValue == true),
new GroupProperty(this, "_Iridescence", "Iridescence", new BaseProperty[]
{
//just to test: to use the same EvalIridescence as lit, find a good mapping for the top IOR (over the iridescence dielectric film)
//when having iridescence:
//new Property(this, "_IridescenceIor", "TopIOR", "Index of refraction on top of iridescence layer", false),
new TextureProperty(this, k_IridescenceMaskMap, k_IridescenceMask, "Iridescence Mask", "Iridescence Mask", false),
new TextureProperty(this, k_IridescenceThicknessMap, k_IridescenceThickness, "Iridescence thickness (Remap to 0..3000nm)", "Iridescence thickness (Remap to 0..3000nm)", false),
}, _ => EnableIridescence.BoolValue == true),
}/*, _ => _materialId == MaterialId.SubSurfaceScattering*/),
}, _ => EnableSSS.BoolValue == true),
new GroupProperty(this, "_Lobe2", "Second Specular Lobe", new BaseProperty[]
new GroupProperty(this, "_Transmission", "Transmission", new BaseProperty[]
new TextureProperty(this, k_Smoothness2Map, k_Smoothness2, "Smoothness2", "Smoothness2", false, false),
new Property(this, k_LobeMix, "Lobe Mix", "Lobe Mix", false),
}),
new DiffusionProfileProperty(this, k_DiffusionProfile, "Diffusion Profile", "A profile determines the shape of the SSS/transmission filter.", false, _ => EnableSSS.BoolValue == false),
new TextureProperty(this, k_ThicknessMap, k_Thickness, "Thickness", "If subsurface scattering is enabled, low values allow some light to be transmitted through the object.", false),
}, _ => EnableTransmission.BoolValue == true),
new GroupProperty(this, "_Anisotropy", "Anisotropy", new BaseProperty[]
new GroupProperty(this, "_Emissive", "Emissive", new BaseProperty[]
new Property(this, k_Anisotropy, "Anisotropy", "Anisotropy of base layer", false),
new TextureProperty(this, k_EmissiveColorMap, k_EmissiveColor, "Emissive Color", "Emissive", true, false),
new Property(this, k_AlbedoAffectEmissive, "Albedo Affect Emissive", "Specifies whether or not the emissive color is multiplied by the albedo.", false),
new GroupProperty(this, "_Transmission", "Transmission", new BaseProperty[]
new GroupProperty(this, "_SpecularAntiAliasing", "Specular Anti-Aliasing", new BaseProperty[]
new DiffusionProfileProperty(this, k_DiffusionProfile, "Diffusion Profile", "A profile determines the shape of the SSS/transmission filter.", false),
new TextureProperty(this, k_ThicknessMap, k_Thickness, "Thickness", "If subsurface scattering is enabled, low values allow some light to be transmitted through the object.", false),
EnableTextureNormalFiltering,
EnableGeometricNormalFiltering,
new Property(this, "_SpecularAntiAliasingThreshold", "Threshold", "Threshold", false, _ => (EnableGeometricNormalFiltering.BoolValue || EnableTextureNormalFiltering.BoolValue) == true),
new Property(this, "_SpecularAntiAliasingScreenSpaceVariance", "Screen Space Variance", "Screen Space Variance (should be less than 0.25)", false, _ => EnableGeometricNormalFiltering.BoolValue == true),
//new GroupProperty(this, "_Iridescence", "Iridescence", new BaseProperty[]
//{
// new TextureProperty(this, k_BaseColorMap, k_BaseColor, "Index of Refraction", "Index of Refraction for Iridescence", false),
// new TextureProperty(this, k_BaseColorMap, k_BaseColor, "Thickness", "Thickness", false),
//}),
//new GroupProperty(this, "_Glint", "Glint", new BaseProperty[]
//{
// new TextureProperty(this, k_BaseColorMap, k_BaseColor, "Density", "Density:", false),
// new TextureProperty(this, k_BaseColorMap, k_BaseColor, "Tint", "Tint", false),
//}),
new GroupProperty(this, "_Debug", "Debug", new BaseProperty[]
{
new Property(this, "_VlayerRecomputePerLight", "Vlayer Recompute Per Light", "", false),
new Property(this, "_VlayerUseRefractedAnglesForBase", "Vlayer Use Refracted Angles For Base", "", false),
new Property(this, "_DebugEnable", "Debug Enable", "Switch to a debug version of the shader", false),
new Property(this, "_DebugEnvLobeMask", "DebugEnvLobeMask", "xyz is Environments Lobe 0 1 2 Enable, w is Enable VLayering", false),
new Property(this, "_DebugLobeMask", "DebugLobeMask", "xyz is Analytical Lobe 0 1 2 Enable", false),
new Property(this, "_DebugAniso", "DebugAniso", "x is Hack Enable, y is factor", false),
}),
return material.GetFloat(k_EmissiveIntensity) > 0.0f;
return (material.GetColor(k_EmissiveColor) != Color.black) || material.GetTexture(k_EmissiveColorMap);
}
protected override void FindBaseMaterialProperties(MaterialProperty[] props)

// TODO: Caution this can generate a lot of garbage collection call ?
string useMapPropertyName = basePropertyName + "UseMap";
string mapPropertyName = basePropertyName + "Map";
string remapPropertyName = basePropertyName + "Remap";
string invertPropertyName = basePropertyName + "RemapInverted";
string rangePropertyName = basePropertyName + "Range";
string remapPropertyName = basePropertyName + "MapRemap";
string invertPropertyName = basePropertyName + "MapRemapInverted";
string rangePropertyName = basePropertyName + "MapRange";
Vector4 rangeVector = material.GetVector(remapPropertyName);
if (material.HasProperty(invertPropertyName) && material.GetFloat(invertPropertyName) > 0.0f)
if (material.HasProperty(remapPropertyName) && material.HasProperty(rangePropertyName))
float s = rangeVector.x;
rangeVector.x = rangeVector.y;
rangeVector.y = s;
Vector4 rangeVector = material.GetVector(remapPropertyName);
if (material.HasProperty(invertPropertyName) && material.GetFloat(invertPropertyName) > 0.0f)
{
float s = rangeVector.x;
rangeVector.x = rangeVector.y;
rangeVector.y = s;
}
material.SetVector(rangePropertyName, rangeVector);
material.SetFloat(useMapPropertyName, 1.0f);
material.SetVector(rangePropertyName, rangeVector);
if (material.HasProperty(useMapPropertyName))
{
material.SetFloat(useMapPropertyName, 1.0f);
}
int channel = (int)material.GetFloat(channelPropertyName);
switch (channel)
if (material.HasProperty(channelPropertyName))
case 0:
material.SetVector(channelMaskPropertyName, new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
break;
case 1:
material.SetVector(channelMaskPropertyName, new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
break;
case 2:
material.SetVector(channelMaskPropertyName, new Vector4(0.0f, 0.0f, 1.0f, 0.0f));
break;
case 3:
material.SetVector(channelMaskPropertyName, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
break;
int channel = (int)material.GetFloat(channelPropertyName);
switch (channel)
{
case 0:
material.SetVector(channelMaskPropertyName, new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
break;
case 1:
material.SetVector(channelMaskPropertyName, new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
break;
case 2:
material.SetVector(channelMaskPropertyName, new Vector4(0.0f, 0.0f, 1.0f, 0.0f));
break;
case 3:
material.SetVector(channelMaskPropertyName, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
break;
}
material.SetFloat(useMapPropertyName, 0.0f);
material.SetVector(rangePropertyName, new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
material.SetVector(channelMaskPropertyName, new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
if (material.HasProperty(useMapPropertyName))
{
material.SetFloat(useMapPropertyName, 0.0f);
}
if (material.HasProperty(rangePropertyName))
{
material.SetVector(rangePropertyName, new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
}
if (material.HasProperty(channelPropertyName))
{
material.SetVector(channelMaskPropertyName, new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
}
}
}

//TODO see BaseLitUI.cs:SetupBaseLitKeywords (stencil etc)
SetupBaseUnlitKeywords(material);
SetupBaseUnlitMaterialPass(material);

{
BaseLitGUI.DoubleSidedNormalMode doubleSidedNormalMode = (BaseLitGUI.DoubleSidedNormalMode)material.GetFloat(k_DoubleSidedNormalMode);
BaseLitGUI.DoubleSidedNormalMode doubleSidedNormalMode =
(BaseLitGUI.DoubleSidedNormalMode)material.GetFloat(k_DoubleSidedNormalMode);
switch (doubleSidedNormalMode)
{
case BaseLitGUI.DoubleSidedNormalMode.Mirror: // Mirror mode (in tangent space)

}
}
//NOTE: For SSS in forward and split lighting, obviously we don't have a gbuffer pass,
// so no stencil tagging there, but velocity? To check...
//TODO: stencil state, displacement, wind, depthoffset, tessellation
CoreUtils.SetKeyword(material, "_NORMALMAP_TANGENT_SPACE", true);
CoreUtils.SetKeyword(material, "_NORMALMAP", material.GetTexture(k_NormalMap));
SetupTextureMaterialProperty(material, k_Smoothness1);
SetupTextureMaterialProperty(material, k_Smoothness2);
SetupTextureMaterialProperty(material, k_SmoothnessA);
SetupTextureMaterialProperty(material, k_SmoothnessB);
SetupTextureMaterialProperty(material, k_Anisotropy);
SetupTextureMaterialProperty(material, k_IridescenceThickness);
SetupTextureMaterialProperty(material, k_IridescenceMask);
SetupTextureMaterialProperty(material, k_CoatSmoothness);
// details
SetupTextureMaterialProperty(material, k_DetailMask);
SetupTextureMaterialProperty(material, k_DetailSmoothness);
// Check if we are using specific UVs.
TextureProperty.UVMapping[] uvIndices = new[]

(TextureProperty.UVMapping)material.GetFloat(k_NormalMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_Smoothness1MapUV),
(TextureProperty.UVMapping)material.GetFloat(k_Smoothness2MapUV),
(TextureProperty.UVMapping)material.GetFloat(k_SmoothnessAMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_SmoothnessBMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_AnisotropyMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_IridescenceThicknessMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_IridescenceMaskMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_CoatSmoothnessMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_CoatNormalMapUV),
// Details
(TextureProperty.UVMapping)material.GetFloat(k_DetailMaskMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_DetailSmoothnessMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_DetailNormalMapUV),
bool requireUv2 = false;
bool requireUv3 = false;
// Set keyword for mapping
//bool requireUv2 = false;
//bool requireUv3 = false;
requireUv2 = requireUv2 || uvIndices[i] == TextureProperty.UVMapping.UV2;
requireUv3 = requireUv3 || uvIndices[i] == TextureProperty.UVMapping.UV3;
//requireUv2 = requireUv2 || uvIndices[i] == TextureProperty.UVMapping.UV2;
//requireUv3 = requireUv3 || uvIndices[i] == TextureProperty.UVMapping.UV3;
//CoreUtils.SetKeyword(material, "_USE_UV2", requireUv2);
//CoreUtils.SetKeyword(material, "_USE_UV3", requireUv3);
bool anisotropyEnabled = material.HasProperty(k_Anisotropy) && (material.GetFloat(k_Anisotropy) != 0.0f);
// TODO: When we have a map, also test for map for enable. (This scheme doesn't allow enabling from
// neutral value though, better to still have flag and uncheck it in UI code when reach neutral
// value and re-enable otherwise).
bool coatEnabled = material.HasProperty(k_CoatEnable) && (material.GetFloat(k_CoatEnable) > 0.0f);
bool dualLobeEnabled = material.HasProperty(k_LobeMix) && (material.GetFloat(k_LobeMix) > 0.0f);
bool detailsEnabled = material.HasProperty(k_EnableDetails) && material.GetFloat(k_EnableDetails) > 0.0f;
CoreUtils.SetKeyword(material, "_USE_DETAILMAP", detailsEnabled);
// Note that we don't use the materialId (cf Lit.shader) mechanism in the UI
bool dualSpecularLobeEnabled = material.HasProperty(k_EnableDualSpecularLobe) && material.GetFloat(k_EnableDualSpecularLobe) > 0.0f;
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_DUAL_SPECULAR_LOBE", dualSpecularLobeEnabled);
bool anisotropyEnabled = material.HasProperty(k_EnableAnisotropy) && material.GetFloat(k_EnableAnisotropy) > 0.0f;
bool iridescenceEnabled = material.HasProperty(k_EnableIridescence) && material.GetFloat(k_EnableIridescence) > 0.0f;
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_IRIDESCENCE", iridescenceEnabled);
bool transmissionEnabled = material.HasProperty(k_EnableTransmission) && material.GetFloat(k_EnableTransmission) > 0.0f;
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_TRANSMISSION", transmissionEnabled);
bool sssEnabled = material.HasProperty(k_EnableSubsurfaceScattering) && material.GetFloat(k_EnableSubsurfaceScattering) > 0.0f;
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SUBSURFACE_SCATTERING", sssEnabled);
bool coatEnabled = material.HasProperty(k_EnableCoat) && material.GetFloat(k_EnableCoat) > 0.0f;
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_DUAL_LOBE", dualLobeEnabled);
bool coatNormalMapEnabled = material.HasProperty(k_EnableCoatNormalMap) && material.GetFloat(k_EnableCoatNormalMap) > 0.0f;
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_COAT_NORMALMAP", coatNormalMapEnabled);
// TEMP - Remove once dev is finish
bool debugEnabled = material.HasProperty("_DebugEnable") && material.GetFloat("_DebugEnable") > 0.0f;
CoreUtils.SetKeyword(material, "_STACKLIT_DEBUG", debugEnabled);
bool vlayerRecomputePerLight = material.HasProperty("_VlayerRecomputePerLight") && material.GetFloat("_VlayerRecomputePerLight") > 0.0f;
CoreUtils.SetKeyword(material, "_VLAYERED_RECOMPUTE_PERLIGHT", vlayerRecomputePerLight);
bool vlayerUseRefractedAnglesForBase = material.HasProperty("_VlayerUseRefractedAnglesForBase") && material.GetFloat("_VlayerUseRefractedAnglesForBase") > 0.0f;
CoreUtils.SetKeyword(material, "_VLAYERED_USE_REFRACTED_ANGLES_FOR_BASE", vlayerUseRefractedAnglesForBase);
// Set the reference value for the stencil test - required for SSS
int stencilRef = (int)StencilLightingUsage.RegularLighting;
if (sssEnabled)
{
stencilRef = (int)StencilLightingUsage.SplitLighting;
}
// As we tag both during velocity pass and Gbuffer pass we need a separate state and we need to use the write mask
material.SetInt(kStencilRef, stencilRef);
material.SetInt(kStencilWriteMask, (int)HDRenderPipeline.StencilBitMask.LightingMask);
material.SetInt(kStencilRefMV, (int)HDRenderPipeline.StencilBitMask.ObjectVelocity);
material.SetInt(kStencilWriteMaskMV, (int)HDRenderPipeline.StencilBitMask.ObjectVelocity);
}
}
} // namespace UnityEditor

63
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/StackLit/BaseMaterialUI.cs


set { m_MaterialProperty.vectorValue = value; }
}
public Property(BaseMaterialGUI parent, string propertyName, string guiText, bool isMandatory = true)
: this(parent, propertyName, guiText, string.Empty, isMandatory)
public Property(BaseMaterialGUI parent, string propertyName, string guiText, bool isMandatory = true, Func<object, bool> isVisible = null)
: this(parent, propertyName, guiText, string.Empty, isMandatory, isVisible)
public Property(BaseMaterialGUI parent, string propertyName, string guiText, string toolTip, bool isMandatory = true)
: base(parent)
public Property(BaseMaterialGUI parent, string propertyName, string guiText, string toolTip, bool isMandatory = true, Func<object, bool> isVisible = null)
: base(parent, isVisible)
{
m_GuiContent = new GUIContent(guiText, toolTip);
PropertyName = propertyName;

private readonly string[] m_Options;
private readonly int[] m_Values = null;
public ComboProperty(BaseMaterialGUI parent, string propertyName, string guiText, string[] options, bool isMandatory = true)
: base(parent, propertyName, guiText, isMandatory)
public ComboProperty(BaseMaterialGUI parent, string propertyName, string guiText, string[] options, bool isMandatory = true, Func<object, bool> isVisible = null)
: base(parent, propertyName, guiText, isMandatory, isVisible)
public ComboProperty(BaseMaterialGUI parent, string propertyName, string guiText, string toolTip, string[] options, bool isMandatory = true)
: base(parent, propertyName, guiText, toolTip, isMandatory)
public ComboProperty(BaseMaterialGUI parent, string propertyName, string guiText, string toolTip, string[] options, bool isMandatory = true, Func<object, bool> isVisible = null)
: base(parent, propertyName, guiText, toolTip, isMandatory, isVisible)
public ComboProperty(BaseMaterialGUI parent, string propertyName, string guiText, string[] options, int[] values, bool isMandatory = true)
: base(parent, propertyName, guiText, isMandatory)
public ComboProperty(BaseMaterialGUI parent, string propertyName, string guiText, string[] options, int[] values, bool isMandatory = true, Func<object, bool> isVisible = null)
: base(parent, propertyName, guiText, isMandatory, isVisible)
public ComboProperty(BaseMaterialGUI parent, string propertyName, string guiText, string toolTip, string[] options, int[] values, bool isMandatory = true)
: base(parent, propertyName, guiText, toolTip, isMandatory)
public ComboProperty(BaseMaterialGUI parent, string propertyName, string guiText, string toolTip, string[] options, int[] values, bool isMandatory = true, Func<object, bool> isVisible = null)
: base(parent, propertyName, guiText, toolTip, isMandatory, isVisible)
{
m_Options = options;
m_Values = values;

public class DiffusionProfileProperty : Property
{
public DiffusionProfileProperty(BaseMaterialGUI parent, string propertyName, string guiText, string toolTip, bool isMandatory = true)
: base(parent, propertyName, guiText, toolTip, isMandatory)
public DiffusionProfileProperty(BaseMaterialGUI parent, string propertyName, string guiText, string toolTip, bool isMandatory = true, Func<object, bool> isVisible = null)
: base(parent, propertyName, guiText, toolTip, isMandatory, isVisible)
{
}

using (var scope = new EditorGUI.ChangeCheckScope())
{
int profileID = (int) FloatValue;
int profileID = (int)FloatValue;
using (new EditorGUILayout.HorizontalScope())
{

private MaterialProperty m_ExtraProperty;
public TextureOneLineProperty(BaseMaterialGUI parent, string propertyName, string guiText, bool isMandatory = true)
: base(parent, propertyName, guiText, isMandatory)
public TextureOneLineProperty(BaseMaterialGUI parent, string propertyName, string guiText, bool isMandatory = true, Func<object, bool> isVisible = null)
: base(parent, propertyName, guiText, isMandatory, isVisible)
public TextureOneLineProperty(BaseMaterialGUI parent, string propertyName, string guiText, string toolTip, bool isMandatory = true)
: base(parent, propertyName, guiText, toolTip, isMandatory)
public TextureOneLineProperty(BaseMaterialGUI parent, string propertyName, string guiText, string toolTip, bool isMandatory = true, Func<object, bool> isVisible = null)
: base(parent, propertyName, guiText, toolTip, isMandatory, isVisible)
public TextureOneLineProperty(BaseMaterialGUI parent, string propertyName, string extraPropertyName, string guiText, string toolTip, bool isMandatory = true)
: base(parent, propertyName, guiText, toolTip, isMandatory)
public TextureOneLineProperty(BaseMaterialGUI parent, string propertyName, string extraPropertyName, string guiText, string toolTip, bool isMandatory = true, Func<object, bool> isVisible = null)
: base(parent, propertyName, guiText, toolTip, isMandatory, isVisible)
{
ExtraPropertyName = extraPropertyName;
}

internal override string ToShaderPropertiesStringInternal()
{
return string.Format("{0}(\"{1}\", 2D) = \"white\" {{}}\n" +
"{2}(\"{3}\", Float) = 0.0",
PropertyName, PropertyText,
ExtraPropertyName, ExtraPropertyName);
"{2}(\"{3}\", Float) = 0.0",
PropertyName, PropertyText,
ExtraPropertyName, ExtraPropertyName);
}
}

public bool m_IsNormalMap;
public TextureProperty(BaseMaterialGUI parent, string propertyName, string constantPropertyName, string guiText, bool useConstantAsTint, bool isMandatory = true, bool isNormalMap = false)
: this(parent, propertyName, constantPropertyName, guiText, string.Empty, useConstantAsTint, isMandatory, isNormalMap)
public TextureProperty(BaseMaterialGUI parent, string propertyName, string constantPropertyName, string guiText, bool useConstantAsTint, bool isMandatory = true, bool isNormalMap = false, Func<object, bool> isVisible = null)
: this(parent, propertyName, constantPropertyName, guiText, string.Empty, useConstantAsTint, isMandatory, isNormalMap, isVisible)
public TextureProperty(BaseMaterialGUI parent, string propertyName, string constantPropertyName, string guiText, string toolTip, bool useConstantAsTint, bool isMandatory = true, bool isNormalMap = false)
: base(parent, propertyName, guiText, toolTip, isMandatory)
public TextureProperty(BaseMaterialGUI parent, string propertyName, string constantPropertyName, string guiText, string toolTip, bool useConstantAsTint, bool isMandatory = true, bool isNormalMap = false, Func<object, bool> isVisible = null)
: base(parent, propertyName, guiText, toolTip, isMandatory, isVisible)
{
m_IsNormalMap = isNormalMap;

m_ChannelProperty = new ComboProperty(parent, propertyName + "Channel", "Channel", Enum.GetNames(typeof(Channel)), false);
m_RemapProperty = new Property(parent, constantPropertyName + "Remap", "Remapping", "Defines the range to remap/scale the values in texture", false);
m_InvertRemapProperty = new Property(parent, constantPropertyName + "RemapInverted", "Invert Remapping", "Whether the mapping values are inverted.", false);
m_RemapProperty = new Property(parent, propertyName + "Remap", "Remapping", "Defines the range to remap/scale the values in texture", false);
m_InvertRemapProperty = new Property(parent, propertyName + "RemapInverted", "Invert Remapping", "Whether the mapping values are inverted.", false);
}
public override void OnFindProperty(MaterialProperty[] props)

"[HideInInspector] {0}Range(\"{1} Range\", Vector) = (0, 1, 0, 0)\n",
m_ConstantPropertyName, constantName, PropertyName);
}
}
}
#endregion
}
}

9
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/LayeredLit/LayeredLitUI.cs


case ShaderUtil.ShaderPropertyType.TexEnv:
{
material.SetTexture(layerPropertyName, layerMaterial.GetTexture(propertyName));
if(!excludeUVMappingProperties)
if (!excludeUVMappingProperties)
{
material.SetTextureOffset(layerPropertyName, layerMaterial.GetTextureOffset(propertyName));
material.SetTextureScale(layerPropertyName, layerMaterial.GetTextureScale(propertyName));

return result;
}
void DoLayeringInputGUI()
{

return layerChanged;
}
protected override bool ShouldEmissionBeEnabled(Material mat)
protected override bool ShouldEmissionBeEnabled(Material material)
return mat.GetFloat(kEmissiveIntensity) > 0.0f;
return (material.GetColor(kEmissiveColor) != Color.black) || material.GetTexture(kEmissiveColorMap);
}
protected override void SetupMaterialKeywordsAndPassInternal(Material material)

CoreUtils.SetKeyword(material, "_HEIGHT_BASED_BLEND", useHeightBasedBlend);
bool useDensityModeEnable = false;
for (int i = 0; i < material.GetInt(kLayerCount); ++i )
for (int i = 0; i < material.GetInt(kLayerCount); ++i)
{
useDensityModeEnable |= material.GetFloat(kOpacityAsDensity + i) != 0.0f;
}

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


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

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


var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
if (HDEditorUtils.ResetMaterialKeywords(mat))
Console.WriteLine("[HDEditorCLI][ResetMaterialKeywords] " + path);
Console.WriteLine("[HDEditorCLI][ResetMaterialKeywords] " + path);
}
break;
}

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


{ "HDRenderPipeline/Decal", DecalUI.SetupMaterialKeywordsAndPass }
};
// Note: This function returns null if used with a package setup.
static string GetScriptableRenderPipelinePath()
{
// User can create their own directory for SRP, so we need to find the current path that they use.
// We do that using the SRPMARKER file.
var srpMarkerPath = Directory.GetFiles(Application.dataPath, "SRPMARKER", SearchOption.AllDirectories).FirstOrDefault();
if (srpMarkerPath != null)
return new Uri(Application.dataPath).MakeRelativeUri(new Uri(Directory.GetParent(srpMarkerPath).ToString())).ToString();
return null;
}
var srpPath = GetScriptableRenderPipelinePath();
if (srpPath != null)
return Path.Combine(srpPath, "ScriptableRenderPipeline/HDRenderPipeline/HDRP/");
// If the SRPMARKER is not found, we assume that a package setup is used.
var srpPath = GetScriptableRenderPipelinePath();
if (srpPath != null)
return Path.Combine(srpPath, "PostProcessing/PostProcessing/");
// If the SRPMARKER is not found, we assume that a package setup is used.
var srpPath = GetScriptableRenderPipelinePath();
if (srpPath != null)
return Path.Combine(srpPath, "ScriptableRenderPipeline/Core/CoreRP/");
// If the SRPMARKER is not found, we assume that a package setup is used.
}
public static T LoadAsset<T>(string relativePath) where T : UnityEngine.Object
{
return AssetDatabase.LoadAssetAtPath<T>(GetHDRenderPipelinePath() + relativePath);
}
public static bool ResetMaterialKeywords(Material material)

{
CoreEditorUtils.RemoveMaterialKeywords(material);
// We need to reapply ToggleOff/Toggle keyword after reset via ApplyMaterialPropertyDrawers
MaterialEditor.ApplyMaterialPropertyDrawers(material);
}
public static List<BaseShaderPreprocessor> GetBaseShaderPreprocessorList()
{
var baseType = typeof(BaseShaderPreprocessor);
var assembly = baseType.Assembly;
var types = assembly.GetTypes()
.Where(t => t.IsSubclassOf(baseType))
.Select(Activator.CreateInstance)
.Cast<BaseShaderPreprocessor>()
.ToList();
return types;
}
}
}

6
com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/VisualEnvironmentEditor.cs


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

void UpdateSkyIntPopupData()
{
if(m_SkyClassNames == null)
if (m_SkyClassNames == null)
{
m_SkyClassNames = new List<GUIContent>();
m_SkyUniqueIDs = new List<int>();

PropertyField(m_FogType);
}
}
}
}

6
com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/SkySettingsEditor.cs


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

{
PropertyField(m_SkyExposure);
PropertyField(m_SkyMultiplier);
if(enableRotation)
if (enableRotation)
PropertyField(m_SkyRotation);
PropertyField(m_EnvUpdateMode);

}
}
}
}
}

9
com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/BakingSkyEditor.cs


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

{
m_VolumeProfile = serializedObject.FindProperty("m_Profile");
m_SkyUniqueID = serializedObject.FindProperty("m_BakingSkyUniqueID");
}
void UpdateSkyIntPopupData(bool reset = false)

m_SkyUniqueIDs.Add(0);
VolumeProfile profile = m_VolumeProfile.objectReferenceValue as VolumeProfile;
if(profile != null)
if (profile != null)
{
var skyTypesDict = SkyManager.skyTypesDict;

{
InitializeProperties();
if(m_VolumeProfile.objectReferenceValue == null)
if (m_VolumeProfile.objectReferenceValue == null)
if(volume != null)
if (volume != null)
{
bakingSky.profile = volume.sharedProfile;
}

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


{
private SerializedDataParameter m_Albedo;
private SerializedDataParameter m_MeanFreePath;
private SerializedDataParameter m_Asymmetry;
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_Asymmetry = Unpack(o.Find(x => x.asymmetry));
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_Asymmetry);
PropertyField(m_Albedo, s_AlbedoLabel);
PropertyField(m_MeanFreePath, s_MeanFreePathLabel);
PropertyField(m_Anisotropy, s_AnisotropyLabel);
PropertyField(m_GlobalLightProbeDimmer, s_GlobalLightProbeDimmerLabel);
}
}
}

4
com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/AtmosphericScattering/LinearFogEditor.cs


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

PropertyField(m_FogHeightEnd);
}
}
}
}

6
com.unity.render-pipelines.high-definition/HDRP/Editor/Sky/AtmosphericScattering/AtmosphericScatteringEditor.cs


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

PropertyField(m_Density);
PropertyField(m_ColorMode);
EditorGUI.indentLevel++;
if(!m_ColorMode.value.hasMultipleDifferentValues && (FogColorMode)m_ColorMode.value.intValue == FogColorMode.ConstantColor)
if (!m_ColorMode.value.hasMultipleDifferentValues && (FogColorMode)m_ColorMode.value.intValue == FogColorMode.ConstantColor)
{
PropertyField(m_Color);
}

EditorGUI.indentLevel--;
}
}
}
}

3
com.unity.render-pipelines.high-definition/HDRP/Editor/com.unity.render-pipelines.high-definition.Editor.asmdef


"com.unity.render-pipelines.core.Editor",
"com.unity.render-pipelines.high-definition.Runtime",
"com.unity.postprocessing.Runtime",
"com.unity.postprocessing.Editor"
"com.unity.postprocessing.Editor",
"Unity.ShaderGraph.Editor"
],
"optionalUnityReferences": [],
"includePlatforms": [

99
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipelineResources/ReflectionProbesPreview.shader


Shader "Debug/ReflectionProbePreview"
Shader "Debug/ReflectionProbePreview"
Properties
{
_Cubemap("_Cubemap", Cube) = "white" {}
_CameraWorldPosition("_CameraWorldPosition", Vector) = (1,1,1,1)
_MipLevel("_MipLevel", Range(0.0,7.0)) = 0.0
_Exposure("_Exposure", Range(-10.0,10.0)) = 0.0
Properties
{
_Cubemap("_Cubemap", Cube) = "white" {}
_CameraWorldPosition("_CameraWorldPosition", Vector) = (1,1,1,1)
_MipLevel("_MipLevel", Range(0.0,7.0)) = 0.0
_Exposure("_Exposure", Range(-10.0,10.0)) = 0.0
}
SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" "RenderType" = "Opaque" "Queue" = "Transparent" }
ZWrite On
Cull Back
}
Pass
{
Name "ForwardUnlit"
Tags{ "LightMode" = "Forward" }
SubShader
{
Tags{ "RenderPipeline" = "HDRenderPipeline" "RenderType" = "Opaque" "Queue" = "Transparent" }
ZWrite On
Cull Back
Pass
{
Name "ForwardUnlit"
Tags{ "LightMode" = "Forward" }
HLSLPROGRAM
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag

struct appdata
{
float4 positionOS : POSITION;
float3 normalOS : NORMAL;
};
struct appdata
{
float4 positionOS : POSITION;
float3 normalOS : NORMAL;
};
struct v2f
{
float4 positionCS : SV_POSITION;
float3 normalWS : NORMAL;
float3 positionWS : TEXCOORD0;
};
struct v2f
{
float4 positionCS : SV_POSITION;
float3 normalWS : NORMAL;
float3 positionWS : TEXCOORD0;
};
float3 _CameraWorldPosition;
float _MipLevel;
float _Exposure;
float3 _CameraWorldPosition;
float _MipLevel;
float _Exposure;
v2f vert(appdata v)
{
v2f o;
v2f vert(appdata v)
{
v2f o;
o.positionWS = GetCameraRelativePositionWS(o.positionWS);
return o;
}
return o;
}
float4 frag(v2f i) : SV_Target
{
//float3 view = normalize(i.worldpos - _CameraWorldPosition);
float3 V = normalize(i.positionWS - GetPrimaryCameraPosition());
float3 R = reflect(V, i.normalWS);
float4 color = SAMPLE_TEXTURECUBE_LOD(_Cubemap, sampler_Cubemap, R, _MipLevel).rgba;
float4 frag(v2f i) : SV_Target
{
//float3 view = normalize(i.worldpos - _CameraWorldPosition);
float3 V = normalize(i.positionWS - GetPrimaryCameraPosition());
float3 R = reflect(V, i.normalWS);
float4 color = SAMPLE_TEXTURECUBE_LOD(_Cubemap, sampler_Cubemap, R, _MipLevel).rgba;
return float4(color);
}
ENDHLSL
}
}
return float4(color);
}
ENDHLSL
}
}
}

14
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/HDShaderIncludePaths.cs


using System.IO;
using System.IO;
using System.Linq;
using UnityEngine;

[ShaderIncludePath]
public static string[] GetPaths()
{
var srpMarker = Directory.GetFiles(Application.dataPath, "SRPMARKER", SearchOption.AllDirectories).FirstOrDefault();
var paths = new string[srpMarker == null ? 1 : 2];
var index = 0;
if (srpMarker != null)
{
var rootPath = Directory.GetParent(srpMarker).ToString();
paths[index] = Path.Combine(rootPath, "ScriptableRenderPipeline/HDRenderPipeline");
index++;
}
paths[index] = Path.GetFullPath("Packages/com.unity.render-pipelines.high-definition");
var paths = new string[1];
paths[0] = Path.GetFullPath("Packages/com.unity.render-pipelines.high-definition");
return paths;
}
}

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


using UnityEditor.AnimatedValues;
using UnityEditor.AnimatedValues;
using UnityEngine.Events;
namespace UnityEditor.Experimental.Rendering

6
com.unity.render-pipelines.high-definition/HDRP/Editor/Shadows/HDShadowSettingsEditor.cs


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

PropertyField(m_CascadeShadowSplits[i], CoreEditorUtils.GetContent(string.Format("Split {0}", i + 1)));
}
if(LightLoop.s_UseCascadeBorders)
if (LightLoop.s_UseCascadeBorders)
{
EditorGUILayout.Space();

}
}
}
}
}

4
com.unity.render-pipelines.high-definition/HDRP/Editor/Shadows/ContactShadowsEditor.cs


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

}
}
}
}
}

27
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/ShadowInitParametersUI.cs


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

public ShadowInitParametersUI()
: base(0)
{
EditorGUILayout.LabelField(_.GetContent("Shadow Atlas Settings"), EditorStyles.boldLabel);
EditorGUILayout.LabelField(_.GetContent("Shadow"), EditorStyles.boldLabel);
++EditorGUI.indentLevel;
EditorGUILayout.LabelField(_.GetContent("Shadow Atlas"), EditorStyles.boldLabel);
--EditorGUI.indentLevel;
EditorGUILayout.Space();
EditorGUILayout.LabelField(_.GetContent("Shadow Map Budget"), EditorStyles.boldLabel);
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(d.maxPointLightShadows, _.GetContent("Max Point Light Shadows"));
EditorGUILayout.PropertyField(d.maxSpotLightShadows, _.GetContent("Max Spot Light Shadows"));
EditorGUILayout.PropertyField(d.maxDirectionalLightShadows, _.GetContent("Max Directional Light Shadows"));
--EditorGUI.indentLevel;
// Clamp negative values
d.shadowAtlasHeight.intValue = Mathf.Max(0, d.shadowAtlasHeight.intValue);
d.shadowAtlasWidth.intValue = Mathf.Max(0, d.shadowAtlasWidth.intValue);
d.maxPointLightShadows.intValue = Mathf.Max(0, d.maxPointLightShadows.intValue);
d.maxSpotLightShadows.intValue = Mathf.Max(0, d.maxSpotLightShadows.intValue);
d.maxDirectionalLightShadows.intValue = Mathf.Max(0, d.maxDirectionalLightShadows.intValue);
--EditorGUI.indentLevel;
}
}

9
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedShadowInitParameters.cs


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

public SerializedProperty shadowAtlasWidth;
public SerializedProperty shadowAtlasHeight;
public SerializedProperty maxPointLightShadows;
public SerializedProperty maxSpotLightShadows;
public SerializedProperty maxDirectionalLightShadows;
public SerializedShadowInitParameters(SerializedProperty root)
{
this.root = root;

maxPointLightShadows = root.Find((ShadowInitParameters s) => s.maxPointLightShadows);
maxSpotLightShadows = root.Find((ShadowInitParameters s) => s.maxSpotLightShadows);
maxDirectionalLightShadows = root.Find((ShadowInitParameters s) => s.maxDirectionalLightShadows);
}
}
}

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


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

public SerializedProperty supportMSAA;
public SerializedProperty MSAASampleCount;
public SerializedProperty supportSubsurfaceScattering;
public SerializedProperty supportForwardOnly;
public SerializedProperty supportOnlyForward;
public SerializedProperty enableUltraQualitySSS;
[UnityEngine.Serialization.FormerlySerializedAs("enableUltraQualitySSS")]
public SerializedProperty increaseSssSampleCount;
[UnityEngine.Serialization.FormerlySerializedAs("supportVolumetric")]
public SerializedProperty supportVolumetrics;
public SerializedProperty increaseResolutionOfVolumetrics;
public SerializedProperty supportRuntimeDebugDisplay;
public SerializedProperty supportDitheringCrossFade;
public SerializedGlobalDecalSettings decalSettings;
public SerializedGlobalDecalSettings decalSettings;
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);
supportForwardOnly = root.Find((RenderPipelineSettings s) => s.supportForwardOnly);
supportMotionVectors = root.Find((RenderPipelineSettings s) => s.supportMotionVectors);
supportStereo = root.Find((RenderPipelineSettings s) => s.supportStereo);
enableUltraQualitySSS = root.Find((RenderPipelineSettings s) => s.enableUltraQualitySSS);
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));
}
}
}

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


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

4
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedHDRenderPipelineAsset.cs


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

public SerializedProperty renderPipelineResources;
public SerializedProperty diffusionProfileSettings;
public SerializedProperty allowShaderVariantStripping;

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


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

22
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedGlobalDecalSettings.cs


using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine.Experimental.Rendering.HDPipeline;
class SerializedGlobalDecalSettings
{
public SerializedProperty root;
class SerializedGlobalDecalSettings
{
public SerializedProperty root;
public SerializedProperty drawDistance;
public SerializedProperty atlasWidth;
public SerializedProperty drawDistance;
public SerializedProperty atlasWidth;
public SerializedGlobalDecalSettings(SerializedProperty root)
public SerializedGlobalDecalSettings(SerializedProperty root)
drawDistance = root.Find((GlobalDecalSettings s) => s.drawDistance);
atlasWidth = root.Find((GlobalDecalSettings s) => s.atlasWidth);
atlasHeight = root.Find((GlobalDecalSettings s) => s.atlasHeight);
drawDistance = root.Find((GlobalDecalSettings s) => s.drawDistance);
atlasWidth = root.Find((GlobalDecalSettings s) => s.atlasWidth);
atlasHeight = root.Find((GlobalDecalSettings s) => s.atlasHeight);
}
}
}

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


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

public SerializedProperty enableSSAO;
public SerializedProperty enableSubsurfaceScattering;
public SerializedProperty enableTransmission;
public SerializedProperty enableAtmosphericScattering;
public SerializedProperty enableVolumetric;
public SerializedProperty diffuseGlobalDimmer;
public SerializedProperty specularGlobalDimmer;

public SerializedProperty enableMotionVectors;
public SerializedProperty enableObjectMotionVectors;
public SerializedProperty enableDBuffer;
public SerializedProperty enableAtmosphericScattering;
public SerializedProperty enableRoughRefraction;
public SerializedProperty enableTransparentPostpass;
public SerializedProperty enableDistortion;

enableSSAO = root.Find((FrameSettings d) => d.enableSSAO);
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.enableVolumetrics);
diffuseGlobalDimmer = root.Find((FrameSettings d) => d.diffuseGlobalDimmer);
specularGlobalDimmer = root.Find((FrameSettings d) => d.specularGlobalDimmer);
enableForwardRenderingOnly = root.Find((FrameSettings d) => d.enableForwardRenderingOnly);

enableObjectMotionVectors = root.Find((FrameSettings d) => d.enableObjectMotionVectors);
enableDBuffer = root.Find((FrameSettings d) => d.enableDBuffer);
enableAtmosphericScattering = root.Find((FrameSettings d) => d.enableAtmosphericScattering);
enableRoughRefraction = root.Find((FrameSettings d) => d.enableRoughRefraction);
enableTransparentPostpass = root.Find((FrameSettings d) => d.enableTransparentPostpass);
enableDistortion = root.Find((FrameSettings d) => d.enableDistortion);

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


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

static RenderPipelineSettingsUI()
{
Inspector = CED.Group(
SectionPrimarySettings,
CED.space,
CED.Select(
(s, d, o) => s.lightLoopSettings,
(s, d, o) => d.lightLoopSettings,
GlobalLightLoopSettingsUI.Inspector
),
CED.space,
CED.Select(
(s, d, o) => s.shadowInitParams,
(s, d, o) => d.shadowInitParams,
ShadowInitParametersUI.SectionAtlas
),
CED.space,
CED.Select(
(s, d, o) => s.decalSettings,
(s, d, o) => d.decalSettings,
GlobalDecalSettingsUI.Inspector
)
SectionPrimarySettings,
CED.space,
CED.Select(
(s, d, o) => s.lightLoopSettings,
(s, d, o) => d.lightLoopSettings,
GlobalLightLoopSettingsUI.Inspector
),
CED.space,
CED.Select(
(s, d, o) => s.shadowInitParams,
(s, d, o) => d.shadowInitParams,
ShadowInitParametersUI.SectionAtlas
),
CED.space,
CED.Select(
(s, d, o) => s.decalSettings,
(s, d, o) => d.decalSettings,
GlobalDecalSettingsUI.Inspector
)
);
);
CED.Action(Drawer_SectionPrimarySettings)
);
CED.Action(Drawer_SectionPrimarySettings)
);
GlobalDecalSettingsUI decalSettings = new GlobalDecalSettingsUI();
GlobalDecalSettingsUI decalSettings = new GlobalDecalSettingsUI();
}
public override void Reset(SerializedRenderPipelineSettings data, UnityAction repaint)

decalSettings.Reset(data.decalSettings, repaint);
decalSettings.Reset(data.decalSettings, repaint);
base.Reset(data, repaint);
}

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

++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(d.supportShadowMask, _.GetContent("Support Shadow Mask"));
EditorGUILayout.PropertyField(d.supportSSR, _.GetContent("Support SSR"));
EditorGUILayout.PropertyField(d.supportSSAO, _.GetContent("Support SSAO"));
EditorGUILayout.PropertyField(d.supportDBuffer, _.GetContent("Support Decal Buffer"));
EditorGUILayout.PropertyField(d.supportMSAA, _.GetContent("Support Multi Sampling Anti-Aliasing"));
EditorGUILayout.PropertyField(d.MSAASampleCount, _.GetContent("MSAA Sample Count"));
EditorGUILayout.PropertyField(d.supportShadowMask, _.GetContent("Support Shadow Mask|Enable memory (Extra Gbuffer in deferred) and shader variant for shadow mask."));
EditorGUILayout.PropertyField(d.supportSSR, _.GetContent("Support SSR|Enable memory use by SSR effect."));
EditorGUILayout.PropertyField(d.supportSSAO, _.GetContent("Support SSAO|Enable memory use by SSAO effect."));
EditorGUILayout.PropertyField(d.supportDBuffer, _.GetContent("Support Decal Buffer|Enable memory and variant of decal buffer."));
// TODO: Implement MSAA - Hide for now as it doesn't work
//EditorGUILayout.PropertyField(d.supportMSAA, _.GetContent("Support Multi Sampling Anti-Aliasing|This feature doesn't work currently."));
//EditorGUILayout.PropertyField(d.MSAASampleCount, _.GetContent("MSAA Sample Count|Allow to select the level of MSAA."));
EditorGUILayout.PropertyField(d.supportForwardOnly, _.GetContent("Support Forward Only"));
EditorGUILayout.PropertyField(d.supportMotionVectors, _.GetContent("Support Motion Vectors"));
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.enableUltraQualitySSS, _.GetContent("Increase SSS Sample Count"));
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."));
--EditorGUI.indentLevel;
}
}

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


using UnityEditor.AnimatedValues;
using UnityEditor.AnimatedValues;
using UnityEngine;
namespace UnityEditor.Experimental.Rendering

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

EditorGUILayout.PropertyField(p.enableComputeMaterialVariants, _.GetContent("Enable Compute Material Variants"));
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFadeGroup();
EditorGUILayout.EndFadeGroup();
GUILayout.EndVertical();
//EditorGUI.indentLevel--;

17
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/GlobalLightLoopSettingsUI.cs


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

static GlobalLightLoopSettingsUI()
{
Inspector = CED.Group(
SectionCookies,
CED.space,
SectionReflection,
CED.space,
SectionSky
);
SectionCookies,
CED.space,
SectionReflection,
CED.space,
SectionSky
);
}
public static readonly CED.IDrawer Inspector;

public GlobalLightLoopSettingsUI()
: base(0)
{
}
static void Drawer_SectionCookies(GlobalLightLoopSettingsUI s, SerializedGlobalLightLoopSettings d, Editor o)

++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(d.skyReflectionSize, _.GetContent("Sky Reflection Size"));
EditorGUILayout.PropertyField(d.skyLightingOverrideLayerMask, _.GetContent("Sky Lighting Override Mask|This layer mask will define in which layers the sky system will look for sky settings volumes for lighting override"));
if(d.skyLightingOverrideLayerMask.intValue == -1)
if (d.skyLightingOverrideLayerMask.intValue == -1)
{
EditorGUILayout.HelpBox("Be careful, Sky Lighting Override Mask is set to Everything. This is most likely a mistake as it serves no purpose.", MessageType.Warning);
}

33
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/GlobalDecalSettingsUI.cs


using UnityEngine;
using UnityEngine;
using CED = CoreEditorDrawer<GlobalDecalSettingsUI, SerializedGlobalDecalSettings>;
using CED = CoreEditorDrawer<GlobalDecalSettingsUI, SerializedGlobalDecalSettings>;
class GlobalDecalSettingsUI : BaseUI<SerializedGlobalDecalSettings>
{
static GlobalDecalSettingsUI()
class GlobalDecalSettingsUI : BaseUI<SerializedGlobalDecalSettings>
{
static GlobalDecalSettingsUI()
}
}
public static readonly CED.IDrawer Inspector;
public static readonly CED.IDrawer SectionDecalSettings = CED.Action(Drawer_SectionDecalSettings);

{
}
}
static void Drawer_SectionDecalSettings(GlobalDecalSettingsUI s, SerializedGlobalDecalSettings d, Editor o)
{
EditorGUILayout.LabelField(_.GetContent("Decals"), EditorStyles.boldLabel);
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(d.drawDistance, _.GetContent("Draw Distance"));
EditorGUILayout.PropertyField(d.atlasWidth, _.GetContent("Atlas Width"));
static void Drawer_SectionDecalSettings(GlobalDecalSettingsUI s, SerializedGlobalDecalSettings d, Editor o)
{
EditorGUILayout.LabelField(_.GetContent("Decals"), EditorStyles.boldLabel);
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(d.drawDistance, _.GetContent("Draw Distance"));
EditorGUILayout.PropertyField(d.atlasWidth, _.GetContent("Atlas Width"));
--EditorGUI.indentLevel;
}
}
--EditorGUI.indentLevel;
}
}
}

85
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/FrameSettingsUI.cs


using UnityEditor.AnimatedValues;
using UnityEditor.AnimatedValues;
using UnityEngine.Events;
namespace UnityEditor.Experimental.Rendering

static FrameSettingsUI()
{
Inspector = CED.Group(
SectionRenderingPasses,
SectionRenderingSettings,
SectionXRSettings,
SectionLightingSettings,
CED.Select(
(s, d, o) => s.lightLoopSettings,
(s, d, o) => d.lightLoopSettings,
LightLoopSettingsUI.SectionLightLoopSettings
)
);
SectionRenderingPasses,
SectionRenderingSettings,
SectionXRSettings,
SectionLightingSettings,
CED.Select(
(s, d, o) => s.lightLoopSettings,
(s, d, o) => d.lightLoopSettings,
LightLoopSettingsUI.SectionLightLoopSettings
)
);
"Rendering Passes",
(s, p, o) => s.isSectionExpandedRenderingPasses,
FoldoutOption.Indent,
CED.LabelWidth(200, CED.Action(Drawer_SectionRenderingPasses))
);
"Rendering Passes",
(s, p, o) => s.isSectionExpandedRenderingPasses,
FoldoutOption.Indent,
CED.LabelWidth(200, CED.Action(Drawer_SectionRenderingPasses))
);
"Rendering Settings",
(s, p, o) => s.isSectionExpandedRenderingSettings,
FoldoutOption.Indent,
CED.LabelWidth(300,
CED.Action(Drawer_FieldForwardRenderingOnly),
CED.FadeGroup(
(s, d, o, i) => s.isSectionExpandedUseForwardOnly,
FadeOption.None,
CED.Action(Drawer_FieldUseDepthPrepassWithDefferedRendering)
),
CED.Action(Drawer_SectionOtherRenderingSettings)
)
);
"Rendering Settings",
(s, p, o) => s.isSectionExpandedRenderingSettings,
FoldoutOption.Indent,
CED.LabelWidth(300,
CED.Action(Drawer_FieldForwardRenderingOnly),
CED.FadeGroup(
(s, d, o, i) => s.isSectionExpandedUseForwardOnly,
FadeOption.None,
CED.Action(Drawer_FieldUseDepthPrepassWithDefferedRendering)
),
CED.Action(Drawer_SectionOtherRenderingSettings)
)
);
(s, d, o, i) => s.isSectionExpandedXRSupported,
FadeOption.None,
CED.FoldoutGroup(
"XR Settings",
(s, p, o) => s.isSectionExpandedXRSettings,
FoldoutOption.Indent,
CED.LabelWidth(200, CED.Action(Drawer_FieldStereoEnabled))));
(s, d, o, i) => s.isSectionExpandedXRSupported,
FadeOption.None,
CED.FoldoutGroup(
"XR Settings",
(s, p, o) => s.isSectionExpandedXRSettings,
FoldoutOption.Indent,
CED.LabelWidth(200, CED.Action(Drawer_FieldStereoEnabled))));
"Lighting Settings",
(s, p, o) => s.isSectionExpandedLightingSettings,
FoldoutOption.Indent,
CED.LabelWidth(250, CED.Action(Drawer_SectionLightingSettings)));
"Lighting Settings",
(s, p, o) => s.isSectionExpandedLightingSettings,
FoldoutOption.Indent,
CED.LabelWidth(250, CED.Action(Drawer_SectionLightingSettings)));
public AnimBool isSectionExpandedRenderingPasses { get { return m_AnimBools[0]; } }
public AnimBool isSectionExpandedLightingSettings { get { return m_AnimBools[1]; } }

public LightLoopSettingsUI lightLoopSettings = new LightLoopSettingsUI();
public FrameSettingsUI()
: base(7)
: base(7)
{
}

EditorGUILayout.PropertyField(p.enableMotionVectors, _.GetContent("Enable Motion Vectors"));
EditorGUILayout.PropertyField(p.enableObjectMotionVectors, _.GetContent("Enable Object Motion Vectors"));
EditorGUILayout.PropertyField(p.enableDBuffer, _.GetContent("Enable DBuffer"));
EditorGUILayout.PropertyField(p.enableAtmosphericScattering, _.GetContent("Enable Atmospheric Scattering"));
EditorGUILayout.PropertyField(p.enableRoughRefraction, _.GetContent("Enable Rough Refraction"));
EditorGUILayout.PropertyField(p.enableDistortion, _.GetContent("Enable Distortion"));
EditorGUILayout.PropertyField(p.enablePostprocess, _.GetContent("Enable Postprocess"));

EditorGUILayout.PropertyField(p.enableSSAO, _.GetContent("Enable SSAO"));
EditorGUILayout.PropertyField(p.enableSubsurfaceScattering, _.GetContent("Enable Subsurface Scattering"));
EditorGUILayout.PropertyField(p.enableTransmission, _.GetContent("Enable Transmission"));
EditorGUILayout.PropertyField(p.enableAtmosphericScattering, _.GetContent("Enable Atmospheric Scattering"));
EditorGUILayout.PropertyField(p.enableVolumetric, _.GetContent(" Enable Volumetric"));
EditorGUILayout.PropertyField(p.enableShadow, _.GetContent("Enable Shadow"));
EditorGUILayout.PropertyField(p.enableContactShadow, _.GetContent("Enable Contact Shadows"));
EditorGUILayout.PropertyField(p.enableShadowMask, _.GetContent("Enable Shadow Masks"));

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


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

105
com.unity.render-pipelines.high-definition/HDRP/Editor/Camera/HDCameraUI.cs


using System;
using System;
using System.Reflection;
using UnityEditor.AnimatedValues;
using UnityEngine;

{
static HDCameraUI()
{
Inspector = new []
Inspector = new[]
{
SectionPrimarySettings,
// Not used for now

public static readonly CED.IDrawer[] Inspector = null;
public static readonly CED.IDrawer SectionPrimarySettings = CED.Group(
CED.Action(Drawer_FieldClearColorMode),
CED.Action(Drawer_FieldBackgroundColorHDR),
CED.Action(Drawer_FieldClearDepth),
CED.Action(Drawer_FieldCullingMask),
CED.Action(Drawer_FieldVolumeLayerMask),
CED.space,
CED.Action(Drawer_Projection),
CED.Action(Drawer_FieldClippingPlanes),
CED.space,
CED.Action(Drawer_CameraWarnings),
CED.Action(Drawer_FieldRenderingPath),
CED.space
);
CED.Action(Drawer_FieldClearColorMode),
CED.Action(Drawer_FieldBackgroundColorHDR),
CED.Action(Drawer_FieldClearDepth),
CED.Action(Drawer_FieldCullingMask),
CED.Action(Drawer_FieldVolumeLayerMask),
CED.space,
CED.Action(Drawer_Projection),
CED.Action(Drawer_FieldClippingPlanes),
CED.space,
CED.Action(Drawer_CameraWarnings),
CED.Action(Drawer_FieldRenderingPath),
CED.space
);
"Physical Settings",
(s, p, o) => s.isSectionExpandedPhysicalSettings,
FoldoutOption.Indent,
CED.Action(Drawer_FieldAperture),
CED.Action(Drawer_FieldShutterSpeed),
CED.Action(Drawer_FieldIso));
"Physical Settings",
(s, p, o) => s.isSectionExpandedPhysicalSettings,
FoldoutOption.Indent,
CED.Action(Drawer_FieldAperture),
CED.Action(Drawer_FieldShutterSpeed),
CED.Action(Drawer_FieldIso));
"Capture Settings",
(s, p, o) => s.isSectionExpandedCaptureSettings,
FoldoutOption.Indent,
CED.Action(Drawer_FieldOcclusionCulling),
CED.Action(Drawer_FieldNormalizedViewPort));
"Capture Settings",
(s, p, o) => s.isSectionExpandedCaptureSettings,
FoldoutOption.Indent,
CED.Action(Drawer_FieldOcclusionCulling),
CED.Action(Drawer_FieldNormalizedViewPort));
"Output Settings",
(s, p, o) => s.isSectionExpandedOutputSettings,
FoldoutOption.Indent,
"Output Settings",
(s, p, o) => s.isSectionExpandedOutputSettings,
FoldoutOption.Indent,
CED.Action(Drawer_SectionMultiDisplay),
CED.Action(Drawer_SectionMultiDisplay),
CED.Action(Drawer_FieldDepth),
CED.Action(Drawer_FieldRenderTarget));
CED.Action(Drawer_FieldDepth),
CED.Action(Drawer_FieldRenderTarget));
(s, d, o, i) => s.isSectionAvailableXRSettings,
FadeOption.None,
CED.FoldoutGroup(
"XR Settings",
(s, p, o) => s.isSectionExpandedXRSettings,
FoldoutOption.Indent,
CED.Action(Drawer_FieldVR),
CED.Action(Drawer_FieldTargetEye)));
(s, d, o, i) => s.isSectionAvailableXRSettings,
FadeOption.None,
CED.FoldoutGroup(
"XR Settings",
(s, p, o) => s.isSectionExpandedXRSettings,
FoldoutOption.Indent,
CED.Action(Drawer_FieldVR),
CED.Action(Drawer_FieldTargetEye)));
(s, d, o, i) => s.isSectionAvailableRenderLoopSettings,
FadeOption.None,
CED.Select(
(s, d, o) => s.frameSettingsUI,
(s, d, o) => d.frameSettings,
FrameSettingsUI.SectionRenderingPasses,
FrameSettingsUI.SectionRenderingSettings,
FrameSettingsUI.SectionLightingSettings),
CED.Select(
(s, d, o) => s.frameSettingsUI.lightLoopSettings,
(s, d, o) => d.frameSettings.lightLoopSettings,
LightLoopSettingsUI.SectionLightLoopSettings));
(s, d, o, i) => s.isSectionAvailableRenderLoopSettings,
FadeOption.None,
CED.Select(
(s, d, o) => s.frameSettingsUI,
(s, d, o) => d.frameSettings,
FrameSettingsUI.SectionRenderingPasses,
FrameSettingsUI.SectionRenderingSettings,
FrameSettingsUI.SectionLightingSettings),
CED.Select(
(s, d, o) => s.frameSettingsUI.lightLoopSettings,
(s, d, o) => d.frameSettings.lightLoopSettings,
LightLoopSettingsUI.SectionLightLoopSettings));
enum ProjectionType { Perspective, Orthographic };

UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
}
}
#endif
static readonly int[] k_TargetEyeValues = { (int)StereoTargetEyeMask.Both, (int)StereoTargetEyeMask.Left, (int)StereoTargetEyeMask.Right, (int)StereoTargetEyeMask.None };

5
com.unity.render-pipelines.high-definition/HDRP/Editor/Camera/HDCameraEditor.cs


Camera m_PreviewCamera;
HDAdditionalCameraData m_PreviewAdditionalCameraData;
PostProcessLayer m_PreviewPostProcessLayer;
HDCamera m_PreviewHDCamera;
void OnEnable()
{

m_PreviewCamera.enabled = false;
m_PreviewCamera.cameraType = CameraType.Preview; // Must be init before adding HDAdditionalCameraData
m_PreviewAdditionalCameraData = m_PreviewCamera.gameObject.AddComponent<HDAdditionalCameraData>();
// Say that we are a camera editor preview and not just a regular preview
m_PreviewAdditionalCameraData.isEditorCameraPreview = true;
m_PreviewHDCamera = new HDCamera(m_PreviewCamera);
m_PreviewHDCamera.Update(m_PreviewPostProcessLayer, m_PreviewAdditionalCameraData.GetFrameSettings());
}
void OnDisable()

10
com.unity.render-pipelines.high-definition/HDRP/Editor/Camera/HDCameraEditor.Handlers.cs


using System;
using System;
using System.Reflection;
using UnityEngine;
using UnityEngine.Experimental.Rendering;

EditorUtility.CopySerialized(cameraData, m_PreviewAdditionalCameraData);
var layer = c.GetComponent<PostProcessLayer>() ?? ComponentSingleton<PostProcessLayer>.instance;
EditorUtility.CopySerialized(layer, m_PreviewPostProcessLayer);
m_PreviewCamera.cameraType = CameraType.SceneView; // This is required else if we use Preview the image is flipped... (Unity...)
// We need to call UpdateDirtyFrameSettings to update the dirty flags that was set in the CopySerialized call
m_PreviewAdditionalCameraData.UpdateDirtyFrameSettings(true, cameraData.GetFrameSettings());
// And then to copy the runtime frame settings
// So this includes the runtime frame settings properly
cameraData.GetFrameSettings().CopyTo(m_PreviewAdditionalCameraData.GetFrameSettings());
m_PreviewHDCamera.Update(m_PreviewPostProcessLayer, m_PreviewAdditionalCameraData.GetFrameSettings());
var previewTexture = GetPreviewTextureWithSize((int)previewSize.x, (int)previewSize.y);
m_PreviewCamera.targetTexture = previewTexture;

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/SerializedReflectionProxyVolumeComponent.cs


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

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/SerializedProxyVolume.cs


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

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


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

public SerializedProperty sphereInfluenceFade;
public SerializedProperty sphereInfluenceNormalFade;
internal SerializedProperty editorAdvancedModeBlendDistancePositive;
internal SerializedProperty editorAdvancedModeBlendDistanceNegative;
internal SerializedProperty editorSimplifiedModeBlendDistance;
internal SerializedProperty editorAdvancedModeBlendNormalDistancePositive;
internal SerializedProperty editorAdvancedModeBlendNormalDistanceNegative;
internal SerializedProperty editorSimplifiedModeBlendNormalDistance;
internal SerializedProperty editorAdvancedModeEnabled;
public SerializedInfluenceVolume(SerializedProperty root)
{
this.root = root;

sphereBaseOffset = root.Find((InfluenceVolume i) => i.sphereBaseOffset);
sphereInfluenceFade = root.Find((InfluenceVolume i) => i.sphereInfluenceFade);
sphereInfluenceNormalFade = root.Find((InfluenceVolume i) => i.sphereInfluenceNormalFade);
editorAdvancedModeBlendDistancePositive = root.FindPropertyRelative("editorAdvancedModeBlendDistancePositive");
editorAdvancedModeBlendDistanceNegative = root.FindPropertyRelative("editorAdvancedModeBlendDistanceNegative");
editorSimplifiedModeBlendDistance = root.FindPropertyRelative("editorSimplifiedModeBlendDistance");
editorAdvancedModeBlendNormalDistancePositive = root.FindPropertyRelative("editorAdvancedModeBlendNormalDistancePositive");
editorAdvancedModeBlendNormalDistanceNegative = root.FindPropertyRelative("editorAdvancedModeBlendNormalDistanceNegative");
editorSimplifiedModeBlendNormalDistance = root.FindPropertyRelative("editorSimplifiedModeBlendNormalDistance");
editorAdvancedModeEnabled = root.FindPropertyRelative("editorAdvancedModeEnabled");
//handle data migration from before editor value were saved
if(editorAdvancedModeBlendDistancePositive.vector3Value == Vector3.zero
&& editorAdvancedModeBlendDistanceNegative.vector3Value == Vector3.zero
&& editorSimplifiedModeBlendDistance.floatValue == 0f
&& editorAdvancedModeBlendNormalDistancePositive.vector3Value == Vector3.zero
&& editorAdvancedModeBlendNormalDistanceNegative.vector3Value == Vector3.zero
&& editorSimplifiedModeBlendNormalDistance.floatValue == 0f
&& (boxInfluencePositiveFade.vector3Value != Vector3.zero
|| boxInfluenceNegativeFade.vector3Value != Vector3.zero))
{
Vector3 positive = boxInfluencePositiveFade.vector3Value;
Vector3 negative = boxInfluenceNegativeFade.vector3Value;
//exact advanced
editorAdvancedModeBlendDistancePositive.vector3Value = positive;
editorAdvancedModeBlendDistanceNegative.vector3Value = negative;
//aproximated simplified
editorSimplifiedModeBlendDistance.floatValue = Mathf.Max(positive.x, positive.y, positive.z, negative.x, negative.y, negative.z);
//no normal modification allowed anymore in PlanarReflectionProbe
boxInfluenceNormalPositiveFade.vector3Value = Vector3.zero;
boxInfluenceNormalNegativeFade.vector3Value = Vector3.zero;
//display old data
editorAdvancedModeEnabled.boolValue = true;
Apply();
}
}
public void Apply()
{
root.serializedObject.ApplyModifiedProperties();
}
}
}

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


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

static ReflectionProxyVolumeComponentUI()
{
Inspector = CED.Select(
(s, d, o) => s.proxyVolume,
(s, d, o) => d.proxyVolume,
ProxyVolumeUI.SectionShape
);
(s, d, o) => s.proxyVolume,
(s, d, o) => d.proxyVolume,
ProxyVolumeUI.SectionShape
);
}
public ProxyVolumeUI proxyVolume = new ProxyVolumeUI();

{
}
public override void Reset(SerializedReflectionProxyVolumeComponent data, UnityAction repaint)

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


using System;
using System;
using UnityEditor.AnimatedValues;
using UnityEditor.IMGUI.Controls;
using UnityEngine;

static ProxyVolumeUI()
{
SectionShape = CED.Group(
CED.Action(Drawer_FieldShapeType),
CED.FadeGroup(
(s, d, o, i) => s.IsSectionExpanded_Shape((ShapeType)i),
FadeOption.Indent,
SectionShapeBox,
SectionShapeSphere
)
);
CED.Action(Drawer_FieldShapeType),
CED.FadeGroup(
(s, d, o, i) => s.IsSectionExpanded_Shape((ShapeType)i),
FadeOption.Indent,
SectionShapeBox,
SectionShapeSphere
)
);
}
public BoxBoundsHandle boxProjectionHandle = new BoxBoundsHandle();

: base(k_ShapeCount)
{
}
public override void Update()

public static void DrawHandles_EditNone(Transform transform, ProxyVolume proxyVolume, ProxyVolumeUI ui, Object sourceAsset)
{
}
static void Handles_EditBase_Sphere(Transform transform, ProxyVolume proxyVolume, ProxyVolumeUI s, Object sourceAsset)

2
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/Volume/ProxyVolumeEditor.cs


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

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


using System;
using System;
using UnityEngine.Experimental.Rendering;
internal static Color k_GizmoThemeColorBase = new Color(255f / 255f, 229f / 255f, 148f / 255f, 80f / 255f);
internal static Color k_GizmoThemeColorBaseFace = new Color(255f / 255f, 229f / 255f, 148f / 255f, 45f / 255f);
internal static Color k_GizmoThemeColorInfluence = new Color(83f / 255f, 255f / 255f, 95f / 255f, 75f / 255f);
internal static Color k_GizmoThemeColorInfluenceFace = new Color(83f / 255f, 255f / 255f, 95f / 255f, 17f / 255f);
internal static Color k_GizmoThemeColorInfluenceNormal = new Color(0f / 255f, 229f / 255f, 255f / 255f, 80f / 255f);
internal static Color k_GizmoThemeColorInfluenceNormalFace = new Color(0f / 255f, 229f / 255f, 255f / 255f, 36f / 255f);
internal static Color k_GizmoThemeColorProjection = new Color(0x00 / 255f, 0xE5 / 255f, 0xFF / 255f, 0x20 / 255f);
internal static Color k_GizmoThemeColorProjectionFace = new Color(0x00 / 255f, 0xE5 / 255f, 0xFF / 255f, 0x20 / 255f);
internal static Color k_GizmoThemeColorDisabled = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
internal static Color k_GizmoThemeColorDisabledFace = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
const int k_AnimBoolFields = 2;
internal static readonly Color k_GizmoThemeColorBase = new Color(255f / 255f, 229f / 255f, 148f / 255f, 80f / 255f);
internal static readonly Color k_GizmoThemeColorBaseFace = new Color(255f / 255f, 229f / 255f, 148f / 255f, 45f / 255f);
internal static readonly Color k_GizmoThemeColorInfluence = new Color(83f / 255f, 255f / 255f, 95f / 255f, 75f / 255f);
internal static readonly Color k_GizmoThemeColorInfluenceFace = new Color(83f / 255f, 255f / 255f, 95f / 255f, 17f / 255f);
internal static readonly Color k_GizmoThemeColorInfluenceNormal = new Color(0f / 255f, 229f / 255f, 255f / 255f, 80f / 255f);
internal static readonly Color k_GizmoThemeColorInfluenceNormalFace = new Color(0f / 255f, 229f / 255f, 255f / 255f, 36f / 255f);
internal static readonly Color k_GizmoThemeColorProjection = new Color(0x00 / 255f, 0xE5 / 255f, 0xFF / 255f, 0x20 / 255f);
internal static readonly Color k_GizmoThemeColorProjectionFace = new Color(0x00 / 255f, 0xE5 / 255f, 0xFF / 255f, 0x20 / 255f);
internal static readonly Color k_GizmoThemeColorDisabled = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
internal static readonly Color k_GizmoThemeColorDisabledFace = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
public BoxBoundsHandle boxBaseHandle = new BoxBoundsHandle();
public BoxBoundsHandle boxInfluenceHandle = new BoxBoundsHandle();
public BoxBoundsHandle boxInfluenceNormalHandle = new BoxBoundsHandle();
public Gizmo6FacesBox boxBaseHandle;
public Gizmo6FacesBoxContained boxInfluenceHandle;
public Gizmo6FacesBoxContained boxInfluenceNormalHandle;
public SphereBoundsHandle sphereBaseHandle = new SphereBoundsHandle();
public SphereBoundsHandle sphereInfluenceHandle = new SphereBoundsHandle();

public bool showInfluenceHandles { get; set; }
public InfluenceVolumeUI()
: base(k_ShapeCount + 1)
: base(k_ShapeCount + k_AnimBoolFields)
isSectionExpandedShape.value = true;
boxBaseHandle = new Gizmo6FacesBox(monochromeFace:true, monochromeSelectedFace:true);
boxInfluenceHandle = new Gizmo6FacesBoxContained(boxBaseHandle, monochromeFace:true, monochromeSelectedFace:true);
boxInfluenceNormalHandle = new Gizmo6FacesBoxContained(boxBaseHandle, monochromeFace:true, monochromeSelectedFace:true);
Color[] handleColors = new Color[]
{
HDReflectionProbeEditor.k_handlesColor[0][0],
HDReflectionProbeEditor.k_handlesColor[0][1],
HDReflectionProbeEditor.k_handlesColor[0][2],
HDReflectionProbeEditor.k_handlesColor[1][0],
HDReflectionProbeEditor.k_handlesColor[1][1],
HDReflectionProbeEditor.k_handlesColor[1][2]
};
boxBaseHandle.handleColors = handleColors;
boxInfluenceHandle.handleColors = handleColors;
boxInfluenceNormalHandle.handleColors = handleColors;
boxBaseHandle.faceColors = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorExtent };
boxBaseHandle.faceColorsSelected = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorExtentFace };
boxInfluenceHandle.faceColors = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceBlend };
boxInfluenceHandle.faceColorsSelected = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceBlendFace };
boxInfluenceNormalHandle.faceColors = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceNormalBlend };
boxInfluenceNormalHandle.faceColorsSelected = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceNormalBlendFace };
}
public override void Update()

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


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

switch (d.shapeType)
{
case ShapeType.Box:
{
var center = d.boxBaseOffset;
var size = d.boxBaseSize;
DrawBoxHandle(
s, d, o, sourceAsset,
s1 => s1.boxBaseHandle,
ref center,
ref size);
d.boxBaseOffset = center;
d.boxBaseSize = size;
{
var center = d.boxBaseOffset;
var size = d.boxBaseSize;
DrawBoxHandle(
s, d, o, sourceAsset,
s1 => s1.boxBaseHandle,
ref center,
ref size);
d.boxBaseOffset = center;
d.boxBaseSize = size;
}
}
{
var center = d.sphereBaseOffset;
var radius = d.sphereBaseRadius;
DrawSphereHandle(
s, d, o, sourceAsset,
s1 => s1.sphereBaseHandle,
ref center,
ref radius);
d.sphereBaseOffset = center;
d.sphereBaseRadius = radius;
{
var center = d.sphereBaseOffset;
var radius = d.sphereBaseRadius;
DrawSphereHandle(
s, d, o, sourceAsset,
s1 => s1.sphereBaseHandle,
ref center,
ref radius);
d.sphereBaseOffset = center;
d.sphereBaseRadius = radius;
}
}
}
Handles.matrix = mat;
Handles.color = c;

switch (d.shapeType)
{
case ShapeType.Box:
{
var positive = d.boxInfluencePositiveFade;
var negative = d.boxInfluenceNegativeFade;
DrawBoxFadeHandle(
s, d, o, sourceAsset,
s1 => s1.boxInfluenceHandle,
d.boxBaseOffset, d.boxBaseSize,
ref positive,
ref negative);
d.boxInfluencePositiveFade = positive;
d.boxInfluenceNegativeFade = negative;
break;
}
{
var positive = d.boxInfluencePositiveFade;
var negative = d.boxInfluenceNegativeFade;
DrawBoxFadeHandle(
s, d, o, sourceAsset,
s1 => s1.boxInfluenceHandle,
d.boxBaseOffset, d.boxBaseSize,
ref positive,
ref negative);
s.data.boxInfluencePositiveFade.vector3Value = positive;
s.data.boxInfluenceNegativeFade.vector3Value = negative;
//save advanced/simplified saved data
if (s.data.editorAdvancedModeEnabled.boolValue)
{
s.data.editorAdvancedModeBlendDistancePositive.vector3Value = positive;
s.data.editorAdvancedModeBlendDistanceNegative.vector3Value = negative;
}
else
{
s.data.editorSimplifiedModeBlendDistance.floatValue = positive.x;
}
s.data.Apply();
break;
}
{
var fade = d.sphereInfluenceFade;
DrawSphereFadeHandle(
s, d, o, sourceAsset,
s1 => s1.sphereInfluenceHandle,
d.sphereBaseOffset, d.sphereBaseRadius,
ref fade);
d.sphereInfluenceFade = fade;
break;
}
{
var fade = d.sphereInfluenceFade;
DrawSphereFadeHandle(
s, d, o, sourceAsset,
s1 => s1.sphereInfluenceHandle,
d.sphereBaseOffset, d.sphereBaseRadius,
ref fade);
d.sphereInfluenceFade = fade;
break;
}
}
Handles.matrix = mat;
Handles.color = c;

switch (d.shapeType)
{
case ShapeType.Box:
{
var positive = d.boxInfluenceNormalPositiveFade;
var negative = d.boxInfluenceNormalNegativeFade;
DrawBoxFadeHandle(
s, d, o, sourceAsset,
s1 => s1.boxInfluenceNormalHandle,
d.boxBaseOffset, d.boxBaseSize,
ref positive,
ref negative);
d.boxInfluenceNormalPositiveFade = positive;
d.boxInfluenceNormalNegativeFade = negative;
break;
}
{
Vector3 positive = d.boxInfluenceNormalPositiveFade;
Vector3 negative = d.boxInfluenceNormalNegativeFade;
DrawBoxFadeHandle(
s, d, o, sourceAsset,
s1 => s1.boxInfluenceNormalHandle,
d.boxBaseOffset, d.boxBaseSize,
ref positive,
ref negative);
s.data.boxInfluenceNormalPositiveFade.vector3Value = positive;
s.data.boxInfluenceNormalNegativeFade.vector3Value = negative;
//save advanced/simplified saved data
if (s.data.editorAdvancedModeEnabled.boolValue)
{
s.data.editorAdvancedModeBlendNormalDistancePositive.vector3Value = positive;
s.data.editorAdvancedModeBlendNormalDistanceNegative.vector3Value = negative;
}
else
{
s.data.editorSimplifiedModeBlendNormalDistance.floatValue = positive.x;
}
s.data.Apply();
break;
}
{
var fade = d.sphereInfluenceNormalFade;
DrawSphereFadeHandle(
s, d, o, sourceAsset,
s1 => s1.sphereInfluenceNormalHandle,
d.sphereBaseOffset, d.sphereBaseRadius,
ref fade);
d.sphereInfluenceNormalFade = fade;
break;
}
{
var fade = d.sphereInfluenceNormalFade;
DrawSphereFadeHandle(
s, d, o, sourceAsset,
s1 => s1.sphereInfluenceNormalHandle,
d.sphereBaseOffset, d.sphereBaseRadius,
ref fade);
d.sphereInfluenceNormalFade = fade;
break;
}
}
Handles.matrix = mat;
Handles.color = c;

InfluenceVolumeUI s, InfluenceVolume d, Editor o, Object sourceAsset,
Func<InfluenceVolumeUI, BoxBoundsHandle> boundsGetter,
Func<InfluenceVolumeUI, Gizmo6FacesBox> boundsGetter,
ref Vector3 center, ref Vector3 size)
{
var b = boundsGetter(s);

static void DrawBoxFadeHandle(
InfluenceVolumeUI s, InfluenceVolume d, Editor o, Object sourceAsset,
Func<InfluenceVolumeUI, BoxBoundsHandle> boundsGetter,
Func<InfluenceVolumeUI, Gizmo6FacesBox> boundsGetter,
Vector3 baseOffset, Vector3 baseSize,
ref Vector3 positive, ref Vector3 negative)
{

b.size = baseSize - positive - negative;
b.allHandleControledByOne = !s.data.editorAdvancedModeEnabled.boolValue;
EditorGUI.BeginChangeCheck();
b.DrawHandle();

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


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

d.boxInfluenceOffset, d.boxInfluenceSizeOffset,
d.sphereInfluenceRadiusOffset,
(editedHandle & HandleType.Influence) != 0,
k_GizmoThemeColorInfluence);
k_GizmoThemeColorInfluence,
false);
if ((showedHandle & HandleType.InfluenceNormal) != 0)
DrawGizmos_FadeHandle(

(editedHandle & HandleType.InfluenceNormal) != 0,
k_GizmoThemeColorInfluenceNormal);
k_GizmoThemeColorInfluenceNormal,
true);
}
static void DrawGizmos_BaseHandle(

{
case ShapeType.Box:
{
if (isSolid)
Gizmos.DrawCube(d.boxBaseOffset, d.boxBaseSize);
else
Gizmos.DrawWireCube(d.boxBaseOffset, d.boxBaseSize);
s.boxBaseHandle.center = d.boxBaseOffset;
s.boxBaseHandle.size = d.boxBaseSize;
s.boxBaseHandle.DrawHull(isSolid);
break;
}
case ShapeType.Sphere:

InfluenceVolumeUI s, InfluenceVolume d, Matrix4x4 matrix,
Vector3 boxOffset, Vector3 boxSizeOffset,
float sphereOffset,
bool isSolid, Color color)
bool isSolid, Color color, bool isNormal)
{
var mat = Gizmos.matrix;
var c = Gizmos.color;

{
case ShapeType.Box:
{
if (isSolid)
Gizmos.DrawCube(d.boxBaseOffset + boxOffset, d.boxBaseSize + boxSizeOffset);
else
Gizmos.DrawWireCube(d.boxBaseOffset + boxOffset, d.boxBaseSize + boxSizeOffset);
Gizmo6FacesBox refBox = isNormal ? s.boxInfluenceNormalHandle : s.boxInfluenceHandle;
refBox.center = d.boxBaseOffset + boxOffset;
refBox.size = d.boxBaseSize + boxSizeOffset;
refBox.DrawHull(isSolid);
break;
}
case ShapeType.Sphere:

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


partial class InfluenceVolumeUI
{
public static readonly CED.IDrawer SectionShape;
public static readonly CED.IDrawer FieldShape = CED.Action(Drawer_FieldShapeType);
public static readonly CED.IDrawer SectionShapeBox = CED.Action(Drawer_SectionShapeBox);
public static readonly CED.IDrawer SectionShapeSphere = CED.Action(Drawer_SectionShapeSphere);

SectionShape = CED.Group(
CED.Action(Drawer_FieldShapeType),
CED.FadeGroup(
(s, d, o, i) => s.IsSectionExpanded_Shape((ShapeType)i),
FadeOption.Indent,
SectionShapeBox,
SectionShapeSphere
)
);
CED.FoldoutGroup(
"Influence Volume",
(s, d, o) => s.isSectionExpandedShape,
FoldoutOption.Indent,
CED.Action(Drawer_FieldShapeType),
CED.FadeGroup(
(s, d, o, i) => s.IsSectionExpanded_Shape((ShapeType)i),
FadeOption.None,
SectionShapeBox,
SectionShapeSphere
)
)
);
CED.FoldoutGroup(
"Influence Volume",
(s, d, o) => s.isSectionExpandedShape,
FoldoutOption.Indent,
CED.Action(Drawer_InfluenceAdvancedSwitch),
CED.space,
CED.Action(Drawer_FieldShapeType),
CED.FadeGroup(
(s, d, o, i) => s.IsSectionExpanded_Shape((ShapeType)i),
FadeOption.None,
SectionShapeBox,
SectionShapeSphere
)
)
);
}
static void Drawer_FieldShapeType(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o)

static void Drawer_InfluenceAdvancedSwitch(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor owner)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
bool advanced = d.editorAdvancedModeEnabled.boolValue;
advanced = !GUILayout.Toggle(!advanced, CoreEditorUtils.GetContent("Normal|Normal parameters mode (only change for box shape)."), EditorStyles.miniButtonLeft, GUILayout.Width(60f), GUILayout.ExpandWidth(false));
advanced = GUILayout.Toggle(advanced, CoreEditorUtils.GetContent("Advanced|Advanced parameters mode (only change for box shape)."), EditorStyles.miniButtonRight, GUILayout.Width(60f), GUILayout.ExpandWidth(false));
s.boxInfluenceHandle.allHandleControledByOne = s.boxInfluenceNormalHandle.allHandleControledByOne = !advanced;
if (d.editorAdvancedModeEnabled.boolValue ^ advanced)
{
d.editorAdvancedModeEnabled.boolValue = advanced;
if (advanced)
{
d.boxInfluencePositiveFade.vector3Value = d.editorAdvancedModeBlendDistancePositive.vector3Value;
d.boxInfluenceNegativeFade.vector3Value = d.editorAdvancedModeBlendDistanceNegative.vector3Value;
d.boxInfluenceNormalPositiveFade.vector3Value = d.editorAdvancedModeBlendNormalDistancePositive.vector3Value;
d.boxInfluenceNormalNegativeFade.vector3Value = d.editorAdvancedModeBlendNormalDistanceNegative.vector3Value;
}
else
{
d.boxInfluenceNegativeFade.vector3Value = d.boxInfluencePositiveFade.vector3Value = Vector3.one * d.editorSimplifiedModeBlendDistance.floatValue;
d.boxInfluenceNormalNegativeFade.vector3Value = d.boxInfluenceNormalPositiveFade.vector3Value = Vector3.one * d.editorSimplifiedModeBlendNormalDistance.floatValue;
}
d.Apply();
}
}
}
bool advanced = d.editorAdvancedModeEnabled.boolValue;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(d.boxBaseOffset, _.GetContent("Box Offset"));
PlanarReflectionProbeUI.Drawer_ToolBarButton(0, o, GUILayout.Width(28f), GUILayout.MinHeight(22f));
EditorGUILayout.EndHorizontal();
//offset have no meaning for planar reflexion probe
//EditorGUILayout.PropertyField(d.boxBaseOffset, _.GetContent("Box Offset"));
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
Drawer_AdvancedBlendDistance(
d,
false,
maxFadeDistance,
CoreEditorUtils.GetContent("Blend Distance|Area around the probe where it is blended with other probes. Only used in deferred probes.")
);
PlanarReflectionProbeUI.Drawer_ToolBarButton(1, o, GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight((advanced ? 3 : 1) * (EditorGUIUtility.singleLineHeight + 3)));
EditorGUILayout.EndHorizontal();
_.DrawVector6Slider(
_.GetContent("Influence Fade"),
d.boxInfluencePositiveFade, d.boxInfluenceNegativeFade,
minFadeDistance, maxFadeDistance);
if (advanced)
{
CoreEditorUtils.DrawVector6(
CoreEditorUtils.GetContent("Face fade|Fade faces of the cubemap."),
d.boxPositiveFaceFade, d.boxNegativeFaceFade, Vector3.zero, Vector3.one, HDReflectionProbeEditor.k_handlesColor);
}
}
EditorGUILayout.Space();
static void Drawer_AdvancedBlendDistance(SerializedInfluenceVolume d, bool isNormal, Vector3 maxBlendDistance, GUIContent content)
{
SerializedProperty blendDistancePositive = isNormal ? d.boxInfluenceNormalPositiveFade : d.boxInfluencePositiveFade;
SerializedProperty blendDistanceNegative = isNormal ? d.boxInfluenceNormalNegativeFade : d.boxInfluenceNegativeFade;
SerializedProperty editorAdvancedModeBlendDistancePositive = isNormal ? d.editorAdvancedModeBlendNormalDistancePositive : d.editorAdvancedModeBlendDistancePositive;
SerializedProperty editorAdvancedModeBlendDistanceNegative = isNormal ? d.editorAdvancedModeBlendNormalDistanceNegative : d.editorAdvancedModeBlendDistanceNegative;
SerializedProperty editorSimplifiedModeBlendDistance = isNormal ? d.editorSimplifiedModeBlendNormalDistance : d.editorSimplifiedModeBlendDistance;
Vector3 bdp = blendDistancePositive.vector3Value;
Vector3 bdn = blendDistanceNegative.vector3Value;
_.DrawVector6Slider(
_.GetContent("Influence Normal Fade"),
d.boxInfluenceNormalPositiveFade, d.boxInfluenceNormalNegativeFade,
minFadeDistance, maxFadeDistance);
EditorGUILayout.BeginVertical();
EditorGUILayout.Space();
if (d.editorAdvancedModeEnabled.boolValue)
{
EditorGUI.BeginChangeCheck();
blendDistancePositive.vector3Value = editorAdvancedModeBlendDistancePositive.vector3Value;
blendDistanceNegative.vector3Value = editorAdvancedModeBlendDistanceNegative.vector3Value;
CoreEditorUtils.DrawVector6(
content,
blendDistancePositive, blendDistanceNegative, Vector3.zero, maxBlendDistance, HDReflectionProbeEditor.k_handlesColor);
if(EditorGUI.EndChangeCheck())
{
editorAdvancedModeBlendDistancePositive.vector3Value = blendDistancePositive.vector3Value;
editorAdvancedModeBlendDistanceNegative.vector3Value = blendDistanceNegative.vector3Value;
}
}
else
{
float distance = editorSimplifiedModeBlendDistance.floatValue;
EditorGUI.BeginChangeCheck();
distance = EditorGUILayout.FloatField(content, distance);
if (EditorGUI.EndChangeCheck())
{
Vector3 decal = Vector3.one * distance;
bdp.x = Mathf.Clamp(decal.x, 0f, maxBlendDistance.x);
bdp.y = Mathf.Clamp(decal.y, 0f, maxBlendDistance.y);
bdp.z = Mathf.Clamp(decal.z, 0f, maxBlendDistance.z);
bdn.x = Mathf.Clamp(decal.x, 0f, maxBlendDistance.x);
bdn.y = Mathf.Clamp(decal.y, 0f, maxBlendDistance.y);
bdn.z = Mathf.Clamp(decal.z, 0f, maxBlendDistance.z);
blendDistancePositive.vector3Value = bdp;
blendDistanceNegative.vector3Value = bdn;
editorSimplifiedModeBlendDistance.floatValue = distance;
}
}
_.DrawVector6Slider(
_.GetContent("Influence Face Fade"),
d.boxPositiveFaceFade, d.boxNegativeFaceFade,
Vector3.zero, Vector3.one);
GUILayout.EndVertical();
}
static void Drawer_SectionShapeSphere(InfluenceVolumeUI s, SerializedInfluenceVolume d, Editor o)

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


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

}
reflectionProxyVolume = objs.Count > 0
? new SerializedReflectionProxyVolumeComponent(new SerializedObject(objs.ToArray()))
: null;
? new SerializedReflectionProxyVolumeComponent(new SerializedObject(objs.ToArray()))
: null;
mode.enumValueIndex = (int)ReflectionProbeMode.Realtime;
refreshMode.enumValueIndex = (int)ReflectionProbeRefreshMode.EveryFrame;
capturePositionMode.enumValueIndex = (int)PlanarReflectionProbe.CapturePositionMode.MirrorCamera;
var updateProxyVolume = reflectionProxyVolume != null
&& serializedObject.targetObjects.Length != reflectionProxyVolume.serializedObject.targetObjects.Length;

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


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

internal SerializedProperty weight;
internal SerializedProperty multiplier;
internal SerializedProperty editorAdvancedModeBlendDistancePositive;
internal SerializedProperty editorAdvancedModeBlendDistanceNegative;
internal SerializedProperty editorSimplifiedModeBlendDistance;
internal SerializedProperty editorAdvancedModeBlendNormalDistancePositive;
internal SerializedProperty editorAdvancedModeBlendNormalDistanceNegative;
internal SerializedProperty editorSimplifiedModeBlendNormalDistance;
internal SerializedProperty editorAdvancedModeEnabled;
internal SerializedProperty proxyVolumeComponent;
public SerializedHDReflectionProbe(SerializedObject so, SerializedObject addso)

blendNormalDistanceNegative = addso.Find((HDAdditionalReflectionData d) => d.blendNormalDistanceNegative);
boxSideFadePositive = addso.Find((HDAdditionalReflectionData d) => d.boxSideFadePositive);
boxSideFadeNegative = addso.Find((HDAdditionalReflectionData d) => d.boxSideFadeNegative);
editorAdvancedModeBlendDistancePositive = addso.FindProperty("editorAdvancedModeBlendDistancePositive");
editorAdvancedModeBlendDistanceNegative = addso.FindProperty("editorAdvancedModeBlendDistanceNegative");
editorSimplifiedModeBlendDistance = addso.FindProperty("editorSimplifiedModeBlendDistance");
editorAdvancedModeBlendNormalDistancePositive = addso.FindProperty("editorAdvancedModeBlendNormalDistancePositive");
editorAdvancedModeBlendNormalDistanceNegative = addso.FindProperty("editorAdvancedModeBlendNormalDistanceNegative");
editorSimplifiedModeBlendNormalDistance = addso.FindProperty("editorSimplifiedModeBlendNormalDistance");
editorAdvancedModeEnabled = addso.FindProperty("editorAdvancedModeEnabled");
//handle data migration from before editor value were saved
if(editorAdvancedModeBlendDistancePositive.vector3Value == Vector3.zero
&& editorAdvancedModeBlendDistanceNegative.vector3Value == Vector3.zero
&& editorSimplifiedModeBlendDistance.floatValue == 0f
&& editorAdvancedModeBlendNormalDistancePositive.vector3Value == Vector3.zero
&& editorAdvancedModeBlendNormalDistanceNegative.vector3Value == Vector3.zero
&& editorSimplifiedModeBlendNormalDistance.floatValue == 0f
&& (blendDistancePositive.vector3Value != Vector3.zero
|| blendDistanceNegative.vector3Value != Vector3.zero
|| blendNormalDistancePositive.vector3Value != Vector3.zero
|| blendNormalDistanceNegative.vector3Value != Vector3.zero))
{
Vector3 positive = blendDistancePositive.vector3Value;
Vector3 negative = blendDistanceNegative.vector3Value;
//exact advanced
editorAdvancedModeBlendDistancePositive.vector3Value = positive;
editorAdvancedModeBlendDistanceNegative.vector3Value = negative;
//aproximated simplified
editorSimplifiedModeBlendDistance.floatValue = Mathf.Max(positive.x, positive.y, positive.z, negative.x, negative.y, negative.z);
positive = blendNormalDistancePositive.vector3Value;
negative = blendNormalDistanceNegative.vector3Value;
//exact advanced
editorAdvancedModeBlendNormalDistancePositive.vector3Value = positive;
editorAdvancedModeBlendNormalDistanceNegative.vector3Value = negative;
//aproximated simplified
editorSimplifiedModeBlendNormalDistance.floatValue = Mathf.Max(positive.x, positive.y, positive.z, negative.x, negative.y, negative.z);
//display old data
editorAdvancedModeEnabled.boolValue = true;
Apply();
}
proxyVolumeComponent = addso.Find((HDAdditionalReflectionData d) => d.proxyVolumeComponent);
}

38
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/ScreenSpaceRefractionEditor.cs


using System.Collections;
using UnityEngine;
using UnityEditor;
using UnityEditor.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEngine.Experimental.Rendering.HDPipeline
namespace UnityEditor.Experimental.Rendering.HDPipeline
public class ScreenSpaceRefractionEditor : VolumeComponentEditor
public class ScreenSpaceRefractionEditor : ScreenSpaceLightingEditor
SerializedDataParameter m_RayMinLevel;
SerializedDataParameter m_RayMaxLevel;
SerializedDataParameter m_RayMaxIterations;
SerializedDataParameter m_RayDepthSuccessBias;
SerializedDataParameter m_ScreenWeightDistance;
public override void OnEnable()
{
var o = new PropertyFetcher<ScreenSpaceRefraction>(serializedObject);
m_RayMinLevel = Unpack(o.Find(x => x.rayMinLevel));
m_RayMaxLevel = Unpack(o.Find(x => x.rayMaxLevel));
m_RayMaxIterations = Unpack(o.Find(x => x.rayMaxIterations));
m_RayDepthSuccessBias = Unpack(o.Find(x => x.rayDepthSuccessBias));
m_ScreenWeightDistance = Unpack(o.Find(x => x.screenWeightDistance));
}
public override void OnInspectorGUI()
{
EditorGUILayout.LabelField(CoreEditorUtils.GetContent("HiZ Settings"));
PropertyField(m_RayMinLevel, CoreEditorUtils.GetContent("Ray Min Level"));
PropertyField(m_RayMaxLevel, CoreEditorUtils.GetContent("Ray Max Level"));
PropertyField(m_RayMaxIterations, CoreEditorUtils.GetContent("Ray Max Iterations"));
PropertyField(m_RayDepthSuccessBias, CoreEditorUtils.GetContent("Ray Depth Success Bias"));
EditorGUILayout.Separator();
EditorGUILayout.LabelField(CoreEditorUtils.GetContent("Common Settings"));
PropertyField(m_ScreenWeightDistance, CoreEditorUtils.GetContent("Screen Weight Distance"));
}
}
}

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


using System;
using System;
using UnityEditor.AnimatedValues;
using UnityEngine.Events;
using UnityEngine.Experimental.Rendering.HDPipeline;

{
partial class PlanarReflectionProbeUI : BaseUI<SerializedPlanarReflectionProbe>
{
const int k_AnimBoolFields = 4;
const int k_AnimBoolFields = 6;
static readonly int k_ReflectionProbeModeModeCount = Enum.GetValues(typeof(ReflectionProbeMode)).Length;
static readonly int k_AnimBoolTotal = k_AnimBoolFields + k_ReflectionProbeModeModeCount;

public AnimBool isSectionExpandedCaptureMirrorSettings { get { return m_AnimBools[k_ReflectionProbeModeModeCount + 2]; } }
public AnimBool isSectionExpandedCaptureStaticSettings { get { return m_AnimBools[k_ReflectionProbeModeModeCount + 3]; } }
public AnimBool isSectionExpendedProxyVolume { get { return m_AnimBools[k_ReflectionProbeModeModeCount + 4]; } }
public AnimBool isSectionExpendedAdditionalSettings { get { return m_AnimBools[k_ReflectionProbeModeModeCount + 5]; } }
public bool showCaptureHandles { get; set; }

isSectionExpandedInfluenceSettings.value = true;
isSectionExpandedCaptureSettings.value = true;
isSectionExpendedProxyVolume.value = true;
isSectionExpendedAdditionalSettings.value = false;
}
public AnimBool IsSectionExpandedReflectionProbeMode(ReflectionProbeMode mode)

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


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

InfluenceVolumeUI.DrawHandles_EditInfluenceNormal(s.influenceVolume, d.influenceVolume, o, mat, d);
break;
case EditMirrorPosition:
{
EditorGUI.BeginChangeCheck();
var m = Handles.matrix;
Handles.matrix = mat;
var p = Handles.PositionHandle(d.captureMirrorPlaneLocalPosition, d.transform.rotation);
if (EditorGUI.EndChangeCheck())
EditorGUI.BeginChangeCheck();
var m = Handles.matrix;
Handles.matrix = mat;
var p = Handles.PositionHandle(d.captureMirrorPlaneLocalPosition, d.transform.rotation);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(d, "Translate Mirror Plane");
d.captureMirrorPlaneLocalPosition = p;
EditorUtility.SetDirty(d);
}
Handles.matrix = m;
break;
Undo.RecordObject(d, "Translate Mirror Plane");
d.captureMirrorPlaneLocalPosition = p;
EditorUtility.SetDirty(d);
Handles.matrix = m;
break;
}
{
EditorGUI.BeginChangeCheck();
var m = Handles.matrix;
Handles.matrix = mat;
var q = Quaternion.LookRotation(d.captureMirrorPlaneLocalNormal, Vector3.up);
q = Handles.RotationHandle(q, d.captureMirrorPlaneLocalPosition);
if (EditorGUI.EndChangeCheck())
EditorGUI.BeginChangeCheck();
var m = Handles.matrix;
Handles.matrix = mat;
var q = Quaternion.LookRotation(d.captureMirrorPlaneLocalNormal, Vector3.up);
q = Handles.RotationHandle(q, d.captureMirrorPlaneLocalPosition);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(d, "Rotate Mirror Plane");
d.captureMirrorPlaneLocalNormal = q * Vector3.forward;
EditorUtility.SetDirty(d);
}
Handles.matrix = m;
break;
Undo.RecordObject(d, "Rotate Mirror Plane");
d.captureMirrorPlaneLocalNormal = q * Vector3.forward;
EditorUtility.SetDirty(d);
Handles.matrix = m;
break;
}
{
EditorGUI.BeginChangeCheck();
var m = Handles.matrix;
Handles.matrix = mat;
var p = Handles.PositionHandle(d.captureLocalPosition, d.transform.rotation);
if (EditorGUI.EndChangeCheck())
EditorGUI.BeginChangeCheck();
var m = Handles.matrix;
Handles.matrix = mat;
var p = Handles.PositionHandle(d.captureLocalPosition, d.transform.rotation);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(d, "Translate Capture Position");
d.captureLocalPosition = p;
EditorUtility.SetDirty(d);
}
Handles.matrix = m;
break;
Undo.RecordObject(d, "Translate Capture Position");
d.captureLocalPosition = p;
EditorUtility.SetDirty(d);
Handles.matrix = m;
break;
}
}
if (d.useMirrorPlane)

Handles.color = k_GizmoMirrorPlaneCamera;
Handles.ArrowHandleCap(
0,
d.captureMirrorPlaneLocalPosition,
0,
d.captureMirrorPlaneLocalPosition,
);
);
Handles.matrix = m;
}

{
case EditBaseShape:
InfluenceVolumeUI.DrawGizmos(
s.influenceVolume,
d.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.Base,
InfluenceVolumeUI.HandleType.All);
s.influenceVolume,
d.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.Base,
InfluenceVolumeUI.HandleType.All);
s.influenceVolume,
d.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.Influence,
InfluenceVolumeUI.HandleType.All);
s.influenceVolume,
d.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.Influence,
InfluenceVolumeUI.HandleType.All);
s.influenceVolume,
d.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.InfluenceNormal,
InfluenceVolumeUI.HandleType.All);
break;
default:
{
var showedHandles = s.influenceVolume.showInfluenceHandles
? InfluenceVolumeUI.HandleType.All
: InfluenceVolumeUI.HandleType.Base;
InfluenceVolumeUI.DrawGizmos(
InfluenceVolumeUI.HandleType.InfluenceNormal,
InfluenceVolumeUI.HandleType.All);
InfluenceVolumeUI.HandleType.None,
showedHandles);
default:
{
var showedHandles = s.influenceVolume.showInfluenceHandles
? InfluenceVolumeUI.HandleType.All
: InfluenceVolumeUI.HandleType.Base;
InfluenceVolumeUI.DrawGizmos(
s.influenceVolume,
d.influenceVolume,
mat,
InfluenceVolumeUI.HandleType.None,
showedHandles);
break;
}
}
}
if (d.proxyVolumeReference != null)

var c = Gizmos.color;
var m = Gizmos.matrix;
Gizmos.matrix = Matrix4x4.TRS(
d.captureMirrorPlanePosition,
Quaternion.LookRotation(d.captureMirrorPlaneNormal, Vector3.up),
Vector3.one);
d.captureMirrorPlanePosition,
Quaternion.LookRotation(d.captureMirrorPlaneNormal, Vector3.up),
Vector3.one);
Gizmos.color = k_GizmoMirrorPlaneCamera;
Gizmos.DrawCube(Vector3.zero, new Vector3(1, 1, 0));

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


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

public static readonly CED.IDrawer Inspector;
public static readonly CED.IDrawer SectionProbeModeSettings;
public static readonly CED.IDrawer ProxyVolumeSettings = CED.FoldoutGroup(
"Proxy Volume",
(s, d, o) => s.isSectionExpendedProxyVolume,
FoldoutOption.Indent,
CED.Action(Drawer_SectionProxySettings)
);
public static readonly CED.IDrawer SectionFoldoutInfluenceSettings = CED.FoldoutGroup(
"Influence Settings",
(s, d, o) => s.isSectionExpandedInfluenceSettings,
FoldoutOption.Indent,
CED.Action(Drawer_SectionInfluenceSettings)
);
public static readonly CED.IDrawer SectionFoldoutAdditionalSettings = CED.FoldoutGroup(
"Artistic Settings",
(s, d, o) => s.isSectionExpendedAdditionalSettings,
FoldoutOption.Indent,
CED.Action(Drawer_SectionInfluenceSettings)
);
public static readonly CED.IDrawer SectionFoldoutCaptureSettings;

static PlanarReflectionProbeUI()
{
SectionFoldoutCaptureSettings = CED.FoldoutGroup(
"Capture Settings",
(s, d, o) => s.isSectionExpandedCaptureSettings,
FoldoutOption.Indent,
CED.Action(Drawer_SectionCaptureSettings),
CED.FadeGroup(
(s, d, o, i) =>
{
switch (i)
"Capture Settings",
(s, d, o) => s.isSectionExpandedCaptureSettings,
FoldoutOption.Indent,
CED.Action(Drawer_SectionCaptureSettings),
CED.FadeGroup(
(s, d, o, i) =>
default:
case 0: return s.isSectionExpandedCaptureMirrorSettings;
case 1: return s.isSectionExpandedCaptureStaticSettings;
}
},
FadeOption.None,
SectionCaptureMirrorSettings,
SectionCaptureStaticSettings)
);
switch (i)
{
default:
case 0: return s.isSectionExpandedCaptureMirrorSettings;
case 1: return s.isSectionExpandedCaptureStaticSettings;
}
},
FadeOption.None,
SectionCaptureMirrorSettings,
SectionCaptureStaticSettings)
);
CED.Action(Drawer_FieldCaptureType),
CED.FadeGroup(
(s, d, o, i) => s.IsSectionExpandedReflectionProbeMode((ReflectionProbeMode)i),
FadeOption.Indent,
SectionProbeModeBakedSettings,
SectionProbeModeRealtimeSettings,
SectionProbeModeCustomSettings
)
);
CED.Action(Drawer_FieldCaptureType),
CED.FadeGroup(
(s, d, o, i) => s.IsSectionExpandedReflectionProbeMode((ReflectionProbeMode)i),
FadeOption.Indent,
SectionProbeModeBakedSettings,
SectionProbeModeRealtimeSettings,
SectionProbeModeCustomSettings
)
);
SectionProbeModeSettings,
CED.space,
CED.Action((s, d, o) => EditorGUILayout.LabelField(_.GetContent("Proxy Volume"), EditorStyles.boldLabel)),
CED.Action(Drawer_FieldProxyVolumeReference),
CED.space,
CED.Action(Drawer_Toolbar),
CED.space,
CED.Select(
(s, d, o) => s.influenceVolume,
(s, d, o) => d.influenceVolume,
InfluenceVolumeUI.SectionFoldoutShape
),
CED.Action(Drawer_DifferentShapeError),
SectionFoldoutInfluenceSettings,
SectionFoldoutCaptureSettings,
CED.Select(
(s, d, o) => s.frameSettings,
(s, d, o) => d.frameSettings,
FrameSettingsUI.Inspector
),
CED.space,
CED.Action(Drawer_SectionBakeButton)
);
CED.Action(Drawer_Toolbar),
CED.space,
ProxyVolumeSettings,
CED.Select(
(s, d, o) => s.influenceVolume,
(s, d, o) => d.influenceVolume,
InfluenceVolumeUI.SectionFoldoutShape
),
CED.Action(Drawer_DifferentShapeError),
SectionFoldoutCaptureSettings,
SectionFoldoutAdditionalSettings,
CED.Select(
(s, d, o) => s.frameSettings,
(s, d, o) => d.frameSettings,
FrameSettingsUI.Inspector
),
CED.space,
CED.Action(Drawer_SectionBakeButton)
);
}
const EditMode.SceneViewEditMode EditBaseShape = EditMode.SceneViewEditMode.ReflectionProbeBox;

"Proxy volume and influence volume have different shape types, this is not supported.",
MessageType.Error,
true
);
);
}
}

GUI.enabled = false;
EditorGUILayout.PropertyField(d.refreshMode, _.GetContent("Refresh Mode"));
EditorGUILayout.PropertyField(d.capturePositionMode, _.GetContent("Capture Position Mode"));
d.refreshMode.enumValueIndex = (int)ReflectionProbeRefreshMode.EveryFrame;
d.capturePositionMode.enumValueIndex = (int)PlanarReflectionProbe.CapturePositionMode.MirrorCamera;
static void Drawer_SectionProxySettings(PlanarReflectionProbeUI s, SerializedPlanarReflectionProbe d, Editor o)
{
EditorGUILayout.PropertyField(d.proxyVolumeReference, _.GetContent("Reference"));
if (d.proxyVolumeReference.objectReferenceValue != null)
{
var proxy = (ReflectionProxyVolumeComponent)d.proxyVolumeReference.objectReferenceValue;
if ((int)proxy.proxyVolume.shapeType != d.influenceVolume.shapeType.enumValueIndex)
EditorGUILayout.HelpBox(
"Proxy volume and influence volume have different shape types, this is not supported.",
MessageType.Error,
true
);
}
else
{
EditorGUILayout.HelpBox(
"When no Proxy setted, Influence shape will be used as Proxy shape too.",
MessageType.Info,
true
);
}
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(d.multiplier, _.GetContent("Multiplier"));

{
GUI.enabled = false;
EditorGUILayout.PropertyField(d.mode, _.GetContent("Type"));
d.mode.enumValueIndex = (int)ReflectionProbeMode.Realtime;
static void Drawer_FieldProxyVolumeReference(PlanarReflectionProbeUI s, SerializedPlanarReflectionProbe d, Editor o)
{
EditorGUILayout.PropertyField(d.proxyVolumeReference, _.GetContent("Reference"));
}
static readonly EditMode.SceneViewEditMode[] k_Toolbar_SceneViewEditModes =
{
EditBaseShape,

static readonly EditMode.SceneViewEditMode[] k_Toolbar_Static_SceneViewEditModes =
{
EditCenter
//EditCenter //offset have no meanings with planar
EditMirrorPosition,
//EditMirrorPosition, //offset have no meanings with planar
EditMirrorRotation
};
static GUIContent[] s_Toolbar_Contents = null;

{
get
{
return s_Toolbar_Static_Contents ?? (s_Toolbar_Static_Contents = new[]
return s_Toolbar_Static_Contents ?? (s_Toolbar_Static_Contents = new GUIContent[]
EditorGUIUtility.IconContent("MoveTool", "|Move the capture position.")
//EditorGUIUtility.IconContent("MoveTool", "|Move the capture position.") //offset have no meanings with planar
});
}
}

{
return s_Toolbar_Mirror_Contents ?? (s_Toolbar_Mirror_Contents = new[]
{
EditorGUIUtility.IconContent("MoveTool", "|Move the mirror plane."),
//EditorGUIUtility.IconContent("MoveTool", "|Move the mirror plane."), //offset have no meanings with planar
EditorGUIUtility.IconContent("RotateTool", "|Rotate the mirror plane.")
});
}

GUILayout.EndHorizontal();
}
static public void Drawer_ToolBarButton(int buttonIndex, Editor owner, params GUILayoutOption[] styles)
{
if (GUILayout.Button(toolbar_Contents[buttonIndex], styles))
{
EditMode.ChangeEditMode(k_Toolbar_SceneViewEditModes[buttonIndex], GetBoundsGetter(owner)(), owner);
}
}
{
var bounds = new Bounds();
foreach (Component targetObject in o.targets)
var rp = targetObject.transform;
var b = rp.position;
bounds.Encapsulate(b);
}
return bounds;
};
var bounds = new Bounds();
foreach (Component targetObject in o.targets)
{
var rp = targetObject.transform;
var b = rp.position;
bounds.Encapsulate(b);
}
return bounds;
};
}
}
}

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


using System;
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor.Callbacks;

public override GUIContent GetPreviewTitle()
{
return _.GetContent("Planar Reflection");
return _.GetContent("Planar Reflection");
}
public override void OnPreviewGUI(Rect r, GUIStyle background)

var row = i / rowSize;
var col = i % rowSize;
var itemRect = new Rect(
r.x + size.x * row + ((row > 0) ? (row - 1) * space.x : 0),
r.y + size.y * col + ((col > 0) ? (col - 1) * space.y : 0),
size.x,
size.y);
r.x + size.x * row + ((row > 0) ? (row - 1) * space.x : 0),
r.y + size.y * col + ((col > 0) ? (col - 1) * space.y : 0),
size.x,
size.y);
if (m_PreviewedTextures[i] != null)
EditorGUI.DrawPreviewTexture(itemRect, m_PreviewedTextures[i], CameraEditorUtils.GUITextureBlit2SRGBMaterial, ScaleMode.ScaleToFit, 0, 1);

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


using System;
using System;
using UnityEditor.AnimatedValues;
using UnityEditor.IMGUI.Controls;
using UnityEditorInternal;

public void ClearOperation(Operation op) { operations &= ~op; }
public void AddOperation(Operation op) { operations |= op; }
public BoxBoundsHandle boxInfluenceHandle = new BoxBoundsHandle();
public BoxBoundsHandle boxProjectionHandle = new BoxBoundsHandle();
public BoxBoundsHandle boxBlendHandle = new BoxBoundsHandle();
public BoxBoundsHandle boxBlendNormalHandle = new BoxBoundsHandle();
public Gizmo6FacesBox alternativeBoxInfluenceHandle;
public Gizmo6FacesBoxContained alternativeBoxBlendHandle;
public Gizmo6FacesBoxContained alternativeBoxBlendNormalHandle;
public SphereBoundsHandle sphereInfluenceHandle = new SphereBoundsHandle();
public SphereBoundsHandle sphereProjectionHandle = new SphereBoundsHandle();
public SphereBoundsHandle sphereBlendHandle = new SphereBoundsHandle();

public AnimBool isSectionExpandedInfluenceVolume { get { return m_AnimBools[0]; } }
public AnimBool isSectionExpandedSeparateProjection { get { return m_AnimBools[1]; } }
public AnimBool isSectionExpandedProxyVolume { get { return m_AnimBools[0]; } }
public AnimBool isSectionExpandedInfluenceVolume { get { return m_AnimBools[1]; } }
public AnimBool isSectionExpandedCaptureSettings { get { return m_AnimBools[2]; } }
public AnimBool isSectionExpandedAdditional { get { return m_AnimBools[3]; } }

public HDReflectionProbeUI()
: base(k_AnimBoolsCount)
{
isSectionExpandedProxyVolume.value = true;
alternativeBoxInfluenceHandle = new Gizmo6FacesBox(monochromeFace:true, monochromeSelectedFace:true);
alternativeBoxBlendHandle = new Gizmo6FacesBoxContained(alternativeBoxInfluenceHandle, monochromeFace:true, monochromeSelectedFace:true);
alternativeBoxBlendNormalHandle = new Gizmo6FacesBoxContained(alternativeBoxInfluenceHandle, monochromeFace:true, monochromeSelectedFace:true);
Color[] handleColors = new Color[]
{
HDReflectionProbeEditor.k_handlesColor[0][0],
HDReflectionProbeEditor.k_handlesColor[0][1],
HDReflectionProbeEditor.k_handlesColor[0][2],
HDReflectionProbeEditor.k_handlesColor[1][0],
HDReflectionProbeEditor.k_handlesColor[1][1],
HDReflectionProbeEditor.k_handlesColor[1][2]
};
alternativeBoxInfluenceHandle.handleColors = handleColors;
alternativeBoxBlendHandle.handleColors = handleColors;
alternativeBoxBlendNormalHandle.handleColors = handleColors;
alternativeBoxInfluenceHandle.faceColors = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorExtent };
alternativeBoxInfluenceHandle.faceColorsSelected = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorExtentFace };
alternativeBoxBlendHandle.faceColors = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceBlend };
alternativeBoxBlendHandle.faceColorsSelected = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceBlendFace };
alternativeBoxBlendNormalHandle.faceColors = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceNormalBlend };
alternativeBoxBlendNormalHandle.faceColorsSelected = new Color[] { HDReflectionProbeEditor.k_GizmoThemeColorInfluenceNormalBlendFace };
}
public override void Update()

SetModeTarget(data.mode.hasMultipleDifferentValues ? -1 : data.mode.intValue);
SetShapeTarget(data.influenceShape.hasMultipleDifferentValues ? -1 : data.influenceShape.intValue);
isSectionExpandedSeparateProjection.value = data.useSeparateProjectionVolume.boolValue;
base.Update();
}

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


using System;
using System;
using System.Reflection;
using UnityEditor.Experimental.Rendering.HDPipeline;
using UnityEditorInternal;

Inspector = new[]
{
SectionPrimarySettings,
SectionProxyVolumeSettings,
SectionSeparateProjectionVolumeSettings,
//SectionSeparateProjectionVolumeSettings,
SectionInfluenceProxyMismatch,
SectionCaptureSettings,
SectionAdditionalSettings,
ButtonBake

public static readonly CED.IDrawer[] Inspector;
public static readonly CED.IDrawer SectionPrimarySettings = CED.Group(
CED.Action(Drawer_ReflectionProbeMode),
CED.FadeGroup((s, p, o, i) => s.IsSectionExpandedMode((ReflectionProbeMode)i),
FadeOption.Indent,
CED.noop, // Baked
CED.Action(Drawer_ModeSettingsRealtime), // Realtime
CED.Action(Drawer_ModeSettingsCustom) // Custom
),
CED.space,
CED.Action(Drawer_InfluenceShape),
//CED.Action(Drawer_IntensityMultiplier),
CED.space,
CED.Action(Drawer_Toolbar),
CED.space,
CED.Action((s, d, o) => EditorGUILayout.PropertyField(d.proxyVolumeComponent, _.GetContent("Proxy Volume")))
);
CED.Action(Drawer_Toolbar),
CED.space,
CED.Action(Drawer_ReflectionProbeMode),
CED.space,
CED.FadeGroup((s, p, o, i) => s.IsSectionExpandedMode((ReflectionProbeMode)i),
FadeOption.Indent,
CED.noop, // Baked
CED.Action(Drawer_ModeSettingsRealtime), // Realtime
CED.Action(Drawer_ModeSettingsCustom) // Custom
)
);
public static readonly CED.IDrawer SectionProxyVolumeSettings = CED.FoldoutGroup(
"Proxy Volume",
(s, p, o) => s.isSectionExpandedProxyVolume,
FoldoutOption.Indent,
CED.Action(Drawer_ProxyVolume)
);
"Influence volume settings",
(s, p, o) => s.isSectionExpandedInfluenceVolume,
FoldoutOption.Indent,
CED.FadeGroup(
(s, p, o, i) => s.IsSectionExpandedShape((ShapeType)i),
FadeOption.None,
CED.Action(Drawer_InfluenceBoxSettings), // Box
CED.Action(Drawer_InfluenceSphereSettings) // Sphere
)/*,
CED.Action(Drawer_UseSeparateProjectionVolume)*/
);
"Influence Volume",
(s, p, o) => s.isSectionExpandedInfluenceVolume,
FoldoutOption.Indent,
CED.Action(Drawer_InfluenceAdvancedSwitch),
CED.space,
CED.Action(Drawer_InfluenceShape),
CED.space,
CED.Action(Drawer_InfluenceAreas),
CED.space,
CED.Action(Drawer_InfluenceSettings)
);
public static readonly CED.IDrawer SectionSeparateProjectionVolumeSettings = CED.FadeGroup(
(s, p, o, i) => s.isSectionExpandedSeparateProjection,
FadeOption.None,
CED.FoldoutGroup(
"Reprojection volume settings",
(s, p, o) => s.isSectionExpandedSeparateProjection,
FoldoutOption.Indent,
CED.FadeGroup(
(s, p, o, i) => s.IsSectionExpandedShape((ShapeType)i),
FadeOption.None,
CED.Action(Drawer_ProjectionBoxSettings), // Box
CED.Action(Drawer_ProjectionSphereSettings) // Sphere
)
)
);
public static readonly CED.IDrawer SectionInfluenceProxyMismatch = CED.Action(Drawer_InfluenceProxyMissmatch);
"Capture settings",
(s, p, o) => s.isSectionExpandedCaptureSettings,
FoldoutOption.Indent,
CED.Action(Drawer_CaptureSettings)
);
"Capture Settings",
(s, p, o) => s.isSectionExpandedCaptureSettings,
FoldoutOption.Indent,
CED.Action(Drawer_CaptureSettings)
);
"Additional settings",
(s, p, o) => s.isSectionExpandedAdditional,
FoldoutOption.Indent,
CED.Action(Drawer_AdditionalSettings)
);
"Artistic Settings",
(s, p, o) => s.isSectionExpandedAdditional,
FoldoutOption.Indent,
CED.Action(Drawer_AdditionalSettings)
);
public static readonly CED.IDrawer ButtonBake = CED.Action(Drawer_BakeActions);

p.resolution.intValue = renderPipelineAsset.GetRenderPipelineSettings().lightLoopSettings.reflectionCubemapSize;
p.resolution.intValue = (int)renderPipelineAsset.GetRenderPipelineSettings().lightLoopSettings.reflectionCubemapSize;
EditorGUILayout.LabelField(CoreEditorUtils.GetContent("Resolution"), CoreEditorUtils.GetContent(p.resolution.intValue.ToString()));
EditorGUILayout.PropertyField(p.shadowDistance, CoreEditorUtils.GetContent("Shadow Distance"));

static void Drawer_AdditionalSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.PropertyField(p.weight);
EditorGUILayout.PropertyField(p.weight, CoreEditorUtils.GetContent("Influence Volume Weight|Blending weight to use while interpolating between influence volume. (Reminder: Sky is an Influence Volume too)."));
EditorGUILayout.PropertyField(p.multiplier);
EditorGUILayout.PropertyField(p.multiplier, CoreEditorUtils.GetContent("Multiplier|Tweeking option to enhance reflection."));
if (EditorGUI.EndChangeCheck())
p.multiplier.floatValue = Mathf.Max(0.0f, p.multiplier.floatValue);

EditorReflectionSystemGUI.DrawBakeButton((ReflectionProbeMode)p.mode.intValue, p.target);
}
static void Drawer_ProxyVolume(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.PropertyField(p.proxyVolumeComponent, _.GetContent("Proxy Volume"));
if (p.proxyVolumeComponent.objectReferenceValue == null)
{
EditorGUILayout.HelpBox(
"When no Proxy setted, Influence shape will be used as Proxy shape too.",
MessageType.Info,
true
);
}
}
static void Drawer_InfluenceProxyMissmatch(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
if (p.proxyVolumeComponent.objectReferenceValue != null)
{
var proxy = (ReflectionProxyVolumeComponent)p.proxyVolumeComponent.objectReferenceValue;
if ((int)proxy.proxyVolume.shapeType != p.influenceShape.enumValueIndex)
EditorGUILayout.HelpBox(
"Proxy volume and influence volume have different shape types, this is not supported.",
MessageType.Error,
true
);
}
}
bool advanced = p.editorAdvancedModeEnabled.boolValue;
CoreEditorUtils.DrawVector6Slider(
CoreEditorUtils.GetContent("Blend Distance|Area around the probe where it is blended with other probes. Only used in deferred probes."),
p.blendDistancePositive, p.blendDistanceNegative, Vector3.zero, maxBlendDistance);
EditorGUILayout.BeginHorizontal();
Drawer_AdvancedBlendDistance(
p,
false,
maxBlendDistance,
CoreEditorUtils.GetContent("Blend Distance|Area around the probe where it is blended with other probes. Only used in deferred probes.")
);
if (GUILayout.Button(toolbar_Contents[1], GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight((advanced ? 3 : 1) * (EditorGUIUtility.singleLineHeight + 3))))
{
EditMode.ChangeEditMode(k_Toolbar_SceneViewEditModes[1], GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
CoreEditorUtils.DrawVector6Slider(
CoreEditorUtils.GetContent("Blend Normal Distance|Area around the probe where the normals influence the probe. Only used in deferred probes."),
p.blendNormalDistancePositive, p.blendNormalDistanceNegative, Vector3.zero, maxBlendDistance);
EditorGUILayout.BeginHorizontal();
Drawer_AdvancedBlendDistance(
p,
true,
maxBlendDistance,
CoreEditorUtils.GetContent("Blend Normal Distance|Area around the probe where the normals influence the probe. Only used in deferred probes.")
);
if (GUILayout.Button(toolbar_Contents[2], GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.MinHeight(22f), GUILayout.MaxHeight((advanced ? 3 : 1) * (EditorGUIUtility.singleLineHeight + 3))))
{
EditMode.ChangeEditMode(k_Toolbar_SceneViewEditModes[2], GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
CoreEditorUtils.DrawVector6Slider(
CoreEditorUtils.GetContent("Face fade|Fade faces of the cubemap."),
p.boxSideFadePositive, p.boxSideFadeNegative, Vector3.zero, Vector3.one);
if (advanced)
{
CoreEditorUtils.DrawVector6(
CoreEditorUtils.GetContent("Face fade|Fade faces of the cubemap."),
p.boxSideFadePositive, p.boxSideFadeNegative, Vector3.zero, Vector3.one, HDReflectionProbeEditor.k_handlesColor);
}
}
EditorGUILayout.Space();
static void Drawer_AdvancedBlendDistance(SerializedHDReflectionProbe p, bool isNormal, Vector3 maxBlendDistance, GUIContent content)
{
SerializedProperty blendDistancePositive = isNormal ? p.blendNormalDistancePositive : p.blendDistancePositive;
SerializedProperty blendDistanceNegative = isNormal ? p.blendNormalDistanceNegative : p.blendDistanceNegative;
SerializedProperty editorAdvancedModeBlendDistancePositive = isNormal ? p.editorAdvancedModeBlendNormalDistancePositive : p.editorAdvancedModeBlendDistancePositive;
SerializedProperty editorAdvancedModeBlendDistanceNegative = isNormal ? p.editorAdvancedModeBlendNormalDistanceNegative : p.editorAdvancedModeBlendDistanceNegative;
SerializedProperty editorSimplifiedModeBlendDistance = isNormal ? p.editorSimplifiedModeBlendNormalDistance : p.editorSimplifiedModeBlendDistance;
Vector3 bdp = blendDistancePositive.vector3Value;
Vector3 bdn = blendDistanceNegative.vector3Value;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(p.boxSize, CoreEditorUtils.GetContent("Box Size|The size of the box in which the reflections will be applied to objects. The value is not affected by the Transform of the Game Object."));
EditorGUILayout.PropertyField(p.boxOffset, CoreEditorUtils.GetContent("Box Offset|The center of the box in which the reflections will be applied to objects. The value is relative to the position of the Game Object."));
EditorGUILayout.PropertyField(p.boxProjection, CoreEditorUtils.GetContent("Box Projection|Box projection causes reflections to appear to change based on the object's position within the probe's box, while still using a single probe as the source of the reflection. This works well for reflections on objects that are moving through enclosed spaces such as corridors and rooms. Setting box projection to False and the cubemap reflection will be treated as coming from infinitely far away. Note that this feature can be globally disabled from Graphics Settings -> Tier Settings"));
EditorGUILayout.BeginVertical();
if (EditorGUI.EndChangeCheck())
if (p.editorAdvancedModeEnabled.boolValue)
var center = p.boxOffset.vector3Value;
var size = p.boxSize.vector3Value;
if (HDReflectionProbeEditorUtility.ValidateAABB(p.target, ref center, ref size))
EditorGUI.BeginChangeCheck();
CoreEditorUtils.DrawVector6(
content,
editorAdvancedModeBlendDistancePositive, editorAdvancedModeBlendDistanceNegative, Vector3.zero, maxBlendDistance, HDReflectionProbeEditor.k_handlesColor);
if(EditorGUI.EndChangeCheck())
p.boxOffset.vector3Value = center;
p.boxSize.vector3Value = size;
blendDistancePositive.vector3Value = editorAdvancedModeBlendDistancePositive.vector3Value;
blendDistanceNegative.vector3Value = editorAdvancedModeBlendDistanceNegative.vector3Value;
p.Apply();
else
{
float distance = editorSimplifiedModeBlendDistance.floatValue;
EditorGUI.BeginChangeCheck();
distance = EditorGUILayout.FloatField(content, distance);
if (EditorGUI.EndChangeCheck())
{
Vector3 decal = Vector3.one * distance;
bdp.x = Mathf.Clamp(decal.x, 0f, maxBlendDistance.x);
bdp.y = Mathf.Clamp(decal.y, 0f, maxBlendDistance.y);
bdp.z = Mathf.Clamp(decal.z, 0f, maxBlendDistance.z);
bdn.x = Mathf.Clamp(decal.x, 0f, maxBlendDistance.x);
bdn.y = Mathf.Clamp(decal.y, 0f, maxBlendDistance.y);
bdn.z = Mathf.Clamp(decal.z, 0f, maxBlendDistance.z);
blendDistancePositive.vector3Value = bdp;
blendDistanceNegative.vector3Value = bdn;
editorSimplifiedModeBlendDistance.floatValue = distance;
p.Apply();
}
}
GUILayout.EndVertical();
}
static void Drawer_InfluenceSphereSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)

var blendDistance = p.blendDistancePositive.vector3Value.x;
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = p.blendDistancePositive.hasMultipleDifferentValues;
blendDistance = EditorGUILayout.Slider(CoreEditorUtils.GetContent("Blend Distance|Area around the probe where it is blended with other probes. Only used in deferred probes."), blendDistance, 0, maxBlendDistance);

p.blendDistanceNegative.vector3Value = Vector3.one * blendDistance;
}
if (GUILayout.Button(toolbar_Contents[1], GUILayout.Width(28f), GUILayout.Height(EditorGUIUtility.singleLineHeight + 3)))
{
EditMode.ChangeEditMode(k_Toolbar_SceneViewEditModes[1], GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = p.blendNormalDistancePositive.hasMultipleDifferentValues;
blendNormalDistance = EditorGUILayout.Slider(CoreEditorUtils.GetContent("Blend Normal Distance|Area around the probe where the normals influence the probe. Only used in deferred probes."), blendNormalDistance, 0, maxBlendDistance);

p.blendNormalDistanceNegative.vector3Value = Vector3.one * blendNormalDistance;
}
if (GUILayout.Button(toolbar_Contents[2], GUILayout.Width(28f), GUILayout.Height(EditorGUIUtility.singleLineHeight + 3)))
{
EditMode.ChangeEditMode(k_Toolbar_SceneViewEditModes[2], GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.PropertyField(p.influenceSphereRadius, CoreEditorUtils.GetContent("Radius"));
EditorGUILayout.PropertyField(p.boxOffset, CoreEditorUtils.GetContent("Sphere Offset|The center of the sphere in which the reflections will be applied to objects. The value is relative to the position of the Game Object."));
EditorGUILayout.PropertyField(p.boxProjection, CoreEditorUtils.GetContent("Sphere Projection|Sphere projection causes reflections to appear to change based on the object's position within the probe's sphere, while still using a single probe as the source of the reflection. This works well for reflections on objects that are moving through enclosed spaces such as corridors and rooms. Setting sphere projection to False and the cubemap reflection will be treated as coming from infinitely far away. Note that this feature can be globally disabled from Graphics Settings -> Tier Settings"));
#endregion
#region Projection Volume
static void Drawer_UseSeparateProjectionVolume(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.PropertyField(p.useSeparateProjectionVolume);
s.isSectionExpandedSeparateProjection.target = p.useSeparateProjectionVolume.boolValue;
}
static void Drawer_ProjectionBoxSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.PropertyField(p.boxReprojectionVolumeSize);
EditorGUILayout.PropertyField(p.boxReprojectionVolumeCenter);
}
static void Drawer_ProjectionSphereSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.PropertyField(p.sphereReprojectionVolumeRadius);
}
#endregion
#region Field Drawers

}
}
static void Drawer_InfluenceAdvancedSwitch(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
bool advanced = p.editorAdvancedModeEnabled.boolValue;
advanced = !GUILayout.Toggle(!advanced, CoreEditorUtils.GetContent("Normal|Normal parameters mode (only change for box shape)."), EditorStyles.miniButtonLeft, GUILayout.Width(60f), GUILayout.ExpandWidth(false));
advanced = GUILayout.Toggle(advanced, CoreEditorUtils.GetContent("Advanced|Advanced parameters mode (only change for box shape)."), EditorStyles.miniButtonRight, GUILayout.Width(60f), GUILayout.ExpandWidth(false));
s.alternativeBoxBlendHandle.allHandleControledByOne = s.alternativeBoxBlendNormalHandle.allHandleControledByOne = !advanced;
if (p.editorAdvancedModeEnabled.boolValue ^ advanced)
{
p.editorAdvancedModeEnabled.boolValue = advanced;
if (advanced)
{
p.blendDistancePositive.vector3Value = p.editorAdvancedModeBlendDistancePositive.vector3Value;
p.blendDistanceNegative.vector3Value = p.editorAdvancedModeBlendDistanceNegative.vector3Value;
p.blendNormalDistancePositive.vector3Value = p.editorAdvancedModeBlendNormalDistancePositive.vector3Value;
p.blendNormalDistanceNegative.vector3Value = p.editorAdvancedModeBlendNormalDistanceNegative.vector3Value;
}
else
{
p.blendDistanceNegative.vector3Value = p.blendDistancePositive.vector3Value = Vector3.one * p.editorSimplifiedModeBlendDistance.floatValue;
p.blendNormalDistanceNegative.vector3Value = p.blendNormalDistancePositive.vector3Value = Vector3.one * p.editorSimplifiedModeBlendNormalDistance.floatValue;
}
p.Apply();
}
}
}
static void Drawer_InfluenceShape(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUI.BeginChangeCheck();

if (EditorGUI.EndChangeCheck())
s.SetShapeTarget(p.influenceShape.intValue);
if (p.proxyVolumeComponent.objectReferenceValue != null)
switch ((ShapeType)p.influenceShape.enumValueIndex)
var proxy = (ReflectionProxyVolumeComponent)p.proxyVolumeComponent.objectReferenceValue;
if ((int)proxy.proxyVolume.shapeType != p.influenceShape.enumValueIndex)
EditorGUILayout.HelpBox(
"Proxy volume and influence volume have different shape types, this is not supported.",
MessageType.Error,
true
);
case ShapeType.Box:
Drawer_InfluenceShapeBoxSettings(s, p, owner);
break;
case ShapeType.Sphere:
Drawer_InfluenceShapeSphereSettings(s, p, owner);
break;
}
}
static void Drawer_InfluenceShapeBoxSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(p.boxSize, CoreEditorUtils.GetContent("Box Size|The size of the box in which the reflections will be applied to objects. The value is not affected by the Transform of the Game Object."));
if (GUILayout.Button(toolbar_Contents[0], GUILayout.Width(28f), GUILayout.Height(EditorGUIUtility.singleLineHeight + 3)))
{
EditMode.ChangeEditMode(EditMode.SceneViewEditMode.ReflectionProbeBox, GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(p.boxOffset, CoreEditorUtils.GetContent("Box Offset|The center of the box in which the reflections will be applied to objects. The value is relative to the position of the Game Object."));
if (GUILayout.Button(toolbar_Contents[3], GUILayout.Width(28f), GUILayout.Height(EditorGUIUtility.singleLineHeight + 3)))
{
EditMode.ChangeEditMode(EditMode.SceneViewEditMode.ReflectionProbeOrigin, GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
var center = p.boxOffset.vector3Value;
var size = p.boxSize.vector3Value;
if (HDReflectionProbeEditorUtility.ValidateAABB(p.target, ref center, ref size))
{
//clamp to contains object center instead of resizing
Vector3 projector = (center - p.boxOffset.vector3Value).normalized;
p.boxOffset.vector3Value = center + Mathf.Abs(Vector3.Dot((p.boxSize.vector3Value - size) * .5f, projector)) * projector;
}
}
}
static void Drawer_InfluenceShapeSphereSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(p.influenceSphereRadius, CoreEditorUtils.GetContent("Radius"));
if (GUILayout.Button(toolbar_Contents[0], GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.Height(EditorGUIUtility.singleLineHeight + 3)))
{
EditMode.ChangeEditMode(EditMode.SceneViewEditMode.ReflectionProbeBox, GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(p.boxOffset, CoreEditorUtils.GetContent("Sphere Offset|The center of the sphere in which the reflections will be applied to objects. The value is relative to the position of the Game Object."));
if (GUILayout.Button(toolbar_Contents[3], GUILayout.ExpandHeight(true), GUILayout.Width(28f), GUILayout.Height(EditorGUIUtility.singleLineHeight + 3)))
{
EditMode.ChangeEditMode(EditMode.SceneViewEditMode.ReflectionProbeOrigin, GetBoundsGetter(p)(), owner);
}
EditorGUILayout.EndHorizontal();
}
static void Drawer_InfluenceAreas(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
if (s.IsSectionExpandedShape(ShapeType.Box).value)
{
Drawer_InfluenceBoxSettings(s, p, owner);
}
if (s.IsSectionExpandedShape(ShapeType.Sphere).value)
{
Drawer_InfluenceSphereSettings(s, p, owner);
static void Drawer_InfluenceSettings(HDReflectionProbeUI s, SerializedHDReflectionProbe p, Editor owner)
{
EditorGUILayout.PropertyField(p.boxProjection, CoreEditorUtils.GetContent("Parallax Correction|Parallax Correction causes reflections to appear to change based on the object's position within the probe's box, while still using a single probe as the source of the reflection. This works well for reflections on objects that are moving through enclosed spaces such as corridors and rooms. Setting Parallax Correction to False and the cubemap reflection will be treated as coming from infinitely far away. Note that this feature can be globally disabled from Graphics Settings -> Tier Settings"));
}
#endregion
#region Toolbar

static Func<Bounds> GetBoundsGetter(SerializedHDReflectionProbe p)
{
return () =>
{
var bounds = new Bounds();
foreach (var targetObject in p.so.targetObjects)
var rp = (ReflectionProbe)targetObject;
var b = rp.bounds;
bounds.Encapsulate(b);
}
return bounds;
};
var bounds = new Bounds();
foreach (var targetObject in p.so.targetObjects)
{
var rp = (ReflectionProbe)targetObject;
var b = rp.bounds;
bounds.Encapsulate(b);
}
return bounds;
};
}
static readonly KeyCode[] k_ShortCutKeys =

}
}
}
#endregion
#region Mode Specific Settings

EditorGUILayout.PropertyField(p.refreshMode, CoreEditorUtils.GetContent("Refresh Mode|Controls how this probe refreshes in the Player"));
EditorGUILayout.PropertyField(p.timeSlicingMode, CoreEditorUtils.GetContent("Time Slicing|If enabled this probe will update over several frames, to help reduce the impact on the frame rate"));
}
#endregion
static MethodInfo k_EditorGUI_ButtonWithDropdownList = typeof(EditorGUI).GetMethod("ButtonWithDropdownList", BindingFlags.Static | BindingFlags.NonPublic, null, CallingConventions.Any, new[] { typeof(GUIContent), typeof(string[]), typeof(GenericMenu.MenuFunction2), typeof(GUILayoutOption[]) }, new ParameterModifier[0]);

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


using System;
using System;
using System.IO;
using System.Linq;
using System.Reflection;

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


static HDReflectionProbeEditor GetEditorFor(ReflectionProbe p)
{
HDReflectionProbeEditor e;
if (s_ReflectionProbeEditors.TryGetValue(p, out e)
&& e != null
if (s_ReflectionProbeEditors.TryGetValue(p, out e)
&& e != null
&& !e.Equals(null)
&& ArrayUtility.IndexOf(e.targets, p) != -1)
return e;

static void PerformOperations(HDReflectionProbeUI s, SerializedHDReflectionProbe p, HDReflectionProbeEditor o)
{
}
void HideAdditionalComponents(bool visible)

for (var i = 0 ; i < targets.Length; ++i)
for (var i = 0; i < targets.Length; ++i)
{
var target = targets[i];
var addData = adds[i];

}
}
}
static void InspectColorsGUI()
{

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


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

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

var p = target as ReflectionProbe;
if (p != null && p.texture != null && targets.Length == 1)
m_CubemapEditor.DrawPreview(position);
}
bool ValidPreviewSetup()

}
private void OnDestroy()
{
DestroyImmediate(m_CubemapEditor);
}
}
}

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


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

internal static Color k_GizmoThemeColorDisabled = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
internal static Color k_GizmoThemeColorDisabledFace = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x10 / 255f);
internal static readonly Color[][] k_handlesColor = new Color[][]
{
new Color[]
{
Color.red,
Color.green,
Color.blue
},
new Color[]
{
new Color(.5f, 0f, 0f, 1f),
new Color(0f, .5f, 0f, 1f),
new Color(0f, 0f, .5f, 1f)
}
};
void OnSceneGUI()
{
var s = m_UIState;

static void Handle_InfluenceFadeEditing(HDReflectionProbeUI s, SerializedHDReflectionProbe sp, Editor o, InfluenceType influenceType)
{
BoxBoundsHandle blendBox;
Gizmo6FacesBoxContained alternativeBlendBox;
SphereBoundsHandle sphereHandle;
Vector3 probeBlendDistancePositive, probeBlendDistanceNegative;
Color color;

case InfluenceType.Standard:
{
blendBox = s.boxBlendHandle;
sphereHandle = s.sphereBlendHandle;
probeBlendDistancePositive = sp.targetData.blendDistancePositive;
probeBlendDistanceNegative = sp.targetData.blendDistanceNegative;
color = k_GizmoThemeColorInfluenceBlend;
break;
}
{
alternativeBlendBox = s.alternativeBoxBlendHandle;
sphereHandle = s.sphereBlendHandle;
probeBlendDistancePositive = sp.targetData.blendDistancePositive;
probeBlendDistanceNegative = sp.targetData.blendDistanceNegative;
color = k_GizmoThemeColorInfluenceBlend;
break;
}
{
blendBox = s.boxBlendNormalHandle;
sphereHandle = s.sphereBlendNormalHandle;
probeBlendDistancePositive = sp.targetData.blendNormalDistancePositive;
probeBlendDistanceNegative = sp.targetData.blendNormalDistanceNegative;
color = k_GizmoThemeColorInfluenceNormalBlend;
break;
}
{
alternativeBlendBox = s.alternativeBoxBlendNormalHandle;
sphereHandle = s.sphereBlendNormalHandle;
probeBlendDistancePositive = sp.targetData.blendNormalDistancePositive;
probeBlendDistanceNegative = sp.targetData.blendNormalDistanceNegative;
color = k_GizmoThemeColorInfluenceNormalBlend;
break;
}
var mat = Handles.matrix;
var col = Handles.color;

case ShapeType.Box:
{
blendBox.center = sp.target.center - (probeBlendDistancePositive - probeBlendDistanceNegative) * 0.5f;
blendBox.size = sp.target.size - probeBlendDistancePositive - probeBlendDistanceNegative;
Handles.color = k_GizmoThemeColorExtent;
EditorGUI.BeginChangeCheck();
Handles.color = color;
blendBox.DrawHandle();
if (EditorGUI.EndChangeCheck())
Undo.RecordObject(sp.target, "Modified Reflection Probe Influence");
Undo.RecordObject(sp.targetData, "Modified Reflection Probe Influence");
alternativeBlendBox.center = sp.target.center - (probeBlendDistancePositive - probeBlendDistanceNegative) * 0.5f;
alternativeBlendBox.size = sp.target.size - probeBlendDistancePositive - probeBlendDistanceNegative;
var center = sp.target.center;
var influenceSize = sp.target.size;
alternativeBlendBox.container.center = sp.target.center;
alternativeBlendBox.container.size = sp.target.size;
var diff = 2 * (blendBox.center - center);
var sum = influenceSize - blendBox.size;
var positive = (sum - diff) * 0.5f;
var negative = (sum + diff) * 0.5f;
var blendDistancePositive = Vector3.Max(Vector3.zero, Vector3.Min(positive, influenceSize));
var blendDistanceNegative = Vector3.Max(Vector3.zero, Vector3.Min(negative, influenceSize));
EditorGUI.BeginChangeCheck();
alternativeBlendBox.DrawHandle();
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(sp.target, "Modified Reflection Probe Influence");
Undo.RecordObject(sp.targetData, "Modified Reflection Probe Influence");
probeBlendDistancePositive = blendDistancePositive;
probeBlendDistanceNegative = blendDistanceNegative;
var center = sp.target.center;
var influenceSize = sp.target.size;
var diff = 2 * (alternativeBlendBox.center - center);
var sum = influenceSize - (alternativeBlendBox.size);
var positive = (sum - diff) * 0.5f;
var negative = (sum + diff) * 0.5f;
var blendDistancePositive = Vector3.Max(Vector3.zero, Vector3.Min(positive, influenceSize));
var blendDistanceNegative = Vector3.Max(Vector3.zero, Vector3.Min(negative, influenceSize));
probeBlendDistancePositive = blendDistancePositive;
probeBlendDistanceNegative = blendDistanceNegative;
ApplyConstraintsOnTargets(s, sp, o);
ApplyConstraintsOnTargets(s, sp, o);
EditorUtility.SetDirty(sp.target);
EditorUtility.SetDirty(sp.targetData);
EditorUtility.SetDirty(sp.target);
EditorUtility.SetDirty(sp.targetData);
}
break;
break;
}
{
sphereHandle.center = sp.target.center;
sphereHandle.radius = Mathf.Clamp(sp.targetData.influenceSphereRadius - probeBlendDistancePositive.x, 0, sp.targetData.influenceSphereRadius);
Handles.color = k_GizmoThemeColorExtent;
EditorGUI.BeginChangeCheck();
Handles.color = color;
sphereHandle.DrawHandle();
if (EditorGUI.EndChangeCheck())
Undo.RecordObject(sp.target, "Modified Reflection influence volume");
Undo.RecordObject(sp.targetData, "Modified Reflection influence volume");
sphereHandle.center = sp.target.center;
sphereHandle.radius = Mathf.Clamp(sp.targetData.influenceSphereRadius - probeBlendDistancePositive.x, 0, sp.targetData.influenceSphereRadius);
var influenceRadius = sp.targetData.influenceSphereRadius;
var blendRadius = sphereHandle.radius;
Handles.color = k_GizmoThemeColorExtent;
EditorGUI.BeginChangeCheck();
Handles.color = color;
sphereHandle.DrawHandle();
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(sp.target, "Modified Reflection influence volume");
Undo.RecordObject(sp.targetData, "Modified Reflection influence volume");
var blendDistance = Mathf.Clamp(influenceRadius - blendRadius, 0, influenceRadius);
var influenceRadius = sp.targetData.influenceSphereRadius;
var blendRadius = sphereHandle.radius;
probeBlendDistancePositive = Vector3.one * blendDistance;
probeBlendDistanceNegative = probeBlendDistancePositive;
var blendDistance = Mathf.Clamp(influenceRadius - blendRadius, 0, influenceRadius);
ApplyConstraintsOnTargets(s, sp, o);
probeBlendDistancePositive = Vector3.one * blendDistance;
probeBlendDistanceNegative = probeBlendDistancePositive;
EditorUtility.SetDirty(sp.target);
EditorUtility.SetDirty(sp.targetData);
ApplyConstraintsOnTargets(s, sp, o);
EditorUtility.SetDirty(sp.target);
EditorUtility.SetDirty(sp.targetData);
}
break;
break;
}
}
Handles.matrix = mat;
Handles.color = col;

{
default:
case InfluenceType.Standard:
{
sp.targetData.blendDistancePositive = probeBlendDistancePositive;
sp.targetData.blendDistanceNegative = probeBlendDistanceNegative;
break;
}
{
sp.blendDistancePositive.vector3Value = probeBlendDistancePositive;
sp.blendDistanceNegative.vector3Value = probeBlendDistanceNegative;
//save advanced/simplified saved data
if (sp.editorAdvancedModeEnabled.boolValue)
{
sp.editorAdvancedModeBlendDistancePositive.vector3Value = probeBlendDistancePositive;
sp.editorAdvancedModeBlendDistanceNegative.vector3Value = probeBlendDistanceNegative;
}
else
{
sp.editorSimplifiedModeBlendDistance.floatValue = probeBlendDistancePositive.x;
}
break;
}
{
sp.targetData.blendNormalDistancePositive = probeBlendDistancePositive;
sp.targetData.blendNormalDistanceNegative = probeBlendDistanceNegative;
break;
}
{
sp.blendNormalDistancePositive.vector3Value = probeBlendDistancePositive;
sp.blendNormalDistanceNegative.vector3Value = probeBlendDistanceNegative;
//save advanced/simplified saved data
if (sp.editorAdvancedModeEnabled.boolValue)
{
sp.editorAdvancedModeBlendNormalDistancePositive.vector3Value = probeBlendDistancePositive;
sp.editorAdvancedModeBlendNormalDistanceNegative.vector3Value = probeBlendDistanceNegative;
}
else
{
sp.editorSimplifiedModeBlendNormalDistance.floatValue = probeBlendDistancePositive.x;
}
break;
}
sp.Apply();
}
static void Handle_InfluenceEditing(HDReflectionProbeUI s, SerializedHDReflectionProbe sp, Editor o)

switch ((ShapeType)sp.influenceShape.enumValueIndex)
{
case ShapeType.Box:
{
s.boxInfluenceHandle.center = sp.target.center;
s.boxInfluenceHandle.size = sp.target.size;
Handles.color = k_GizmoThemeColorExtent;
EditorGUI.BeginChangeCheck();
s.boxInfluenceHandle.DrawHandle();
if (EditorGUI.EndChangeCheck())
Undo.RecordObject(sp.target, "Modified Reflection Probe AABB");
Undo.RecordObject(sp.targetData, "Modified Reflection Probe AABB");
s.alternativeBoxInfluenceHandle.center = sp.target.center;
s.alternativeBoxInfluenceHandle.size = sp.target.size;
var center = s.boxInfluenceHandle.center;
var size = s.boxInfluenceHandle.size;
EditorGUI.BeginChangeCheck();
s.alternativeBoxInfluenceHandle.DrawHandle();
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(sp.target, "Modified Reflection Probe AABB");
Undo.RecordObject(sp.targetData, "Modified Reflection Probe AABB");
HDReflectionProbeEditorUtility.ValidateAABB(sp.target, ref center, ref size);
Vector3 center;
Vector3 size;
center = s.alternativeBoxInfluenceHandle.center;
size = s.alternativeBoxInfluenceHandle.size;
sp.target.center = center;
sp.target.size = size;
HDReflectionProbeEditorUtility.ValidateAABB(sp.target, ref center, ref size);
ApplyConstraintsOnTargets(s, sp, o);
sp.target.center = center;
sp.target.size = size;
EditorUtility.SetDirty(sp.target);
EditorUtility.SetDirty(sp.targetData);
//ApplyConstraintsOnTargets(s, sp, o);
EditorUtility.SetDirty(sp.target);
EditorUtility.SetDirty(sp.targetData);
}
break;
break;
}
{
s.sphereInfluenceHandle.center = sp.target.center;
s.sphereInfluenceHandle.radius = sp.targetData.influenceSphereRadius;
Handles.color = k_GizmoThemeColorExtent;
EditorGUI.BeginChangeCheck();
s.sphereInfluenceHandle.DrawHandle();
if (EditorGUI.EndChangeCheck())
Undo.RecordObject(sp.target, "Modified Reflection Probe AABB");
Undo.RecordObject(sp.targetData, "Modified Reflection Probe AABB");
s.sphereInfluenceHandle.center = sp.target.center;
s.sphereInfluenceHandle.radius = sp.targetData.influenceSphereRadius;
var center = sp.target.center;
var influenceRadius = s.sphereInfluenceHandle.radius;
var radius = Vector3.one * influenceRadius;
Handles.color = k_GizmoThemeColorExtent;
EditorGUI.BeginChangeCheck();
s.sphereInfluenceHandle.DrawHandle();
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(sp.target, "Modified Reflection Probe AABB");
Undo.RecordObject(sp.targetData, "Modified Reflection Probe AABB");
HDReflectionProbeEditorUtility.ValidateAABB(sp.target, ref center, ref radius);
influenceRadius = radius.x;
var center = sp.target.center;
var influenceRadius = s.sphereInfluenceHandle.radius;
var radius = Vector3.one * influenceRadius;
sp.targetData.influenceSphereRadius = influenceRadius;
HDReflectionProbeEditorUtility.ValidateAABB(sp.target, ref center, ref radius);
influenceRadius = radius.x;
ApplyConstraintsOnTargets(s, sp, o);
sp.targetData.influenceSphereRadius = influenceRadius;
EditorUtility.SetDirty(sp.target);
EditorUtility.SetDirty(sp.targetData);
//ApplyConstraintsOnTargets(s, sp, o);
EditorUtility.SetDirty(sp.target);
EditorUtility.SetDirty(sp.targetData);
}
break;
break;
}
}
Handles.matrix = mat;
Handles.color = col;

var reflectionData = reflectionProbe.GetComponent<HDAdditionalReflectionData>();
Gizmos_Influence(reflectionProbe, reflectionData, null, false);
//Gizmos_Influence(reflectionProbe, reflectionData, e, false);
Gizmos_InfluenceFade(reflectionProbe, reflectionData, null, InfluenceType.Standard, false);
Gizmos_InfluenceFade(reflectionProbe, reflectionData, null, InfluenceType.Normal, false);

var e = GetEditorFor(reflectionProbe);
if (e == null || !e.sceneViewEditing)
return;
static void Gizmos_InfluenceFade(ReflectionProbe p, HDAdditionalReflectionData a, Editor e, InfluenceType type, bool isEdit)
static void Gizmos_InfluenceFade(ReflectionProbe p, HDAdditionalReflectionData a, HDReflectionProbeEditor e, InfluenceType type, bool isEdit)
Gizmo6FacesBoxContained box;
Vector3 boxCenterOffset;
Vector3 boxSizeOffset;
float sphereRadiusOffset;

default:
case InfluenceType.Standard:
{
boxCenterOffset = a.boxBlendCenterOffset;
boxSizeOffset = a.boxBlendSizeOffset;
sphereRadiusOffset = a.sphereBlendRadiusOffset;
color = isEdit ? k_GizmoThemeColorInfluenceBlendFace : k_GizmoThemeColorInfluenceBlend;
break;
}
{
box = e != null ? e.m_UIState.alternativeBoxBlendHandle : null;
boxCenterOffset = a.boxBlendCenterOffset;
boxSizeOffset = a.boxBlendSizeOffset;
sphereRadiusOffset = a.sphereBlendRadiusOffset;
color = isEdit ? k_GizmoThemeColorInfluenceBlendFace : k_GizmoThemeColorInfluenceBlend;
break;
}
{
boxCenterOffset = a.boxBlendNormalCenterOffset;
boxSizeOffset = a.boxBlendNormalSizeOffset;
sphereRadiusOffset = a.sphereBlendNormalRadiusOffset;
color = isEdit ? k_GizmoThemeColorInfluenceNormalBlendFace : k_GizmoThemeColorInfluenceNormalBlend;
break;
}
{
box = e != null ? e.m_UIState.alternativeBoxBlendNormalHandle : null;
boxCenterOffset = a.boxBlendNormalCenterOffset;
boxSizeOffset = a.boxBlendNormalSizeOffset;
sphereRadiusOffset = a.sphereBlendNormalRadiusOffset;
color = isEdit ? k_GizmoThemeColorInfluenceNormalBlendFace : k_GizmoThemeColorInfluenceNormalBlend;
break;
}
}
Gizmos.matrix = HDReflectionProbeEditorUtility.GetLocalSpace(p);

{
Gizmos.color = color;
if (isEdit)
Gizmos.DrawCube(p.center + boxCenterOffset, p.size + boxSizeOffset);
else
Gizmos.DrawWireCube(p.center + boxCenterOffset, p.size + boxSizeOffset);
break;
}
{
Gizmos.color = color;
if(e != null) // e == null may occure when editor have still not been created at selection while the tool is not used for this part
{
box.DrawHull(isEdit);
}
else
{
if (isEdit)
Gizmos.DrawCube(p.center + boxCenterOffset, p.size + boxSizeOffset);
else
Gizmos.DrawWireCube(p.center + boxCenterOffset, p.size + boxSizeOffset);
}
break;
}
{
Gizmos.color = color;
if (isEdit)
Gizmos.DrawSphere(p.center, a.influenceSphereRadius + sphereRadiusOffset);
else
Gizmos.DrawWireSphere(p.center, a.influenceSphereRadius + sphereRadiusOffset);
break;
}
{
Gizmos.color = color;
if (isEdit)
Gizmos.DrawSphere(p.center, a.influenceSphereRadius + sphereRadiusOffset);
else
Gizmos.DrawWireSphere(p.center, a.influenceSphereRadius + sphereRadiusOffset);
break;
}
}
Gizmos.matrix = mat;

static void Gizmos_Influence(ReflectionProbe p, HDAdditionalReflectionData a, Editor e, bool isEdit)
static void Gizmos_Influence(ReflectionProbe p, HDAdditionalReflectionData a, HDReflectionProbeEditor e, bool isEdit)
{
var col = Gizmos.color;
var mat = Gizmos.matrix;

{
case ShapeType.Box:
{
Gizmos.color = isEdit ? k_GizmoThemeColorExtentFace : k_GizmoThemeColorExtent;
if (isEdit)
Gizmos.DrawCube(p.center, p.size);
else
Gizmos.DrawWireCube(p.center, p.size);
break;
}
{
Gizmos.color = k_GizmoThemeColorExtentFace;
e.m_UIState.alternativeBoxInfluenceHandle.DrawHull(isEdit);
break;
}
{
Gizmos.color = k_GizmoThemeColorExtentFace;
if (isEdit)
Gizmos.DrawSphere(p.center, a.influenceSphereRadius);
else
Gizmos.DrawWireSphere(p.center, a.influenceSphereRadius);
break;
}
{
Gizmos.color = k_GizmoThemeColorExtentFace;
if (isEdit)
Gizmos.DrawSphere(p.center, a.influenceSphereRadius);
else
Gizmos.DrawWireSphere(p.center, a.influenceSphereRadius);
break;
}
}
Gizmos.matrix = mat;

6
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/HDCubemapInspector.cs


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

m_ReflectiveMaterial.SetFloat("_MipLevel", mipLevelPreview);
}
if(m_PreviewUtility == null)
if (m_PreviewUtility == null)
InitPreview();
UpdateCamera();

void InitPreview()
{
if (m_PreviewUtility != null)
m_PreviewUtility.Cleanup();
m_PreviewUtility = new PreviewRenderUtility(false, true);
m_PreviewUtility.cameraFieldOfView = 50.0f;
m_PreviewUtility.camera.nearClipPlane = 0.01f;

16
com.unity.render-pipelines.high-definition/HDRP/Editor/Lighting/Reflection/EditorReflectionSystemGUI.cs


case ReflectionProbeMode.Custom:
{
if (ButtonWithDropdownList(
_.GetContent("Bake|Bakes Reflection Probe's cubemap, overwriting the existing cubemap texture asset (if any)."), k_BakeCustomOptionText,
data =>
_.GetContent("Bake|Bakes Reflection Probe's cubemap, overwriting the existing cubemap texture asset (if any)."), k_BakeCustomOptionText,
data =>
{
var mode = (int)data;

}
}
},
GUILayout.ExpandWidth(true)))
GUILayout.ExpandWidth(true)))
{
if (probe != null)
{

case ReflectionProbeMode.Baked:
{
GUI.enabled = probe != null && probe.enabled
|| planarProbe != null && planarProbe.enabled;
|| planarProbe != null && planarProbe.enabled;
_.GetContent("Bake"),
k_BakeButtonsText,
data =>
_.GetContent("Bake"),
k_BakeButtonsText,
data =>
GUILayout.ExpandWidth(true)))
GUILayout.ExpandWidth(true)))
{
if (probe != null)
{

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


using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

if (IsCollidingWithOtherProbes(path, probe, out collidingProbe))
{
if (!EditorUtility.DisplayDialog("Texture is used by other reflection probe",
string.Format("'{0}' path is used by the game object '{1}', do you really want to overwrite it?",
path, collidingProbe.name), "Yes", "No"))
string.Format("'{0}' path is used by the game object '{1}', do you really want to overwrite it?",
path, collidingProbe.name), "Yes", "No"))
{
return;
}

var scene = probe.gameObject.scene;
var directory = Path.Combine(Path.GetDirectoryName(scene.path), Path.GetFileNameWithoutExtension(scene.path));
var filename = string.Format("PlanarReflectionProbe-{0}.exr", 0);
return Path.Combine(directory, filename);
}

if (IsCollidingWithOtherProbes(path, probe, out collidingProbe))
{
if (!EditorUtility.DisplayDialog("Cubemap is used by other reflection probe",
string.Format("'{0}' path is used by the game object '{1}', do you really want to overwrite it?",
path, collidingProbe.name), "Yes", "No"))
string.Format("'{0}' path is used by the game object '{1}', do you really want to overwrite it?",
path, collidingProbe.name), "Yes", "No"))
{
return;
}

if (result == null)
{
result = EditorUtility.CreateGameObjectWithHideFlags(
"Reflection System Dictionary",
k_ReflectionSystemDictionaryHideFlags,
typeof(ReflectionSystemSceneDictionary))
"Reflection System Dictionary",
k_ReflectionSystemDictionaryHideFlags,
typeof(ReflectionSystemSceneDictionary))
.GetComponent<ReflectionSystemSceneDictionary>();
SceneManager.MoveGameObjectToScene(result.gameObject, scene);

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


using System;
using System.Linq;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Experimental.Rendering;

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

sealed class SerializedLightData
{
public SerializedProperty directionalIntensity;
public SerializedProperty punctualIntensity;
public SerializedProperty areaIntensity;
public SerializedProperty intensity;
public SerializedProperty enableSpotReflector;
public SerializedProperty spotInnerPercent;
public SerializedProperty lightDimmer;

public SerializedProperty nonLightmappedOnly;
public SerializedProperty lightTypeExtent;
public SerializedProperty spotLightShape;
public SerializedProperty shapeWidth;

public SerializedProperty maxSmoothness;
public SerializedProperty applyRangeAttenuation;
public SerializedProperty volumetricDimmer;
public SerializedProperty lightUnit;
public SerializedProperty displayAreaLightEmissiveMesh;
// Editor stuff
public SerializedProperty useOldInspector;

public SerializedProperty dimmer;
public SerializedProperty fadeDistance;
public SerializedProperty resolution;
public SerializedProperty contactShadows;
// Bias control
public SerializedProperty viewBiasMin;

//Disc,
}
enum DirectionalLightUnit
{
Lux = LightUnit.Lux,
}
enum AreaLightUnit
{
Lumen = LightUnit.Lumen,
Luminance = LightUnit.Luminance,
}
enum PunctualLightUnit
{
Lumen = LightUnit.Lumen,
Candela = LightUnit.Candela,
}
HDAdditionalLightData[] m_AdditionalLightDatas;
AdditionalShadowData[] m_AdditionalShadowDatas;
bool m_UpdateAreaLightEmissiveMeshComponents = false;
protected override void OnEnable()
{

var lightData = CoreEditorUtils.GetAdditionalData<HDAdditionalLightData>(targets, HDAdditionalLightData.InitDefaultHDAdditionalLightData);
var shadowData = CoreEditorUtils.GetAdditionalData<AdditionalShadowData>(targets, HDAdditionalShadowData.InitDefaultHDAdditionalShadowData);
m_SerializedAdditionalLightData = new SerializedObject(lightData);
m_SerializedAdditionalShadowData = new SerializedObject(shadowData);
m_AdditionalLightDatas = CoreEditorUtils.GetAdditionalData<HDAdditionalLightData>(targets, HDAdditionalLightData.InitDefaultHDAdditionalLightData);
m_AdditionalShadowDatas = CoreEditorUtils.GetAdditionalData<AdditionalShadowData>(targets, HDAdditionalShadowData.InitDefaultHDAdditionalShadowData);
m_SerializedAdditionalLightData = new SerializedObject(m_AdditionalLightDatas);
m_SerializedAdditionalShadowData = new SerializedObject(m_AdditionalShadowDatas);
m_AdditionalLightData = new SerializedLightData
{
directionalIntensity = o.Find(x => x.directionalIntensity),
punctualIntensity = o.Find(x => x.punctualIntensity),
areaIntensity = o.Find(x => x.areaIntensity),
enableSpotReflector = o.Find(x => x.enableSpotReflector),
spotInnerPercent = o.Find(x => x.m_InnerSpotPercent),
lightDimmer = o.Find(x => x.lightDimmer),
fadeDistance = o.Find(x => x.fadeDistance),
affectDiffuse = o.Find(x => x.affectDiffuse),
affectSpecular = o.Find(x => x.affectSpecular),
lightTypeExtent = o.Find(x => x.lightTypeExtent),
spotLightShape = o.Find(x => x.spotLightShape),
shapeWidth = o.Find(x => x.shapeWidth),
shapeHeight = o.Find(x => x.shapeHeight),
aspectRatio = o.Find(x => x.aspectRatio),
shapeRadius = o.Find(x => x.shapeRadius),
maxSmoothness = o.Find(x => x.maxSmoothness),
applyRangeAttenuation = o.Find(x => x.applyRangeAttenuation),
m_AdditionalLightData = new SerializedLightData
{
intensity = o.Find(x => x.displayLightIntensity),
enableSpotReflector = o.Find(x => x.enableSpotReflector),
spotInnerPercent = o.Find(x => x.m_InnerSpotPercent),
lightDimmer = o.Find(x => x.lightDimmer),
volumetricDimmer = o.Find(x => x.volumetricDimmer),
lightUnit = o.Find(x => x.lightUnit),
displayAreaLightEmissiveMesh = o.Find(x => x.displayAreaLightEmissiveMesh),
fadeDistance = o.Find(x => x.fadeDistance),
affectDiffuse = o.Find(x => x.affectDiffuse),
affectSpecular = o.Find(x => x.affectSpecular),
nonLightmappedOnly = o.Find(x => x.nonLightmappedOnly),
lightTypeExtent = o.Find(x => x.lightTypeExtent),
spotLightShape = o.Find(x => x.spotLightShape),
shapeWidth = o.Find(x => x.shapeWidth),
shapeHeight = o.Find(x => x.shapeHeight),
aspectRatio = o.Find(x => x.aspectRatio),
shapeRadius = o.Find(x => x.shapeRadius),
maxSmoothness = o.Find(x => x.maxSmoothness),
applyRangeAttenuation = o.Find(x => x.applyRangeAttenuation),
// Editor stuff
useOldInspector = o.Find(x => x.useOldInspector),
showFeatures = o.Find(x => x.featuresFoldout),
showAdditionalSettings = o.Find(x => x.showAdditionalSettings)
};
// Editor stuff
useOldInspector = o.Find(x => x.useOldInspector),
showFeatures = o.Find(x => x.featuresFoldout),
showAdditionalSettings = o.Find(x => x.showAdditionalSettings)
};
m_AdditionalShadowData = new SerializedShadowData
{
dimmer = o.Find(x => x.shadowDimmer),
fadeDistance = o.Find(x => x.shadowFadeDistance),
resolution = o.Find(x => x.shadowResolution),
m_AdditionalShadowData = new SerializedShadowData
{
dimmer = o.Find(x => x.shadowDimmer),
fadeDistance = o.Find(x => x.shadowFadeDistance),
resolution = o.Find(x => x.shadowResolution),
contactShadows = o.Find(x => x.contactShadows),
viewBiasMin = o.Find(x => x.viewBiasMin),
viewBiasMax = o.Find(x => x.viewBiasMax),
viewBiasScale = o.Find(x => x.viewBiasScale),
normalBiasMin = o.Find(x => x.normalBiasMin),
normalBiasMax = o.Find(x => x.normalBiasMax),
normalBiasScale = o.Find(x => x.normalBiasScale),
sampleBiasScale = o.Find(x => x.sampleBiasScale),
edgeLeakFixup = o.Find(x => x.edgeLeakFixup),
edgeToleranceNormal = o.Find(x => x.edgeToleranceNormal),
edgeTolerance = o.Find(x => x.edgeTolerance)
viewBiasMin = o.Find(x => x.viewBiasMin),
viewBiasMax = o.Find(x => x.viewBiasMax),
viewBiasScale = o.Find(x => x.viewBiasScale),
normalBiasMin = o.Find(x => x.normalBiasMin),
normalBiasMax = o.Find(x => x.normalBiasMax),
normalBiasScale = o.Find(x => x.normalBiasScale),
sampleBiasScale = o.Find(x => x.sampleBiasScale),
edgeLeakFixup = o.Find(x => x.edgeLeakFixup),
edgeToleranceNormal = o.Find(x => x.edgeToleranceNormal),
edgeTolerance = o.Find(x => x.edgeTolerance)
};
// Update emissive mesh and light intensity when undo/redo
Undo.undoRedoPerformed += () => {
m_SerializedAdditionalLightData.ApplyModifiedProperties();
foreach (var hdLightData in m_AdditionalLightDatas)
if (hdLightData != null)
hdLightData.UpdateAreaLightEmissiveMesh();
};
}

m_SerializedAdditionalShadowData.ApplyModifiedProperties();
m_SerializedAdditionalLightData.ApplyModifiedProperties();
settings.ApplyModifiedProperties();
if (m_UpdateAreaLightEmissiveMeshComponents)
UpdateAreaLightEmissiveMeshComponents();
// If the light is disabled in the editor we force the light upgrade from his inspector
foreach (var additionalLightData in m_AdditionalLightDatas)
additionalLightData.UpgradeLight();
}
void DrawFoldout(SerializedProperty foldoutProperty, string title, Action func)

void DrawFeatures()
{
bool disabledScope = settings.isCompletelyBaked
|| m_LightShape == LightShape.Line
|| m_LightShape == LightShape.Rectangle;
bool disabledScope = m_LightShape == LightShape.Line || (m_LightShape == LightShape.Rectangle && settings.isRealtime);
using (new EditorGUI.DisabledScope(disabledScope))
{

{
EditorGUI.BeginChangeCheck(); // For GI we need to detect any change on additional data and call SetLightDirty + For intensity we need to detect light shape change
EditorGUI.BeginChangeCheck();
if (EditorGUI.EndChangeCheck())
UpdateLightIntensityUnit();
if (m_LightShape != LightShape.Directional)
settings.DrawRange(false);

m_AdditionalLightData.shapeHeight.floatValue = Mathf.Max(m_AdditionalLightData.shapeHeight.floatValue, k_MinAreaWidth);
settings.areaSizeX.floatValue = m_AdditionalLightData.shapeWidth.floatValue;
settings.areaSizeY.floatValue = m_AdditionalLightData.shapeHeight.floatValue;
settings.shadowsType.enumValueIndex = (int)LightShadows.None;
if (settings.isRealtime)
settings.shadowsType.enumValueIndex = (int)LightShadows.None;
break;
case LightShape.Line:

if (EditorGUI.EndChangeCheck())
{
UpdateLightIntensity();
UpdateLightScale();
m_UpdateAreaLightEmissiveMeshComponents = true;
// Caution: this function must match the one in HDAdditionalLightData.ConvertPhysicalLightIntensityToLightIntensity - any change need to be replicated
void UpdateLightIntensity()
void UpdateLightIntensityUnit()
// Clamp negative values.
m_AdditionalLightData.directionalIntensity.floatValue = Mathf.Max(0, m_AdditionalLightData.directionalIntensity.floatValue);
m_AdditionalLightData.punctualIntensity.floatValue = Mathf.Max(0, m_AdditionalLightData.punctualIntensity.floatValue);
m_AdditionalLightData.areaIntensity.floatValue = Mathf.Max(0, m_AdditionalLightData.areaIntensity.floatValue);
if (m_LightShape == LightShape.Directional)
m_AdditionalLightData.lightUnit.enumValueIndex = (int)DirectionalLightUnit.Lux;
else
m_AdditionalLightData.lightUnit.enumValueIndex = (int)LightUnit.Lumen;
}
switch (m_LightShape)
// Refect light size changes on transform local scale
void UpdateLightScale()
{
foreach (var hdLightData in m_AdditionalLightDatas)
{
switch (m_LightShape)
{
case LightShape.Line:
hdLightData.transform.localScale = new Vector3(m_AdditionalLightData.shapeWidth.floatValue, 0, 0);
break;
case LightShape.Rectangle:
hdLightData.transform.localScale = new Vector3(m_AdditionalLightData.shapeWidth.floatValue, m_AdditionalLightData.shapeHeight.floatValue, 0);
break;
case LightShape.Point:
case LightShape.Spot:
hdLightData.transform.localScale = Vector3.one * settings.range.floatValue;
break;
}
}
}
LightUnit LightIntensityUnitPopup(LightShape shape)
{
LightUnit selectedLightUnit;
LightUnit oldLigthUnit = (LightUnit)m_AdditionalLightData.lightUnit.enumValueIndex;
EditorGUI.BeginChangeCheck();
switch (shape)
settings.intensity.floatValue = m_AdditionalLightData.directionalIntensity.floatValue;
selectedLightUnit = (LightUnit)EditorGUILayout.EnumPopup((DirectionalLightUnit)m_AdditionalLightData.lightUnit.enumValueIndex);
settings.intensity.floatValue = LightUtils.ConvertPointLightIntensity(m_AdditionalLightData.punctualIntensity.floatValue);
case LightShape.Spot:
selectedLightUnit = (LightUnit)EditorGUILayout.EnumPopup((PunctualLightUnit)m_AdditionalLightData.lightUnit.enumValueIndex);
default:
selectedLightUnit = (LightUnit)EditorGUILayout.EnumPopup((AreaLightUnit)m_AdditionalLightData.lightUnit.enumValueIndex);
break;
}
if (EditorGUI.EndChangeCheck())
ConvertLightIntensity(oldLigthUnit, selectedLightUnit);
case LightShape.Spot:
// Spot should used conversion which take into account the angle, and thus the intensity vary with angle.
// This is not easy to manipulate for lighter, so we simply consider any spot light as just occluded point light. So reuse the same code.
return selectedLightUnit;
}
var spotLightShape = (SpotLightShape)m_AdditionalLightData.spotLightShape.enumValueIndex;
void ConvertLightIntensity(LightUnit oldLightUnit, LightUnit newLightUnit)
{
float intensity = m_AdditionalLightData.intensity.floatValue;
if (m_AdditionalLightData.enableSpotReflector.boolValue)
// For punctual lights
if (oldLightUnit == LightUnit.Lumen && newLightUnit == LightUnit.Candela)
{
if (m_LightShape == LightShape.Spot && m_AdditionalLightData.enableSpotReflector.boolValue)
{
// We have already calculate the correct value, just assign it
intensity = ((Light)target).intensity;
}
else
intensity = LightUtils.ConvertPointLightLumenToCandela(intensity);
}
if (oldLightUnit == LightUnit.Candela && newLightUnit == LightUnit.Lumen)
{
if (m_LightShape == LightShape.Spot && m_AdditionalLightData.enableSpotReflector.boolValue)
{
// We just need to multiply candela by solid angle in this case
if ((SpotLightShape)m_AdditionalLightData.spotLightShape.enumValueIndex == SpotLightShape.Cone)
intensity = LightUtils.ConvertSpotLightCandelaToLumen(intensity, ((Light)target).spotAngle * Mathf.Deg2Rad, true);
else if ((SpotLightShape)m_AdditionalLightData.spotLightShape.enumValueIndex == SpotLightShape.Pyramid)
if (spotLightShape == SpotLightShape.Cone)
{
settings.intensity.floatValue = LightUtils.ConvertSpotLightIntensity(m_AdditionalLightData.punctualIntensity.floatValue, settings.spotAngle.floatValue * Mathf.Deg2Rad, true );
}
else if (spotLightShape == SpotLightShape.Pyramid)
{
float angleA, angleB;
LightUtils.CalculateAnglesForPyramid( m_AdditionalLightData.aspectRatio.floatValue, settings.spotAngle.floatValue,
out angleA, out angleB);
float angleA, angleB;
LightUtils.CalculateAnglesForPyramid(m_AdditionalLightData.aspectRatio.floatValue, ((Light)target).spotAngle * Mathf.Deg2Rad, out angleA, out angleB);
settings.intensity.floatValue = LightUtils.ConvertFrustrumLightIntensity(m_AdditionalLightData.punctualIntensity.floatValue, angleA, angleB );
}
else // Box shape, fallback to punctual light.
{
settings.intensity.floatValue = LightUtils.ConvertPointLightIntensity(m_AdditionalLightData.punctualIntensity.floatValue);
}
intensity = LightUtils.ConvertFrustrumLightCandelaToLumen(intensity, angleA, angleB);
else // Reflector disabled, fallback to punctual light.
{
settings.intensity.floatValue = LightUtils.ConvertPointLightIntensity(m_AdditionalLightData.punctualIntensity.floatValue);
}
break;
else // Box
intensity = LightUtils.ConvertPointLightCandelaToLumen(intensity);
}
else
intensity = LightUtils.ConvertPointLightCandelaToLumen(intensity);
}
case LightShape.Rectangle:
settings.intensity.floatValue = LightUtils.ConvertRectLightIntensity(m_AdditionalLightData.areaIntensity.floatValue, m_AdditionalLightData.shapeWidth.floatValue, m_AdditionalLightData.shapeHeight.floatValue);
break;
// For area lights
if (oldLightUnit == LightUnit.Lumen && newLightUnit == LightUnit.Luminance)
{
if (m_LightShape == LightShape.Rectangle)
intensity = LightUtils.ConvertRectLightLumenToLuminance(intensity, m_AdditionalLightData.shapeWidth.floatValue, m_AdditionalLightData.shapeHeight.floatValue);
else if (m_LightShape == LightShape.Line)
intensity = LightUtils.CalculateLineLightLumenToLuminance(intensity, m_AdditionalLightData.shapeWidth.floatValue);
}
if (oldLightUnit == LightUnit.Luminance && newLightUnit == LightUnit.Lumen)
{
if (m_LightShape == LightShape.Rectangle)
intensity = LightUtils.ConvertRectLightLuminanceToLumen(intensity, m_AdditionalLightData.shapeWidth.floatValue, m_AdditionalLightData.shapeHeight.floatValue);
else if (m_LightShape == LightShape.Line)
intensity = LightUtils.CalculateLineLightLuminanceToLumen(intensity, m_AdditionalLightData.shapeWidth.floatValue);
}
case LightShape.Line:
settings.intensity.floatValue = LightUtils.CalculateLineLightIntensity(m_AdditionalLightData.areaIntensity.floatValue, m_AdditionalLightData.shapeWidth.floatValue);
break;
}
m_AdditionalLightData.intensity.floatValue = intensity;
void DrawLightSettings()
void UpdateAreaLightEmissiveMeshComponents()
settings.DrawColor();
EditorGUI.BeginChangeCheck();
switch (m_LightShape)
foreach (var hdLightData in m_AdditionalLightDatas)
case LightShape.Directional:
EditorGUILayout.PropertyField(m_AdditionalLightData.directionalIntensity, s_Styles.directionalIntensity);
break;
hdLightData.UpdateAreaLightEmissiveMesh();
case LightShape.Point:
case LightShape.Spot:
EditorGUILayout.PropertyField(m_AdditionalLightData.punctualIntensity, s_Styles.punctualIntensity);
MeshRenderer emissiveMeshRenderer = hdLightData.GetComponent<MeshRenderer>();
MeshFilter emissiveMeshFilter = hdLightData.GetComponent<MeshFilter>();
// Only display reflector option if it make sense
if (m_LightShape == LightShape.Spot)
{
var spotLightShape = (SpotLightShape)m_AdditionalLightData.spotLightShape.enumValueIndex;
if (spotLightShape == SpotLightShape.Cone || spotLightShape == SpotLightShape.Pyramid)
EditorGUILayout.PropertyField(m_AdditionalLightData.enableSpotReflector, s_Styles.enableSpotReflector);
}
break;
// If the display emissive mesh is disabled, skip to the next selected light
if (emissiveMeshFilter == null || emissiveMeshRenderer == null)
continue ;
case LightShape.Rectangle:
case LightShape.Line:
EditorGUILayout.PropertyField(m_AdditionalLightData.areaIntensity, s_Styles.areaIntensity);
break;
// We only load the mesh and it's material here, because we can't do that inside HDAdditionalLightData (Editor assembly)
// Every other properties of the mesh is updated in HDAdditionalLightData to support timeline and editor records
emissiveMeshFilter.mesh = UnityEditor.Experimental.Rendering.HDPipeline.HDEditorUtils.LoadAsset< Mesh >("RenderPipelineResources/Quad.FBX");
if (emissiveMeshRenderer.sharedMaterial == null)
emissiveMeshRenderer.material = new Material(Shader.Find("HDRenderPipeline/Unlit"));
if (EditorGUI.EndChangeCheck())
m_UpdateAreaLightEmissiveMeshComponents = false;
}
void DrawLightSettings()
{
settings.DrawColor();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(m_AdditionalLightData.intensity, s_Styles.lightIntensity);
m_AdditionalLightData.lightUnit.enumValueIndex = (int)LightIntensityUnitPopup(m_LightShape);
EditorGUILayout.EndHorizontal();
// Only display reflector option if it make sense
if (m_LightShape == LightShape.Spot)
UpdateLightIntensity();
var spotLightShape = (SpotLightShape)m_AdditionalLightData.spotLightShape.enumValueIndex;
if ((spotLightShape == SpotLightShape.Cone || spotLightShape == SpotLightShape.Pyramid)
&& m_AdditionalLightData.lightUnit.enumValueIndex == (int)PunctualLightUnit.Lumen)
EditorGUILayout.PropertyField(m_AdditionalLightData.enableSpotReflector, s_Styles.enableSpotReflector);
}
settings.DrawBounceIntensity();

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

EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_AdditionalLightData.affectDiffuse, s_Styles.affectDiffuse);
EditorGUILayout.PropertyField(m_AdditionalLightData.affectSpecular, s_Styles.affectSpecular);
EditorGUILayout.PropertyField(m_AdditionalLightData.fadeDistance, s_Styles.fadeDistance);
if (m_LightShape != LightShape.Directional)
EditorGUILayout.PropertyField(m_AdditionalLightData.fadeDistance, s_Styles.fadeDistance);
EditorGUILayout.PropertyField(m_AdditionalLightData.applyRangeAttenuation, s_Styles.applyRangeAttenuation);
EditorGUILayout.PropertyField(m_AdditionalLightData.volumetricDimmer, s_Styles.volumetricDimmer);
if (m_LightShape != LightShape.Directional)
EditorGUILayout.PropertyField(m_AdditionalLightData.applyRangeAttenuation, s_Styles.applyRangeAttenuation);
// Emissive mesh for area light only
if (HDAdditionalLightData.IsAreaLight(m_AdditionalLightData.lightTypeExtent))
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AdditionalLightData.displayAreaLightEmissiveMesh, s_Styles.displayAreaLightEmissiveMesh);
if (EditorGUI.EndChangeCheck())
m_UpdateAreaLightEmissiveMeshComponents = true;
}
EditorGUI.indentLevel--;
}

EditorGUILayout.PropertyField(settings.bakedShadowRadiusProp, s_Styles.bakedShadowRadius);
break;
}
if (settings.isMixed)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AdditionalLightData.nonLightmappedOnly, s_Styles.nonLightmappedOnly);
if (EditorGUI.EndChangeCheck())
{
((Light)target).lightShadowCasterMode = m_AdditionalLightData.nonLightmappedOnly.boolValue ? LightShadowCasterMode.NonLightmappedOnly : LightShadowCasterMode.Everything;
}
}
}
void DrawShadows()

EditorGUILayout.Space();
EditorGUILayout.LabelField("Additional Settings", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_AdditionalShadowData.contactShadows, s_Styles.contactShadows);
if (settings.lightType.enumValueIndex != (int)LightType.Directional)
{

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


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

public readonly GUIContent directionalIntensity = new GUIContent("Intensity (Lux)", "Illuminance of the directional light at ground level in lux.");
public readonly GUIContent punctualIntensity = new GUIContent("Intensity (Lumen)", "Luminous power of the light in lumen. Spotlight are considered as point light with barndoor so match intensity of a point light.");
public readonly GUIContent areaIntensity = new GUIContent("Intensity (Lumen)", "Luminous power of the light in lumen.");
public readonly GUIContent lightIntensity = new GUIContent("Intensity", "");
public readonly GUIContent nonLightmappedOnly = new GUIContent("Non Lightmapped Only", "This will disable the rendering of lightmapped object for shadow map. Only effective with shadow mask feature");
public readonly GUIContent volumetricDimmer = new GUIContent("Volumetric Dimmer", "Allows to reduce the intensity of the scattered volumetric lighting.");
public readonly GUIContent fadeDistance = new GUIContent("Fade Distance", "The distance at which the light will smoothly fade before being culled to minimize popping.");
public readonly GUIContent spotInnerPercent = new GUIContent("Inner Percent", "Controls size of the angular attenuation in percent of the base angle of the Spot light's cone.");
public readonly GUIContent spotLightShape = new GUIContent("Shape", "The shape use for the spotlight. Has an impact on the cookie transformation and light angular attenuation.");

public readonly GUIContent shapeWidthBox = new GUIContent("Size X", "");
public readonly GUIContent shapeHeightBox = new GUIContent("Size Y", "");
public readonly GUIContent applyRangeAttenuation = new GUIContent("Apply Range Attenuation", "Allows disabling range attenuation. This is useful indoor (like a room) to avoid having to setup a large range for a light to get correct inverse square attenuation that may leak out of the indoor");
public readonly GUIContent displayAreaLightEmissiveMesh = new GUIContent("Display Emissive Mesh", "Generate an emissive mesh using the size, color and intensity of the area light");
public readonly GUIContent enableSpotReflector = new GUIContent("Enable spot reflector", "When true it simulate a spot light with reflector (mean the intensity of the light will be more focus with narrower angle), otherwise light outside of the cone is simply absorbed (mean intensity is constent whatever the size of the cone).");
public readonly GUIContent enableSpotReflector = new GUIContent("Angle affect intensity", "When true it simulate a spot light with reflector (mean the intensity of the light will be more focus with narrower angle), otherwise light outside of the cone is simply absorbed (mean intensity is constent whatever the size of the cone).");
public readonly GUIContent contactShadows = new GUIContent("Enable Contact Shadows", "Enable support for contact shadows on this light. Better for lights with a lot of visible shadows.");
// Bias control
public readonly GUIContent viewBiasMin = new GUIContent("View Bias");

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


string CorePath = HDEditorUtils.GetCorePath();
newAsset.defaultDiffuseMaterial = Load<Material>(HDRenderPipelinePath + "RenderPipelineResources/DefaultHDMaterial.mat");
newAsset.defaultMirrorMaterial = Load<Material>(HDRenderPipelinePath + "RenderPipelineResources/DefaultHDMirrorMaterial.mat");
newAsset.defaultTerrainMaterial = Load<Material>(HDRenderPipelinePath + "RenderPipelineResources/DefaultHDTerrainMaterial.mat");
newAsset.defaultShader = Load<Shader>(HDRenderPipelinePath + "Material/Lit/Lit.shader");
newAsset.debugFontTexture = Load<Texture2D>(HDRenderPipelinePath + "RenderPipelineResources/DebugFont.tga");

newAsset.buildMaterialFlagsShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/LightLoop/materialflags.compute");
newAsset.deferredComputeShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/LightLoop/Deferred.compute");
newAsset.deferredDirectionalShadowComputeShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/DeferredDirectionalShadow.compute");
newAsset.screenSpaceShadowComputeShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/ScreenSpaceShadow.compute");
newAsset.volumeVoxelizationCS = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/Volumetrics/VolumeVoxelization.compute");
newAsset.volumetricLightingCS = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/Volumetrics/VolumetricLighting.compute");

newAsset.skyboxCubemap = Shader.Find("Skybox/Cubemap");
// Material
newAsset.preIntegratedFGD = Load<Shader>(HDRenderPipelinePath + "Material/PreIntegratedFGD.shader");
newAsset.preIntegratedFGD_GGXDisneyDiffuse = Load<Shader>(HDRenderPipelinePath + "Material/PreIntegratedFGD/PreIntegratedFGD_GGXDisneyDiffuse.shader");
newAsset.preIntegratedFGD_CharlieClothLambert = Load<Shader>(HDRenderPipelinePath + "Material/PreIntegratedFGD/PreIntegratedFGD_CharlieClothLambert.shader");
// Utilities / Core
newAsset.encodeBC6HCS = Load<ComputeShader>(CorePath + "CoreResources/EncodeBC6H.compute");

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


fileFormatVersion: 2
guid: 168f8e50628e857489eb62f41d9c911f
guid: d342206cb3c614b4fa4caee7fb269b93
MonoImporter:
externalObjects: {}
serializedVersion: 2

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


using System.Collections;
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Build;
using UnityEditor.Rendering;

namespace UnityEditor.Experimental.Rendering.HDPipeline
{
#if UNITY_2018_2_OR_NEWER
class HDRPVariantStripper : IPreprocessShaders
class HDRPreprocessShaders : IPreprocessShaders
// returns true if the variant should be stripped.
delegate bool VariantStrippingFunc(Shader shader, ShaderSnippetData snippet, ShaderCompilerData inputData);
ShaderKeyword m_ShadowMask;
ShaderKeyword m_Transparent;
ShaderKeyword m_DebugDisplay;
ShaderKeyword m_TileLighting;
ShaderKeyword m_ClusterLighting;
ShaderKeyword m_FeatureSSS;
public HDRPVariantStripper()
public HDRPreprocessShaders()
{
// TODO: Grab correct configuration/quality asset.
HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;

m_StripperFuncs = new Dictionary<string, VariantStrippingFunc>();
m_StripperFuncs.Add("HDRenderPipeline/Lit", LitShaderStripper);
m_StripperFuncs.Add("HDRenderPipeline/LitTessellation", LitShaderStripper);
m_StripperFuncs.Add("HDRenderPipeline/LayeredLit", LitShaderStripper);
m_StripperFuncs.Add("HDRenderPipeline/LayeredLitTessellation", LitShaderStripper);
m_Transparent = new ShaderKeyword("_SURFACE_TYPE_TRANSPARENT");
m_DebugDisplay = new ShaderKeyword("DEBUG_DISPLAY");
m_TileLighting = new ShaderKeyword("USE_FPTL_LIGHTLIST");
m_ClusterLighting = new ShaderKeyword("USE_CLUSTERED_LIGHTLIST");
m_FeatureSSS = new ShaderKeyword("_MATERIAL_FEATURE_SUBSURFACE_SCATTERING");
}
bool LitShaderStripper(Shader shader, ShaderSnippetData snippet, ShaderCompilerData inputData)
{
bool isGBufferPass = snippet.passName == "GBuffer";
bool isForwardPass = snippet.passName == "Forward";
bool isTransparentForwardPass = snippet.passName == "TransparentDepthPostpass" || snippet.passName == "TransparentBackface" || snippet.passName == "TransparentDepthPrepass";
bool isMotionPass = snippet.passName == "Motion Vectors";
// NOTE: All these keyword should be automatically stripped so there's no need to handle them ourselves.
// LIGHTMAP_ON, DIRLIGHTMAP_COMBINED, DYNAMICLIGHTMAP_ON, LIGHTMAP_SHADOW_MIXING, SHADOWS_SHADOWMASK
// FOG_LINEAR, FOG_EXP, FOG_EXP2
// STEREO_INSTANCING_ON, STEREO_MULTIVIEW_ON, STEREO_CUBEMAP_RENDER_ON, UNITY_SINGLE_PASS_STEREO
// INSTANCING_ON
if (!m_CurrentHDRPAsset.renderPipelineSettings.supportMotionVectors && isMotionPass)
return true;
// When using forward only, we never need GBuffer pass (only Forward)
if (m_CurrentHDRPAsset.renderPipelineSettings.supportForwardOnly && isGBufferPass)
return true;
if (inputData.shaderKeywordSet.IsEnabled(m_Transparent))
{
// If transparent, we never need GBuffer pass.
if (isGBufferPass)
return true;
List<BaseShaderPreprocessor> materialList = HDEditorUtils.GetBaseShaderPreprocessorList();
// We will also use cluster instead of tile
if (inputData.shaderKeywordSet.IsEnabled(m_TileLighting))
return true;
}
else // Opaque
// Fill the dictionary with material to handle
foreach (BaseShaderPreprocessor material in materialList)
// If opaque, we never need transparent specific passes (even in forward only mode)
if (isTransparentForwardPass)
return true;
if (!m_CurrentHDRPAsset.renderPipelineSettings.supportForwardOnly && inputData.shaderKeywordSet.IsEnabled(m_ClusterLighting))
return true;
if (!m_CurrentHDRPAsset.renderPipelineSettings.supportForwardOnly)
{
// If opaque and not forward only, then we only need the forward debug pass.
if (isForwardPass && !inputData.shaderKeywordSet.IsEnabled(m_DebugDisplay))
return true;
}
material.AddStripperFuncs(m_StripperFuncs);
// TODO: Expose development build flag.
//if (developmentBuild && inputData.shaderKeywordSet.IsEnabled(m_DebugDisplay))
// return true;
// TODO: Tests for later
// We need to find a way to strip useless shader features for passes/shader stages that don't need them (example, vertex shaders won't ever need SSS Feature flag)
// This causes several problems:
// - Runtime code that "finds" shader variants based on feature flags might not find them anymore... thus fall backing to the "let's give a score to variant" code path that may find the wrong variant.
// - Another issue is that if a feature is declared without a "_" fall-back, if we strip the other variants, none may be left to use! This needs to be changed on our side.
//if (snippet.shaderType == ShaderType.Vertex && inputData.shaderKeywordSet.IsEnabled(m_FeatureSSS))
// return true;
return false;
public int callbackOrder { get { return 0; } }
public void OnProcessShader(Shader shader, ShaderSnippetData snippet, IList<ShaderCompilerData> inputData)

int inputShaderVariantCount = inputData.Count;
ShaderCompilerData workaround = inputData[0];
if (stripperFunc(shader, snippet, input))
if (stripperFunc(m_CurrentHDRPAsset, shader, snippet, input))
// 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.
if (inputData.Count == 0)
inputData.Add(workaround);
#endif
}

2
com.unity.render-pipelines.high-definition/HDRP/Editor/BuildProcessors/HDRPPreprocessBuild.cs.meta


fileFormatVersion: 2
guid: 2ae263b0b434c7e4d9229fde8f6096c5
guid: 0c6c205acc48bbd4c9cbf70d66fa9ffc
MonoImporter:
externalObjects: {}
serializedVersion: 2

4
com.unity.render-pipelines.high-definition/HDRP/Editor/BuildProcessors/HDRPPreprocessBuild.cs


using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
class HDRPCustomBuildProcessor : IPreprocessBuildWithReport
class HDRPPreprocessBuild : IPreprocessBuildWithReport
{
public int callbackOrder { get { return 0; } }

report.summary.platform == BuildTarget.PS4 ||
report.summary.platform == BuildTarget.Switch)
{
return ;
return;
}
string msg = "The platform " + report.summary.platform.ToString() + " is not supported with Hight Definition Render Pipeline";

8
com.unity.render-pipelines.high-definition/HDRP/Material/Builtin/BuiltinData.hlsl


shadowMask = inBuffer;
}
// TODO: CAUTION: current DecodeVelocity is not used in motion vector / TAA pass as it come from Postprocess stack
// This will be fix when postprocess will be integrated into HD, but it mean that we must not change the
// EncodeVelocity / DecodeVelocity code for now, i.e it must do nothing like it is doing currently.
// Note2: Motion blur code of posptrocess stack do * 2 - 1 to uncompress velocity which is not expected, TAA is correct.
// Design note: We assume that velocity/distortion fit into a single buffer (i.e not spread on several buffer)
void EncodeVelocity(float2 velocity, out float4 outBuffer)
{

// TODO: require a remap
// TODO: we should not gamma correct, but easier to debug for now without correct high range value
result = builtinData.bakeDiffuseLighting; needLinearToSRGB = true;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_COLOR:
// emissiveColor is premultiply by emissive intensity
result = (builtinData.emissiveColor / builtinData.emissiveIntensity); needLinearToSRGB = true;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_DEPTH_OFFSET:
result = builtinData.depthOffset.xxx * 10.0; // * 10 assuming 1 unity is 1m

18
com.unity.render-pipelines.high-definition/HDRP/Material/Builtin/BuiltinData.cs.hlsl


#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK_2 (104)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK_3 (105)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_COLOR (106)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_INTENSITY (107)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_VELOCITY (108)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_DISTORTION (109)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_DISTORTION_BLUR (110)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_DEPTH_OFFSET (111)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_VELOCITY (107)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_DISTORTION (108)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_DISTORTION_BLUR (109)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_DEPTH_OFFSET (110)
#define DEBUGVIEW_BUILTIN_LIGHTTRANSPORTDATA_DIFFUSE_COLOR (120)
#define DEBUGVIEW_BUILTIN_LIGHTTRANSPORTDATA_EMISSIVE_COLOR (121)
#define DEBUGVIEW_BUILTIN_LIGHTTRANSPORTDATA_DIFFUSE_COLOR (150)
#define DEBUGVIEW_BUILTIN_LIGHTTRANSPORTDATA_EMISSIVE_COLOR (151)
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.Builtin+BuiltinData
// PackingRules = Exact

float shadowMask2;
float shadowMask3;
float3 emissiveColor;
float emissiveIntensity;
float2 velocity;
float2 distortion;
float distortionBlur;

break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_COLOR:
result = builtindata.emissiveColor;
needLinearToSRGB = true;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_INTENSITY:
result = builtindata.emissiveIntensity.xxx;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_VELOCITY:
result = float3(builtindata.velocity, 0.0);

6
com.unity.render-pipelines.high-definition/HDRP/Material/Builtin/BuiltinData.cs


[SurfaceDataAttributes("Shadow Mask 3")]
public float shadowMask3;
[SurfaceDataAttributes("Emissive Color", false, true)]
[SurfaceDataAttributes("Emissive Color", false, false)]
[SurfaceDataAttributes("Emissive Intensity")]
public float emissiveIntensity;
// These is required for motion blur and temporalAA
[SurfaceDataAttributes("Velocity")]

// LightTransportData
// This struct is use to store information for Enlighten/Progressive light mapper. both at runtime or off line.
//-----------------------------------------------------------------------------
[GenerateHLSL(PackingRules.Exact, false, true, 120)]
[GenerateHLSL(PackingRules.Exact, false, true, 150)]
public struct LightTransportData
{
[SurfaceDataAttributes("", false, true)]

70
com.unity.render-pipelines.high-definition/HDRP/Material/GGXConvolution/RuntimeFilterIBL.cs


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

if (!m_GgxIblSampleData)
{
m_GgxIblSampleData = new RenderTexture(m_GgxIblMaxSampleCount, k_GgxIblMipCountMinusOne, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
m_GgxIblSampleData = new RenderTexture(m_GgxIblMaxSampleCount, k_GgxIblMipCountMinusOne, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
m_GgxIblSampleData.name = CoreUtils.GetRenderTargetAutoName(m_GgxIblMaxSampleCount, k_GgxIblMipCountMinusOne, RenderTextureFormat.ARGBHalf, "GGXIblSampleData");
m_GgxIblSampleData.name = CoreUtils.GetRenderTargetAutoName(m_GgxIblMaxSampleCount, k_GgxIblMipCountMinusOne, 1, RenderTextureFormat.ARGBHalf, "GGXIblSampleData");
m_GgxIblSampleData.hideFlags = HideFlags.HideAndDontSave;
m_GgxIblSampleData.Create();

m_PlanarColorMips.Clear();
}
void FilterCubemapCommon( CommandBuffer cmd,
Texture source, RenderTexture target,
Matrix4x4[] worldToViewMatrices)
void FilterCubemapCommon(CommandBuffer cmd,
Texture source, RenderTexture target,
Matrix4x4[] worldToViewMatrices)
{
int mipCount = 1 + (int)Mathf.Log(source.width, 2.0f);
if (mipCount < ((int)EnvConstants.SpecCubeLodStep + 1))

{
var lodCount = Mathf.Max(Mathf.FloorToInt(Mathf.Log(Mathf.Min(source.width, source.height), 2f)), 0);
for (var i = 0 ; i < lodCount - 0; ++i)
for (var i = 0; i < lodCount - 0; ++i)
width,
height,
target.depth,
target.format,
target.sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear
);
width,
height,
target.depth,
target.format,
target.sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear
);
var createRT = lodIsMissing
var createRT = lodIsMissing
? RenderTextureReadWrite.sRGB
: RenderTextureReadWrite.Linear
);
? RenderTextureReadWrite.sRGB
: RenderTextureReadWrite.Linear
);
if (createRT && rt)
rt.Release();

width,
height,
target.depth,
target.format,
target.sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear
);
width,
height,
target.depth,
target.format,
target.sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear
);
rt.enableRandomWrite = true;
rt.name = "Planar Convolution Tmp RT";
rt.hideFlags = HideFlags.HideAndDontSave;

target,
m_PlanarColorMips,
lodCount
);
);
public void FilterCubemapMIS( CommandBuffer cmd,
Texture source, RenderTexture target,
RenderTexture conditionalCdf, RenderTexture marginalRowCdf)
public void FilterCubemapMIS(CommandBuffer cmd,
Texture source, RenderTexture target,
RenderTexture conditionalCdf, RenderTexture marginalRowCdf)
{
// Bind the input cubemap.
m_BuildProbabilityTablesCS.SetTexture(m_ConditionalDensitiesKernel, "envMap", source);

}
int HashRenderTextureProperties(
int width,
int width,
int depth,
RenderTextureFormat format,
int depth,
RenderTextureFormat format,
return width.GetHashCode()
^ height.GetHashCode()
^ depth.GetHashCode()
^ format.GetHashCode()
^ sRGB.GetHashCode();
return width.GetHashCode()
^ height.GetHashCode()
^ depth.GetHashCode()
^ format.GetHashCode()
^ sRGB.GetHashCode();
}
}
}

18
com.unity.render-pipelines.high-definition/HDRP/Material/DiffusionProfile/DiffusionProfileSettings.cs


// Clamp to avoid artifacts.
shapeParam = new Vector3(
1f / Mathf.Max(0.001f, scatteringDistance.r),
1f / Mathf.Max(0.001f, scatteringDistance.g),
1f / Mathf.Max(0.001f, scatteringDistance.b)
);
1f / Mathf.Max(0.001f, scatteringDistance.r),
1f / Mathf.Max(0.001f, scatteringDistance.g),
1f / Mathf.Max(0.001f, scatteringDistance.b)
);
// We importance sample the color channel with the widest scattering distance.
float s = Mathf.Min(shapeParam.x, shapeParam.y, shapeParam.z);

{
// Generate 'u' on (0, 0.5] and (0.5, 1).
float u = (i <= kNumSamples / 2) ? 0.5f - i * step // The center and to the left
: i * step; // From the center to the right
: i * step; // From the center to the right
u = Mathf.Clamp(u, 0.001f, 0.999f);

// Store (1 / (2 * WeightedVariance)) per color channel.
// Warning: do not use halfRcpWeightedVariances.Set(). It will not work.
halfRcpWeightedVariances = new Vector4(0.5f / (weightedStdDev.x * weightedStdDev.x),
0.5f / (weightedStdDev.y * weightedStdDev.y),
0.5f / (weightedStdDev.z * weightedStdDev.z),
0.5f / (weightedStdDev.w * weightedStdDev.w));
0.5f / (weightedStdDev.y * weightedStdDev.y),
0.5f / (weightedStdDev.z * weightedStdDev.z),
0.5f / (weightedStdDev.w * weightedStdDev.w));
// <<< Old SSS Model
static float DisneyProfile(float r, float s)

{
return Mathf.Lerp(NormalCdfInverse(p, stdDev1), NormalCdfInverse(p, stdDev2), lerpWeight);
}
// <<< Old SSS Model
}

3
com.unity.render-pipelines.high-definition/HDRP/Material/GBufferManager.cs


public RenderTargetIdentifier[] GetBuffersRTI(bool enableShadowMask)
{
if(!enableShadowMask)
if (!enableShadowMask)
{
// nameID can change from one frame to another depending on the msaa flag so so we need to update this array to be sure it's up to date.
// Moreover, if we don't have shadow masks we only need to bind the first GBuffers

m_RTIDsNoShadowMask[i] = m_RTs[i].nameID;
}
return m_RTIDsNoShadowMask;
}
else
{

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


// Return camera relative probe volume world to object transformation
float4x4 GetProbeVolumeWorldToObject()
{
return ApplyCameraTranslationToInverseMatrix(unity_ProbeVolumeWorldToObject);
}
float3 SampleBakedGI(float3 positionWS, float3 normalWS, float2 uvStaticLightmap, float2 uvDynamicLightmap)
float3 SampleBakedGI(float3 positionRWS, float3 normalWS, float2 uvStaticLightmap, float2 uvDynamicLightmap)
{
// If there is no lightmap, it assume lightprobe
#if !defined(LIGHTMAP_ON) && !defined(DYNAMICLIGHTMAP_ON)

}
else
{
// TODO: We use GetAbsolutePositionWS(positionWS) to handle the camera relative case here but this should be part of the unity_ProbeVolumeWorldToObject matrix on C++ side (sadly we can't modify it for HDRenderPipeline...)
return SampleProbeVolumeSH4(TEXTURE3D_PARAM(unity_ProbeVolumeSH, samplerunity_ProbeVolumeSH), GetAbsolutePositionWS(positionWS), normalWS, unity_ProbeVolumeWorldToObject,
return SampleProbeVolumeSH4(TEXTURE3D_PARAM(unity_ProbeVolumeSH, samplerunity_ProbeVolumeSH), positionRWS, normalWS, GetProbeVolumeWorldToObject(),
unity_ProbeVolumeParams.y, unity_ProbeVolumeParams.z, unity_ProbeVolumeMin, unity_ProbeVolumeSizeInv);
}

#endif
}
float4 SampleShadowMask(float3 positionWS, float2 uvStaticLightmap) // normalWS not use for now
float4 SampleShadowMask(float3 positionRWS, float2 uvStaticLightmap) // normalWS not use for now
{
#if defined(LIGHTMAP_ON)
float2 uv = uvStaticLightmap * unity_LightmapST.xy + unity_LightmapST.zw;

if (unity_ProbeVolumeParams.x == 1.0)
{
// TODO: We use GetAbsolutePositionWS(positionWS) to handle the camera relative case here but this should be part of the unity_ProbeVolumeWorldToObject matrix on C++ side (sadly we can't modify it for HDRenderPipeline...)
rawOcclusionMask = SampleProbeOcclusion(TEXTURE3D_PARAM(unity_ProbeVolumeSH, samplerunity_ProbeVolumeSH), GetAbsolutePositionWS(positionWS), unity_ProbeVolumeWorldToObject,
rawOcclusionMask = SampleProbeOcclusion(TEXTURE3D_PARAM(unity_ProbeVolumeSH, samplerunity_ProbeVolumeSH), positionRWS, GetProbeVolumeWorldToObject(),
unity_ProbeVolumeParams.y, unity_ProbeVolumeParams.z, unity_ProbeVolumeMin, unity_ProbeVolumeSizeInv);
}
else

return rawOcclusionMask;
}
// Calculate velocity in Clip space [-1..1]
float2 CalculateVelocity(float4 positionCS, float4 previousPositionCS)
{
// This test on define is required to remove warning of divide by 0 when initializing empty struct

14
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/ShaderPass/DecalSharePass.hlsl


#ifndef SHADERPASS
#ifndef SHADERPASS
#if (SHADERPASS == SHADERPASS_DBUFFER_MESH)
#define ATTRIBUTES_NEED_NORMAL
#define ATTRIBUTES_NEED_TANGENT // Always present as we require it also in case of anisotropic lighting
#define ATTRIBUTES_NEED_TEXCOORD0
#define VARYINGS_NEED_POSITION_WS
#define VARYINGS_NEED_TANGENT_TO_WORLD
#define VARYINGS_NEED_TEXCOORD0
#endif
#include "../../ShaderPass/VaryingMesh.hlsl"
#include "HDRP/ShaderPass/VaryingMesh.hlsl"

208
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalUtilities.hlsl


// we need to find a way to calculate mips. For now just fetch first mip of the decals
void ApplyBlendNormal(inout float4 dst, inout int matMask, float2 texCoords, int mapMask, float3x3 decalToWorld, float blend, float lod)
{
float4 src;
src.xyz = mul(decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D_LOD(_DecalAtlas2D, _trilinear_clamp_sampler_DecalAtlas2D, texCoords, lod))) * 0.5f + 0.5f;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);
matMask |= mapMask;
float4 src;
src.xyz = mul(decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D_LOD(_DecalAtlas2D, _trilinear_clamp_sampler_DecalAtlas2D, texCoords, lod))) * 0.5f + 0.5f;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);
matMask |= mapMask;
void ApplyBlendDiffuse(inout float4 dst, inout int matMask, float2 texCoords, int mapMask, inout float blend, float lod)
void ApplyBlendDiffuse(inout float4 dst, inout int matMask, float2 texCoords, float4 src, int mapMask, inout float blend, float lod, int diffuseTextureBound)
float4 src = SAMPLE_TEXTURE2D_LOD(_DecalAtlas2D, _trilinear_clamp_sampler_DecalAtlas2D, texCoords, lod);
src.w *= blend;
blend = src.w; // diffuse texture alpha affects all other channels
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);
matMask |= mapMask;
if(diffuseTextureBound)
{
src *= SAMPLE_TEXTURE2D_LOD(_DecalAtlas2D, _trilinear_clamp_sampler_DecalAtlas2D, texCoords, lod);
}
src.w *= blend;
blend = src.w; // diffuse texture alpha affects all other channels
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);
matMask |= mapMask;
float4 src = SAMPLE_TEXTURE2D_LOD(_DecalAtlas2D, _trilinear_clamp_sampler_DecalAtlas2D, texCoords, lod);
src.z = src.w;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);
matMask |= mapMask;
float4 src = SAMPLE_TEXTURE2D_LOD(_DecalAtlas2D, _trilinear_clamp_sampler_DecalAtlas2D, texCoords, lod);
src.z = src.w;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);
matMask |= mapMask;
if(_EnableDBuffer)
{
DecalSurfaceData decalSurfaceData;
int mask = 0;
// the code in the macros, gets moved inside the conditionals by the compiler
FETCH_DBUFFER(DBuffer, _DBufferTexture, posInput.positionSS);
if(_EnableDBuffer)
{
DecalSurfaceData decalSurfaceData;
int mask = 0;
// the code in the macros, gets moved inside the conditionals by the compiler
FETCH_DBUFFER(DBuffer, _DBufferTexture, posInput.positionSS);
#ifdef _SURFACE_TYPE_TRANSPARENT // forward transparent using clustered decals
#ifdef _SURFACE_TYPE_TRANSPARENT // forward transparent using clustered decals
DBuffer0 = float4(0.0f, 0.0f, 0.0f, 1.0f);
DBuffer1 = float4(0.5f, 0.5f, 0.5f, 1.0f);
DBuffer2 = float4(0.0f, 0.0f, 0.0f, 1.0f);
DBuffer0 = float4(0.0f, 0.0f, 0.0f, 1.0f);
DBuffer1 = float4(0.5f, 0.5f, 0.5f, 1.0f);
DBuffer2 = float4(0.0f, 0.0f, 0.0f, 1.0f);
#ifdef LIGHTLOOP_TILE_PASS
GetCountAndStart(posInput, LIGHTCATEGORY_DECAL, decalStart, decalCount);

#endif
float3 positionWS = GetAbsolutePositionWS(posInput.positionWS);
float3 positionRWS = posInput.positionWS;
// get world space ddx/ddy for adjacent pixels to be used later in mipmap lod calculation
float3 positionWSDdx = ddx(positionWS);
float3 positionWSDdy = ddy(positionWS);
// get world space ddx/ddy for adjacent pixels to be used later in mipmap lod calculation
float3 positionRWSDdx = ddx(positionRWS);
float3 positionRWSDdy = ddy(positionRWS);
float3 positionDS = mul(decalData.worldToDecal, float4(positionWS, 1.0)).xyz;
positionDS = positionDS * float3(1.0, -1.0, 1.0) + float3(0.5, 0.0f, 0.5); // decal clip space
if ((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f)))
{
// clamp by half a texel to avoid sampling neighboring textures in the atlas
float2 clampAmount = float2(0.5f / _DecalAtlasResolution.x, 0.5f / _DecalAtlasResolution.y);
float2 diffuseMin = decalData.diffuseScaleBias.zw + clampAmount; // offset into atlas is in .zw
float2 diffuseMax = decalData.diffuseScaleBias.zw + decalData.diffuseScaleBias.xy - clampAmount; // scale relative to full atlas size is in .xy so total texture extent in atlas is (1,1) * scale
// Get the relative world camera to decal matrix
float4x4 worldToDecal = ApplyCameraTranslationToInverseMatrix(decalData.worldToDecal);
float2 normalMin = decalData.normalScaleBias.zw + clampAmount;
float2 normalMax = decalData.normalScaleBias.zw + decalData.normalScaleBias.xy - clampAmount;
float3 positionDS = mul(worldToDecal, float4(positionRWS, 1.0)).xyz;
positionDS = positionDS * float3(1.0, -1.0, 1.0) + float3(0.5, 0.0f, 0.5); // decal clip space
if ((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f)))
{
float2 uvScale = float2(decalData.normalToWorld[3][0], decalData.normalToWorld[3][1]);
float2 uvBias = float2(decalData.normalToWorld[3][2], decalData.normalToWorld[3][3]);
positionDS.xz = positionDS.xz * uvScale + uvBias;
positionDS.xz = frac(positionDS.xz);
float2 maskMin = decalData.maskScaleBias.zw + clampAmount;
float2 maskMax = decalData.maskScaleBias.zw + decalData.maskScaleBias.xy - clampAmount;
// clamp by half a texel to avoid sampling neighboring textures in the atlas
float2 clampAmount = float2(0.5f / _DecalAtlasResolution.x, 0.5f / _DecalAtlasResolution.y);
float2 sampleDiffuse = clamp(positionDS.xz * decalData.diffuseScaleBias.xy + decalData.diffuseScaleBias.zw, diffuseMin, diffuseMax);
float2 sampleNormal = clamp(positionDS.xz * decalData.normalScaleBias.xy + decalData.normalScaleBias.zw, normalMin, normalMax);
float2 sampleMask = clamp(positionDS.xz * decalData.maskScaleBias.xy + decalData.maskScaleBias.zw, maskMin, maskMax);
float2 diffuseMin = decalData.diffuseScaleBias.zw + clampAmount; // offset into atlas is in .zw
float2 diffuseMax = decalData.diffuseScaleBias.zw + decalData.diffuseScaleBias.xy - clampAmount; // scale relative to full atlas size is in .xy so total texture extent in atlas is (1,1) * scale
// need to compute the mipmap LOD manually because we are sampling inside a loop
float3 positionDSDdx = mul(decalData.worldToDecal, float4(positionWSDdx, 0.0)).xyz; // transform the derivatives to decal space, any translation is irrelevant
float3 positionDSDdy = mul(decalData.worldToDecal, float4(positionWSDdy, 0.0)).xyz;
float2 sampleDiffuseDdx = positionDSDdx.xz * decalData.diffuseScaleBias.xy; // factor in the atlas scale
float2 sampleDiffuseDdy = positionDSDdy.xz * decalData.diffuseScaleBias.xy;
float lodDiffuse = ComputeTextureLOD(sampleDiffuseDdx, sampleDiffuseDdy, _DecalAtlasResolution);
float2 sampleNormalDdx = positionDSDdx.xz * decalData.normalScaleBias.xy;
float2 sampleNormalDdy = positionDSDdy.xz * decalData.normalScaleBias.xy;
float lodNormal = ComputeTextureLOD(sampleNormalDdx, sampleNormalDdy, _DecalAtlasResolution);
float2 normalMin = decalData.normalScaleBias.zw + clampAmount;
float2 normalMax = decalData.normalScaleBias.zw + decalData.normalScaleBias.xy - clampAmount;
float2 sampleMaskDdx = positionDSDdx.xz * decalData.maskScaleBias.xy;
float2 sampleMaskDdy = positionDSDdy.xz * decalData.maskScaleBias.xy;
float lodMask = ComputeTextureLOD(sampleMaskDdx, sampleMaskDdy, _DecalAtlasResolution);
float2 maskMin = decalData.maskScaleBias.zw + clampAmount;
float2 maskMax = decalData.maskScaleBias.zw + decalData.maskScaleBias.xy - clampAmount;
float decalBlend = decalData.normalToWorld[0][3];
float2 sampleDiffuse = clamp(positionDS.xz * decalData.diffuseScaleBias.xy + decalData.diffuseScaleBias.zw, diffuseMin, diffuseMax);
float2 sampleNormal = clamp(positionDS.xz * decalData.normalScaleBias.xy + decalData.normalScaleBias.zw, normalMin, normalMax);
float2 sampleMask = clamp(positionDS.xz * decalData.maskScaleBias.xy + decalData.maskScaleBias.zw, maskMin, maskMax);
if((decalData.diffuseScaleBias.x > 0) && (decalData.diffuseScaleBias.y > 0))
{
ApplyBlendDiffuse(DBuffer0, mask, sampleDiffuse, DBUFFERHTILEBIT_DIFFUSE, decalBlend, lodDiffuse);
alpha = alpha < decalBlend ? decalBlend : alpha; // use decal alpha if it is higher than transparent alpha
}
// need to compute the mipmap LOD manually because we are sampling inside a loop
float3 positionDSDdx = mul(worldToDecal, float4(positionRWSDdx, 0.0)).xyz; // transform the derivatives to decal space, any translation is irrelevant
float3 positionDSDdy = mul(worldToDecal, float4(positionRWSDdy, 0.0)).xyz;
if ((decalData.normalScaleBias.x > 0) && (decalData.normalScaleBias.y > 0))
{
ApplyBlendNormal(DBuffer1, mask, sampleNormal, DBUFFERHTILEBIT_NORMAL, (float3x3)decalData.normalToWorld, decalBlend, lodNormal);
}
float2 sampleDiffuseDdx = positionDSDdx.xz * decalData.diffuseScaleBias.xy; // factor in the atlas scale
float2 sampleDiffuseDdy = positionDSDdy.xz * decalData.diffuseScaleBias.xy;
float lodDiffuse = ComputeTextureLOD(sampleDiffuseDdx, sampleDiffuseDdy, _DecalAtlasResolution);
float2 sampleNormalDdx = positionDSDdx.xz * decalData.normalScaleBias.xy;
float2 sampleNormalDdy = positionDSDdy.xz * decalData.normalScaleBias.xy;
float lodNormal = ComputeTextureLOD(sampleNormalDdx, sampleNormalDdy, _DecalAtlasResolution);
if ((decalData.maskScaleBias.x > 0) && (decalData.maskScaleBias.y > 0))
float2 sampleMaskDdx = positionDSDdx.xz * decalData.maskScaleBias.xy;
float2 sampleMaskDdy = positionDSDdy.xz * decalData.maskScaleBias.xy;
float lodMask = ComputeTextureLOD(sampleMaskDdx, sampleMaskDdy, _DecalAtlasResolution);
float decalBlend = decalData.normalToWorld[0][3];
float4 src = decalData.baseColor;
int diffuseTextureBound = (decalData.diffuseScaleBias.x > 0) && (decalData.diffuseScaleBias.y > 0);
ApplyBlendDiffuse(DBuffer0, mask, sampleDiffuse, src, DBUFFERHTILEBIT_DIFFUSE, decalBlend, lodDiffuse, diffuseTextureBound);
alpha = alpha < decalBlend ? decalBlend : alpha; // use decal alpha if it is higher than transparent alpha
float albedoContribution = decalData.normalToWorld[1][3];
if (albedoContribution == 0.0f)
ApplyBlendMask(DBuffer2, mask, sampleMask, DBUFFERHTILEBIT_MASK, decalBlend, lodMask);
mask = 0; // diffuse will not get modified
}
}
if ((decalData.normalScaleBias.x > 0) && (decalData.normalScaleBias.y > 0))
{
ApplyBlendNormal(DBuffer1, mask, sampleNormal, DBUFFERHTILEBIT_NORMAL, (float3x3)decalData.normalToWorld, decalBlend, lodNormal);
}
if ((decalData.maskScaleBias.x > 0) && (decalData.maskScaleBias.y > 0))
{
ApplyBlendMask(DBuffer2, mask, sampleMask, DBUFFERHTILEBIT_MASK, decalBlend, lodMask);
}
}
}
mask = UnpackByte(LOAD_TEXTURE2D(_DecalHTileTexture, posInput.positionSS / 8).r);
mask = UnpackByte(LOAD_TEXTURE2D(_DecalHTileTexture, posInput.positionSS / 8).r);
DECODE_FROM_DBUFFER(DBuffer, decalSurfaceData);
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
if(mask & DBUFFERHTILEBIT_DIFFUSE)
{
surfaceData.baseColor.xyz = surfaceData.baseColor.xyz * decalSurfaceData.baseColor.w + decalSurfaceData.baseColor.xyz;
}
DECODE_FROM_DBUFFER(DBuffer, decalSurfaceData);
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
if(mask & DBUFFERHTILEBIT_DIFFUSE)
{
surfaceData.baseColor.xyz = surfaceData.baseColor.xyz * decalSurfaceData.baseColor.w + decalSurfaceData.baseColor.xyz;
}
if(mask & DBUFFERHTILEBIT_NORMAL)
{
surfaceData.normalWS.xyz = normalize(surfaceData.normalWS.xyz * decalSurfaceData.normalWS.w + decalSurfaceData.normalWS.xyz);
}
if(mask & DBUFFERHTILEBIT_MASK)
{
surfaceData.metallic = surfaceData.metallic * decalSurfaceData.mask.w + decalSurfaceData.mask.x;
surfaceData.ambientOcclusion = surfaceData.ambientOcclusion * decalSurfaceData.mask.w + decalSurfaceData.mask.y;
surfaceData.perceptualSmoothness = surfaceData.perceptualSmoothness * decalSurfaceData.mask.w + decalSurfaceData.mask.z;
}
}
if(mask & DBUFFERHTILEBIT_NORMAL)
{
surfaceData.normalWS.xyz = normalize(surfaceData.normalWS.xyz * decalSurfaceData.normalWS.w + decalSurfaceData.normalWS.xyz);
}
if(mask & DBUFFERHTILEBIT_MASK)
{
surfaceData.metallic = surfaceData.metallic * decalSurfaceData.mask.w + decalSurfaceData.mask.x;
surfaceData.ambientOcclusion = surfaceData.ambientOcclusion * decalSurfaceData.mask.w + decalSurfaceData.mask.y;
surfaceData.perceptualSmoothness = surfaceData.perceptualSmoothness * decalSurfaceData.mask.w + decalSurfaceData.mask.z;
}
}

5
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalProperties.hlsl


#ifndef UNITY_DECALPROPERTIES_INCLUDED
#ifndef UNITY_DECALPROPERTIES_INCLUDED
#define UNITY_DECALPROPERTIES_INCLUDED
TEXTURE2D(_BaseColorMap);

SAMPLER(sampler_MaskMap);
float _DecalBlend;
float4 _BaseColor;
#endif
#endif

60
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalData.hlsl


//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
#include "CoreRP/ShaderLibrary/EntityLighting.hlsl"
#include "../MaterialUtilities.hlsl"
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
#elif (SHADERPASS == SHADERPASS_DBUFFER_MESH)
void GetSurfaceData(FragInputs input, out DecalSurfaceData surfaceData)
#endif
surfaceData.baseColor = float4(0,0,0,0);
surfaceData.normalWS = float4(0,0,0,0);
surfaceData.mask = float4(0,0,0,0);
surfaceData.HTileMask = 0;
float totalBlend = clamp(normalToWorld[0][3], 0.0f, 1.0f);
surfaceData.baseColor = _BaseColor;
surfaceData.normalWS = float4(0,0,0,0);
surfaceData.mask = float4(0,0,0,0);
surfaceData.HTileMask = 0;
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
float totalBlend = clamp(normalToWorld[0][3], 0.0f, 1.0f);
float2 scale = float2(normalToWorld[3][0], normalToWorld[3][1]);
float2 offset = float2(normalToWorld[3][2], normalToWorld[3][3]);
float2 texCoords = texCoordDS * scale + offset;
#elif (SHADERPASS == SHADERPASS_DBUFFER_MESH)
float totalBlend = _DecalBlend;
float2 texCoords = input.texCoord0;
#endif
surfaceData.baseColor = SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, texCoordDS.xy);
surfaceData.baseColor *= SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, texCoords);
#endif
totalBlend = surfaceData.baseColor.w; // base alpha affects all other channels;
totalBlend = surfaceData.baseColor.w; // base alpha affects all other channels;
// outside _COLORMAP because we still have base color
#if _ALBEDOCONTRIBUTION
#else
surfaceData.baseColor.w = 0; // dont blend any albedo
surfaceData.normalWS.xyz = mul((float3x3)normalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoordDS))) * 0.5f + 0.5f;
surfaceData.normalWS.w = totalBlend;
surfaceData.HTileMask |= DBUFFERHTILEBIT_NORMAL;
float3 normalTS = UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoords));
#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR)
float3 normalWS = mul((float3x3)normalToWorld, normalTS);
#elif (SHADERPASS == SHADERPASS_DBUFFER_MESH)
float3 normalWS;
GetNormalWS(input, 0, normalTS, normalWS);
surfaceData.normalWS.xyz = normalWS * 0.5f + 0.5f;
surfaceData.normalWS.w = totalBlend;
surfaceData.HTileMask |= DBUFFERHTILEBIT_NORMAL;
#endif
surfaceData.mask = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, texCoordDS.xy);
surfaceData.mask.z = surfaceData.mask.w;
surfaceData.mask.w = totalBlend;
surfaceData.HTileMask |= DBUFFERHTILEBIT_MASK;
surfaceData.mask = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, texCoords);
surfaceData.mask.z = surfaceData.mask.w;
surfaceData.mask.w = totalBlend;
surfaceData.HTileMask |= DBUFFERHTILEBIT_MASK;
#endif
}

58
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/Decal.shader


{
Properties
{
_BaseColor("_BaseColor", Color) = (1,1,1,1)
_NormalMap("NormalMap", 2D) = "bump" {} // Tangent space normal map
_MaskMap("MaskMap", 2D) = "white" {}
_DecalBlend("_DecalBlend", Range(0.0, 1.0)) = 0.5
_NormalMap("NormalMap", 2D) = "bump" {} // Tangent space normal map
_MaskMap("MaskMap", 2D) = "white" {}
_DecalBlend("_DecalBlend", Range(0.0, 1.0)) = 0.5
[ToggleUI] _AlbedoMode("_AlbedoMode", Range(0.0, 1.0)) = 1.0
}
HLSLINCLUDE

//-------------------------------------------------------------------------------------
// Variant
//-------------------------------------------------------------------------------------
#pragma shader_feature _COLORMAP
#pragma shader_feature _NORMALMAP
#pragma shader_feature _MASKMAP
#pragma shader_feature _COLORMAP
#pragma shader_feature _NORMALMAP
#pragma shader_feature _MASKMAP
#pragma shader_feature _ALBEDOCONTRIBUTION
#pragma multi_compile_instancing
#pragma multi_compile_instancing
#define UNITY_MATERIAL_DECAL
#define UNITY_MATERIAL_DECAL
//-------------------------------------------------------------------------------------
// Include

Pass
{
Name "DBuffer" // Name is not used
Tags { "LightMode" = "DBuffer" } // This will be only for opaque object based on the RenderQueue index
Name "DBufferProjector" // Name is not used
Tags { "LightMode" = "DBufferProjector" } // This will be only for opaque object based on the RenderQueue index
// back faces with zfail, for cases when camera is inside the decal volume
// back faces with zfail, for cases when camera is inside the decal volume
ZWrite Off
ZTest Greater
// using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html
Blend SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha
HLSLPROGRAM
#define SHADERPASS SHADERPASS_DBUFFER_PROJECTOR
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"
#include "DecalData.hlsl"
#include "../../ShaderPass/ShaderPassDBuffer.hlsl"
ENDHLSL
}
Pass
{
Name "DBufferMesh" // Name is not used
Tags{"LightMode" = "DBufferMesh"} // This will be only for opaque object based on the RenderQueue index
Cull Back
ZTest Greater
ZTest LEqual
#define SHADERPASS SHADERPASS_DBUFFER
#define SHADERPASS SHADERPASS_DBUFFER_MESH
#include "../../ShaderVariables.hlsl"
#include "Decal.hlsl"
#include "ShaderPass/DecalSharePass.hlsl"

ENDHLSL
}
}
ENDHLSL
}
}
CustomEditor "Experimental.Rendering.HDPipeline.DecalUI"
}

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


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

out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0
#define DECLARE_DBUFFER_TEXTURE(NAME) \
TEXTURE2D(MERGE_NAME(NAME, 0));
TEXTURE2D(MERGE_NAME(NAME, 0));
#define FETCH_DBUFFER(NAME, TEX, unCoord2) \
DBufferType0 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 0), unCoord2);

#elif DBUFFERMATERIAL_COUNT == 2
#define OUTPUT_DBUFFER(NAME) \
out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \
out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1
out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \
out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1
#define DECLARE_DBUFFER_TEXTURE(NAME) \
TEXTURE2D(MERGE_NAME(NAME, 0)); \

#elif DBUFFERMATERIAL_COUNT == 3
#define OUTPUT_DBUFFER(NAME) \
out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \
out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \
out DBufferType2 MERGE_NAME(NAME, 2) : SV_Target2
out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \
out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \
out DBufferType2 MERGE_NAME(NAME, 2) : SV_Target2
#define DECLARE_DBUFFER_TEXTURE(NAME) \
TEXTURE2D(MERGE_NAME(NAME, 0)); \

#elif DBUFFERMATERIAL_COUNT == 4
#define OUTPUT_DBUFFER(NAME) \
out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \
out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \
out DBufferType2 MERGE_NAME(NAME, 2) : SV_Target2, \
out DBufferType3 MERGE_NAME(NAME, 3) : SV_Target3
out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \
out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \
out DBufferType2 MERGE_NAME(NAME, 2) : SV_Target2, \
out DBufferType3 MERGE_NAME(NAME, 3) : SV_Target3
#define DECLARE_DBUFFER_TEXTURE(NAME) \
TEXTURE2D(MERGE_NAME(NAME, 0)); \

#endif // #ifdef DBUFFERMATERIAL_COUNT
CBUFFER_START(UnityDecalParameters)
uint _EnableDBuffer;
float2 _DecalAtlasResolution;
uint _EnableDBuffer;
float2 _DecalAtlasResolution;
UNITY_INSTANCING_BUFFER_START(Decal)
UNITY_DEFINE_INSTANCED_PROP(float4x4, _NormalToWorld)
UNITY_INSTANCING_BUFFER_END(matrix)
UNITY_INSTANCING_BUFFER_START(Decal)
UNITY_DEFINE_INSTANCED_PROP(float4x4, _NormalToWorld)
UNITY_INSTANCING_BUFFER_END(matrix)
RW_TEXTURE2D(float, _DecalHTile); // DXGI_FORMAT_R8_UINT is not supported by Unity
TEXTURE2D(_DecalHTileTexture);

TEXTURE2D_ARRAY(_DecalAtlas);
TEXTURE2D_ARRAY(_DecalAtlas);
SAMPLER(sampler_DecalAtlas);
TEXTURE2D(_DecalAtlas2D);

void EncodeIntoDBuffer( DecalSurfaceData surfaceData,
out DBufferType0 outDBuffer0,
out DBufferType1 outDBuffer1,
out DBufferType2 outDBuffer2
out DBufferType2 outDBuffer2
outDBuffer0 = surfaceData.baseColor;
outDBuffer1 = surfaceData.normalWS;
outDBuffer2 = surfaceData.mask;
outDBuffer0 = surfaceData.baseColor;
outDBuffer1 = surfaceData.normalWS;
outDBuffer2 = surfaceData.mask;
}
void DecodeFromDBuffer(

)
{
ZERO_INITIALIZE(DecalSurfaceData, surfaceData);
surfaceData.baseColor = inDBuffer0;
surfaceData.normalWS.xyz = inDBuffer1.xyz * 2.0f - 1.0f;
surfaceData.normalWS.w = inDBuffer1.w;
surfaceData.mask = inDBuffer2;
surfaceData.baseColor = inDBuffer0;
surfaceData.normalWS.xyz = inDBuffer1.xyz * 2.0f - 1.0f;
surfaceData.normalWS.w = inDBuffer1.w;
surfaceData.mask = inDBuffer2;

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


//
// UnityEngine.Experimental.Rendering.HDPipeline.Decal+DecalSurfaceData: static fields
//
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_BASE_COLOR (10000)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_NORMAL (10001)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_MASK (10002)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_HTILE_MASK (10003)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_BASE_COLOR (200)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_NORMAL (201)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_MASK (202)
#define DEBUGVIEW_DECAL_DECALSURFACEDATA_HTILE_MASK (203)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Decal+DBufferMaterial: static fields

float4 diffuseScaleBias;
float4 normalScaleBias;
float4 maskScaleBias;
float4 baseColor;
//
// 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;
}
//
// Debug functions

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


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

[GenerateHLSL(PackingRules.Exact, false, true, 10000)]
[GenerateHLSL(PackingRules.Exact, false, true, 200)]
public struct DecalSurfaceData
{
[SurfaceDataAttributes("Base Color", false, true)]

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

[GenerateHLSL(PackingRules.Exact)]
public enum DBufferHTileBit
{
{
Diffuse = 1,
Normal = 2,
Mask = 4

// DBuffer management
//-----------------------------------------------------------------------------
// should this be combined into common class shared with Lit.cs???
static public int GetMaterialDBufferCount() { return (int)DBufferMaterial.Count; }
// should this be combined into common class shared with Lit.cs???
static public int GetMaterialDBufferCount() { return (int)DBufferMaterial.Count; }
static RenderTextureFormat[] m_RTFormat = { RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32 };
static bool[] m_sRGBFlags= { true, false, false };
static RenderTextureFormat[] m_RTFormat = { RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32 };
static bool[] m_sRGBFlags = { true, false, false };
static public void GetMaterialDBufferDescription(out RenderTextureFormat[] RTFormat, out bool[] sRGBFlags)
{
static public void GetMaterialDBufferDescription(out RenderTextureFormat[] RTFormat, out bool[] sRGBFlags)
{
}
}
// normalToWorld.m03 - total blend factor
// normalToWorld.m13 - diffuse texture index in atlas
// normalToWorld.m23 - normal texture index in atlas
// normalToWorld.m33 - mask texture index in atlas
[GenerateHLSL]
// 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];
// albedo contribution on/off:
// float albedoContribution = decalData.normalToWorld[1][3];
// tiling:
// float2 uvScale = float2(decalData.normalToWorld[3][0], decalData.normalToWorld[3][1]);
// float2 uvBias = float2(decalData.normalToWorld[3][2], decalData.normalToWorld[3][3]);
[GenerateHLSL(PackingRules.Exact, false)]
public struct DecalData
{
public Matrix4x4 worldToDecal;

public Vector4 maskScaleBias;
public Vector4 baseColor;
};
}

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


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

public int vsibleDecalCount { get; set; }
public bool EnableDBUffer { get; set; }
RTHandleSystem.RTHandle m_HTile;

cmd.SetGlobalTexture(HDShaderIDs._DecalHTileTexture, m_HTile);
}
public void PushGlobalParams(CommandBuffer cmd, FrameSettings frameSettings)
public void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd)
if (frameSettings.enableDBuffer)
if (hdCamera.frameSettings.enableDBuffer)
cmd.SetGlobalInt(HDShaderIDs._EnableDBuffer, vsibleDecalCount > 0 ? 1 : 0);
cmd.SetGlobalInt(HDShaderIDs._EnableDBuffer, EnableDBUffer ? 1 : 0);
cmd.SetGlobalVector(HDShaderIDs._DecalAtlasResolution, new Vector2(HDUtils.hdrpSettings.decalSettings.atlasWidth, HDUtils.hdrpSettings.decalSettings.atlasHeight));
BindBufferAsTextures(cmd);
}

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


public void InitSSSBuffers(GBufferManager gbufferManager, RenderPipelineSettings settings)
{
// TODO: For MSAA, at least initially, we can only support Jimenez, because we can't create MSAA + UAV render targets.
if (settings.supportForwardOnly)
if (settings.supportOnlyForward)
{
// In case of full forward we must allocate the render target for forward SSS (or reuse one already existing)
// TODO: Provide a way to reuse a render target

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

RTHandles.Release(m_HTile);
}
public void PushGlobalParams(CommandBuffer cmd, DiffusionProfileSettings sssParameters, FrameSettings frameSettings)
public void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd, DiffusionProfileSettings sssParameters)
cmd.SetGlobalInt(HDShaderIDs._EnableSubsurfaceScattering, frameSettings.enableSubsurfaceScattering ? 1 : 0);
cmd.SetGlobalInt(HDShaderIDs._EnableSubsurfaceScattering, hdCamera.frameSettings.enableSubsurfaceScattering ? 1 : 0);
unsafe
{
// Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system.

cmd.SetGlobalVectorArray(HDShaderIDs._ShapeParams, sssParameters.shapeParams);
cmd.SetGlobalVectorArray(HDShaderIDs._HalfRcpVariancesAndWeights, sssParameters.halfRcpVariancesAndWeights);
// To disable transmission, we simply nullify the transmissionTint
cmd.SetGlobalVectorArray(HDShaderIDs._TransmissionTintsAndFresnel0, frameSettings.enableTransmission ? sssParameters.transmissionTintsAndFresnel0 : sssParameters.disabledTransmissionTintsAndFresnel0);
cmd.SetGlobalVectorArray(HDShaderIDs._TransmissionTintsAndFresnel0, hdCamera.frameSettings.enableTransmission ? sssParameters.transmissionTintsAndFresnel0 : sssParameters.disabledTransmissionTintsAndFresnel0);
cmd.SetGlobalVectorArray(HDShaderIDs._WorldScales, sssParameters.worldScales);
}

// Most modern GPUs support it. We can avoid performing a costly copy in this case.
// TODO: test/implement for other platforms.
return SystemInfo.graphicsDeviceType != GraphicsDeviceType.PlayStation4 &&
SystemInfo.graphicsDeviceType != GraphicsDeviceType.XboxOne &&
SystemInfo.graphicsDeviceType != GraphicsDeviceType.XboxOneD3D12;
SystemInfo.graphicsDeviceType != GraphicsDeviceType.XboxOne &&
SystemInfo.graphicsDeviceType != GraphicsDeviceType.XboxOneD3D12;
public void SubsurfaceScatteringPass(HDCamera hdCamera, CommandBuffer cmd, DiffusionProfileSettings sssParameters, FrameSettings frameSettings,
RTHandleSystem.RTHandle colorBufferRT, RTHandleSystem.RTHandle diffuseBufferRT, RTHandleSystem.RTHandle depthStencilBufferRT, RTHandleSystem.RTHandle depthTextureRT)
public void SubsurfaceScatteringPass(HDCamera hdCamera, CommandBuffer cmd, DiffusionProfileSettings sssParameters,
RTHandleSystem.RTHandle colorBufferRT, RTHandleSystem.RTHandle diffuseBufferRT, RTHandleSystem.RTHandle depthStencilBufferRT, RTHandleSystem.RTHandle depthTextureRT)
if (sssParameters == null || !frameSettings.enableSubsurfaceScattering)
if (sssParameters == null || !hdCamera.frameSettings.enableSubsurfaceScattering)
return;
// TODO: For MSAA, at least initially, we can only support Jimenez, because we can't

HDUtils.SetRenderTarget(cmd, hdCamera, m_HTile, ClearFlag.Color, CoreUtils.clearColorAllBlack);
HDUtils.SetRenderTarget(cmd, hdCamera, depthStencilBufferRT); // No need for color buffer here
cmd.SetRandomWriteTarget(1, m_HTile);
cmd.SetRandomWriteTarget(1, m_HTile); // This need to be done AFTER SetRenderTarget
// Generate HTile for the split lighting stencil usage. Don't write into stencil texture (shaderPassId = 2)
// Use ShaderPassID 1 => "Pass 2 - Export HTILE for stencilRef to output"
CoreUtils.DrawFullScreen(cmd, m_CopyStencilForSplitLighting, null, 2);

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


// Reconstruct the view-space position.
float2 centerPosSS = posInput.positionNDC;
float2 cornerPosSS = centerPosSS + 0.5 * _ScreenSize.zw;
float centerDepth = LOAD_TEXTURE2D(_MainDepthTexture, centerPosition).r;
float centerDepth = LOAD_TEXTURE2D(_CameraDepthTexture, centerPosition).r;
float3 centerPosVS = ComputeViewSpacePosition(centerPosSS, centerDepth, UNITY_MATRIX_I_P);
float3 cornerPosVS = ComputeViewSpacePosition(cornerPosSS, centerDepth, UNITY_MATRIX_I_P);

// Apply bilateral weighting.
// Ref #1: Skin Rendering by Pseudo–Separable Cross Bilateral Filtering.
// Ref #2: Separable SSS, Supplementary Materials, Section E.
float rawDepth = LOAD_TEXTURE2D(_MainDepthTexture, samplePosition).r;
float rawDepth = LOAD_TEXTURE2D(_CameraDepthTexture, samplePosition).r;
float sampleDepth = LinearEyeDepth(rawDepth, _ZBufferParams);
float zDistance = centimPerUnit * sampleDepth - (centimPerUnit * centerPosVS.z);
sampleWeight *= exp(-zDistance * zDistance * halfRcpVariance);

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


#include "../DiffusionProfile/DiffusionProfileSettings.cs.hlsl"
#include "../DiffusionProfile/DiffusionProfile.hlsl"
// Subsurface scattering constant
#define SSS_WRAP_ANGLE (PI/12) // 15 degrees
#define SSS_WRAP_LIGHT cos(PI/2 - SSS_WRAP_ANGLE)
// ----------------------------------------------------------------------------
// constant buffer declaration
// ----------------------------------------------------------------------------
CBUFFER_START(UnitySSSAndTransmissionParameters)
// Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system.

uint diffusionProfile;
};
#define SSSBufferType0 float4
#define SSSBufferType0 float4 // Must match GBufferType0 in deferred
// SSSBuffer texture declaration
TEXTURE2D(_SSSBufferTexture0);

}
// OUTPUT_SSSBUFFER start from SV_Target2 as SV_Target0 and SV_Target1 are used for lighting buffer
#define OUTPUT_SSSBUFFER(NAME) out GBufferType0 MERGE_NAME(NAME, 0) : SV_Target2
#define OUTPUT_SSSBUFFER(NAME) out SSSBufferType0 MERGE_NAME(NAME, 0) : SV_Target2
#define ENCODE_INTO_SSSBUFFER(SURFACE_DATA, UNPOSITIONSS, NAME) EncodeIntoSSSBuffer(ConvertSurfaceDataToSSSData(SURFACE_DATA), UNPOSITIONSS, MERGE_NAME(NAME, 0))
#define DECODE_FROM_SSSBUFFER(UNPOSITIONSS, SSS_DATA) DecodeFromSSSBuffer(UNPOSITIONSS, SSS_DATA)

return subsurfaceLighting.b > 0;
}
// ----------------------------------------------------------------------------
// Helper functions to use SSS/Transmission with a material
// ----------------------------------------------------------------------------
// Following function allow to easily setup SSS and transmission inside a material.
// User can request either SSS functions, or Transmission functions, or both, by defining MATERIAL_INCLUDE_SUBSURFACESCATTERING and/or MATERIAL_INCLUDE_TRANSMISSION
// before including this file.
// + It require that the material follow naming convention for properties inside BSDFData
// struct BSDFData
// {
// (...)
// // Share for SSS and Transmission
// uint materialFeatures;
// uint diffusionProfile;
// // For SSS
// float3 diffuseColor;
// float3 fresnel0;
// float subsurfaceMask;
// // For transmission
// float thickness;
// bool useThickObjectMode;
// float3 transmittance;
// perceptualRoughness; // Only if user chose to support DisneyDiffuse
// (...)
// }
// Note: Transmission functions for light evaluation are included in LightEvaluation.hlsl file also based on the MATERIAL_INCLUDE_TRANSMISSION
// For LightEvaluation.hlsl file it is required to define a BRDF for the transmission. Defining USE_DIFFUSE_LAMBERT_BRDF use Lambert, otherwise it use Disneydiffuse
#define MATERIAL_FEATURE_SSS_TRANSMISSION_START (1 << 16) // It should be safe to start these flags
#define MATERIAL_FEATURE_FLAGS_SSS_OUTPUT_SPLIT_LIGHTING ((MATERIAL_FEATURE_SSS_TRANSMISSION_START) << 0)
#define MATERIAL_FEATURE_FLAGS_SSS_TEXTURING_MODE_OFFSET FastLog2((MATERIAL_FEATURE_SSS_TRANSMISSION_START) << 1) // Note: The texture mode is 2bit, thus go from '<< 1' to '<< 3'
#define MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_MIXED_THICKNESS ((MATERIAL_FEATURE_SSS_TRANSMISSION_START) << 3)
// Flags used as a shortcut to know if we have thin mode transmission
#define MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_THIN_THICKNESS ((MATERIAL_FEATURE_SSS_TRANSMISSION_START) << 4)
#ifdef MATERIAL_INCLUDE_SUBSURFACESCATTERING
void FillMaterialSSS(uint diffusionProfile, float subsurfaceMask, inout BSDFData bsdfData)
{
bsdfData.diffusionProfile = diffusionProfile;
bsdfData.fresnel0 = _TransmissionTintsAndFresnel0[diffusionProfile].a;
bsdfData.subsurfaceMask = subsurfaceMask;
bsdfData.materialFeatures |= MATERIAL_FEATURE_FLAGS_SSS_OUTPUT_SPLIT_LIGHTING;
bsdfData.materialFeatures |= GetSubsurfaceScatteringTexturingMode(diffusionProfile) << MATERIAL_FEATURE_FLAGS_SSS_TEXTURING_MODE_OFFSET;
}
bool ShouldOutputSplitLighting(BSDFData bsdfData)
{
return HasFlag(bsdfData.materialFeatures, MATERIAL_FEATURE_FLAGS_SSS_OUTPUT_SPLIT_LIGHTING);
}
float3 GetModifiedDiffuseColorForSSS(BSDFData bsdfData)
{
// Subsurface scattering mode
uint texturingMode = (bsdfData.materialFeatures >> MATERIAL_FEATURE_FLAGS_SSS_TEXTURING_MODE_OFFSET) & 3;
return ApplySubsurfaceScatteringTexturingMode(texturingMode, bsdfData.diffuseColor);
}
#endif
#ifdef MATERIAL_INCLUDE_TRANSMISSION
// Assume that bsdfData.diffusionProfile is init
void FillMaterialTransmission(uint diffusionProfile, float thickness, inout BSDFData bsdfData)
{
bsdfData.diffusionProfile = diffusionProfile;
bsdfData.fresnel0 = _TransmissionTintsAndFresnel0[diffusionProfile].a;
bsdfData.thickness = _ThicknessRemaps[diffusionProfile].x + _ThicknessRemaps[diffusionProfile].y * thickness;
// The difference between the thin and the regular (a.k.a. auto-thickness) modes is the following:
// * in the thin object mode, we assume that the geometry is thin enough for us to safely share
// the shadowing information between the front and the back faces;
// * the thin mode uses baked (textured) thickness for all transmission calculations;
// * the thin mode uses wrapped diffuse lighting for the NdotL;
// * the auto-thickness mode uses the baked (textured) thickness to compute transmission from
// indirect lighting and non-shadow-casting lights; for shadowed lights, it calculates
// the thickness using the distance to the closest occluder sampled from the shadow map.
// If the distance is large, it may indicate that the closest occluder is not the back face of
// the current object. That's not a problem, since large thickness will result in low intensity.
bool useThinObjectMode = IsBitSet(asuint(_TransmissionFlags), diffusionProfile);
bsdfData.materialFeatures |= useThinObjectMode ? MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_THIN_THICKNESS : MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_MIXED_THICKNESS;
// Compute transmittance using baked thickness here. It may be overridden for direct lighting
// in the auto-thickness mode (but is always used for indirect lighting).
#if SHADEROPTIONS_USE_DISNEY_SSS
bsdfData.transmittance = ComputeTransmittanceDisney(_ShapeParams[diffusionProfile].rgb,
_TransmissionTintsAndFresnel0[diffusionProfile].rgb,
bsdfData.thickness);
#else
bsdfData.transmittance = ComputeTransmittanceJimenez( _HalfRcpVariancesAndWeights[diffusionProfile][0].rgb,
_HalfRcpVariancesAndWeights[diffusionProfile][0].a,
_HalfRcpVariancesAndWeights[diffusionProfile][1].rgb,
_HalfRcpVariancesAndWeights[diffusionProfile][1].a,
_TransmissionTintsAndFresnel0[diffusionProfile].rgb,
bsdfData.thickness);
#endif
}
#endif

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

正在加载...
取消
保存