浏览代码

Merge branch 'Add-Per-Pixel-scale' of https://github.com/Unity-Technologies/ScriptableRenderLoop

/stochastic_alpha_test
Evgenii Golubev 7 年前
当前提交
ea93b8f4
共有 108 个文件被更改,包括 1714 次插入1310 次删除
  1. 2
      ScriptableRenderPipeline/Core/Camera/CameraSwitcher.cs
  2. 1
      ScriptableRenderPipeline/Core/Camera/FreeCamera.cs
  3. 19
      ScriptableRenderPipeline/Core/CommandBufferPool.cs
  4. 37
      ScriptableRenderPipeline/Core/CoreUtils.cs
  5. 3
      ScriptableRenderPipeline/Core/Debugging/DebugActionManager.cs
  6. 3
      ScriptableRenderPipeline/Core/Debugging/DebugItemHandler.cs
  7. 4
      ScriptableRenderPipeline/Core/Debugging/DebugItemUI.cs
  8. 1
      ScriptableRenderPipeline/Core/Debugging/DebugMenuManager.cs
  9. 3
      ScriptableRenderPipeline/Core/Debugging/DebugMenuState.cs
  10. 3
      ScriptableRenderPipeline/Core/Debugging/DebugMenuUI.cs
  11. 4
      ScriptableRenderPipeline/Core/Debugging/DebugMenuUpdater.cs
  12. 3
      ScriptableRenderPipeline/Core/Debugging/DebugPanel.cs
  13. 3
      ScriptableRenderPipeline/Core/Debugging/DebugPanelUI.cs
  14. 1
      ScriptableRenderPipeline/Core/Debugging/Debugging.cs
  15. 4
      ScriptableRenderPipeline/Core/Debugging/Editor/DebugMenuEditor.cs
  16. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateBool.cs
  17. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateColor.cs
  18. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateFloat.cs
  19. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateInt.cs
  20. 4
      ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateUInt.cs
  21. 3
      ScriptableRenderPipeline/Core/Inputs/InputRegistering.cs
  22. 2
      ScriptableRenderPipeline/Core/Singleton.cs
  23. 73
      ScriptableRenderPipeline/Core/TextureCache.cs
  24. 66
      ScriptableRenderPipeline/HDRenderPipeline/Camera/HDCamera.cs
  25. 3
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs
  26. 4
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayLatlong.shader
  27. 4
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugFullScreen.shader
  28. 4
      ScriptableRenderPipeline/HDRenderPipeline/Debug/LightingDebugPanel.cs
  29. 1
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineInspector.cs
  30. 85
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs
  31. 326
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
  32. 34
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.cs
  33. 367
      ScriptableRenderPipeline/HDRenderPipeline/HDStringConstants.cs
  34. 59
      ScriptableRenderPipeline/HDRenderPipeline/HDUtils.cs
  35. 3
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Editor/HDLightEditor.Styles.cs
  36. 15
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Editor/HDLightEditor.cs
  37. 130
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/EditorLightUtilities.cs
  38. 2
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs
  39. 6
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Volumetrics/HomogeneousFog.cs
  40. 4
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Volumetrics/VolumetricLighting.cs
  41. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs
  42. 3
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/Editor/LayeredLitUI.cs
  43. 5
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs
  44. 18
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/LitUI.cs
  45. 8
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl
  46. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitData.hlsl
  47. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.DisneyDiffuse.cs
  48. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.GGX.cs
  49. 259
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringProfile.cs
  50. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/BaseUnlitUI.cs
  51. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/UnlitUI.cs
  52. 1
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.cs
  53. 2
      ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/HDRenderPipelineResources.asset
  54. 2
      ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/HDRenderPipelineResources.asset.meta
  55. 73
      ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/RenderPipelineResources.cs
  56. 4
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Editor/CommonSettingsEditor.cs
  57. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawSssProfile.shader
  58. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader
  59. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/SceneSettings.cs
  60. 1
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/SceneSettingsManager.cs
  61. 1
      ScriptableRenderPipeline/HDRenderPipeline/ShaderConfig.cs
  62. 1
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPass.cs
  63. 6
      ScriptableRenderPipeline/HDRenderPipeline/Sky/GGXConvolve.shader
  64. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Editor/HDRISkyEditor.cs
  65. 11
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/HDRISkyRenderer.cs
  66. 16
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/HDRISkySettings.cs
  67. 4
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Resources/SkyHDRI.shader
  68. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/Editor/ProceduralSkyEditor.cs
  69. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkyRenderer.cs
  70. 41
      ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkySettings.cs
  71. 50
      ScriptableRenderPipeline/HDRenderPipeline/Sky/RuntimeFilterIBL.cs
  72. 178
      ScriptableRenderPipeline/HDRenderPipeline/Sky/SkyManager.cs
  73. 5
      ScriptableRenderPipeline/HDRenderPipeline/Sky/SkyRenderer.cs
  74. 35
      ScriptableRenderPipeline/HDRenderPipeline/Sky/SkySettings.cs
  75. 6
      ScriptableRenderPipeline/HDRenderPipeline/Sky/SkySettingsSingleton.cs
  76. 2
      ScriptableRenderPipeline/HDRenderPipeline/Wind/ShaderWindSettings.cs
  77. 2
      ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardGUI.cs
  78. 1
      ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightUnlitGUI.cs
  79. 1
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipeline.cs
  80. 4
      TestbedPipelines/Fptl/FptlLighting.cs
  81. 2
      TestbedPipelines/Fptl/SkyboxHelper.cs
  82. 2
      TestbedPipelines/OnTileDeferredPipeline/OnTileDeferredRenderPipeline.cs
  83. 2
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/HDRPAsset/HDRenderPipelineResourcesTest.asset
  84. 87
      ScriptableRenderPipeline/Core/Editor/CoreEditorUtils.cs
  85. 13
      ScriptableRenderPipeline/Core/Editor/CoreEditorUtils.cs.meta
  86. 10
      ScriptableRenderPipeline/Core/Resources/Editor.meta
  87. 23
      ScriptableRenderPipeline/Core/Resources/GPUCopy.compute
  88. 10
      ScriptableRenderPipeline/Core/Resources/GPUCopy.compute.meta
  89. 33
      ScriptableRenderPipeline/Core/Resources/GPUCopy.cs
  90. 13
      ScriptableRenderPipeline/Core/Resources/GPUCopy.cs.meta
  91. 164
      ScriptableRenderPipeline/Core/Resources/GPUCopyAsset.cs
  92. 13
      ScriptableRenderPipeline/Core/Resources/GPUCopyAsset.cs.meta
  93. 17
      ScriptableRenderPipeline/Core/Resources/GPUCopyDefinition.asset
  94. 10
      ScriptableRenderPipeline/Core/Resources/GPUCopyDefinition.asset.meta
  95. 88
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDAssetFactory.cs
  96. 13
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDAssetFactory.cs.meta
  97. 36
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDEditorUtils.cs
  98. 13
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDEditorUtils.cs.meta
  99. 413
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs.orig

2
ScriptableRenderPipeline/Core/Camera/CameraSwitcher.cs


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

1
ScriptableRenderPipeline/Core/Camera/FreeCamera.cs


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

19
ScriptableRenderPipeline/Core/CommandBufferPool.cs


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

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

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

37
ScriptableRenderPipeline/Core/CoreUtils.cs


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

public static class CoreUtils
{
public static List<RenderPipelineMaterial> GetRenderPipelineMaterialList()
{
var baseType = typeof(RenderPipelineMaterial);
var assembly = baseType.Assembly;
var types = assembly.GetTypes()
.Where(t => t.IsSubclassOf(baseType))
.Select(Activator.CreateInstance)
.Cast<RenderPipelineMaterial>()
.ToList();
// Note: If there is a need for an optimization in the future of this function, user can
// simply fill the materialList manually by commenting the code abode and returning a
// custom list of materials they use in their game.
//
// return new List<RenderPipelineMaterial>
// {
// new Lit(),
// new Unlit(),
// ...
// };
return types;
}
// Render Target Management.
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier buffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)
{

UnityObject.Destroy(obj);
#endif
}
}
public static void Destroy(params UnityObject[] objs)
{
if (objs == null)
return;
foreach (var o in objs)
Destroy(o);
}
public static void SafeRelease(ComputeBuffer buffer)

3
ScriptableRenderPipeline/Core/Debugging/DebugActionManager.cs


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

3
ScriptableRenderPipeline/Core/Debugging/DebugItemHandler.cs


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

4
ScriptableRenderPipeline/Core/Debugging/DebugItemUI.cs


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

1
ScriptableRenderPipeline/Core/Debugging/DebugMenuManager.cs


using System;
using System.Linq;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

3
ScriptableRenderPipeline/Core/Debugging/DebugMenuState.cs


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

3
ScriptableRenderPipeline/Core/Debugging/DebugMenuUI.cs


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

4
ScriptableRenderPipeline/Core/Debugging/DebugMenuUpdater.cs


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

3
ScriptableRenderPipeline/Core/Debugging/DebugPanel.cs


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

3
ScriptableRenderPipeline/Core/Debugging/DebugPanelUI.cs


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

1
ScriptableRenderPipeline/Core/Debugging/Debugging.cs


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

4
ScriptableRenderPipeline/Core/Debugging/Editor/DebugMenuEditor.cs


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

4
ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateBool.cs


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

4
ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateColor.cs


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

4
ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateFloat.cs


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

4
ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateInt.cs


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

4
ScriptableRenderPipeline/Core/Debugging/Serialization/DebugItemStateUInt.cs


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

3
ScriptableRenderPipeline/Core/Inputs/InputRegistering.cs


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

2
ScriptableRenderPipeline/Core/Singleton.cs


using UnityEngine.SceneManagement;
namespace UnityEngine.Experimental.Rendering
{
[ExecuteInEditMode]

73
ScriptableRenderPipeline/Core/TextureCache.cs


{
protected int m_NumMipLevels;
#if UNITY_EDITOR
static int s_TextureCacheIdGenerator = 0;
int m_TextureCacheId = 0;
static bool s_ForceReinjectGlobalFirst = false;
static bool s_ForceReinjectGlobalSecond = false;
static int s_GlobalSecondSetByTexCacheID = -1;
// here we receive the in-editor updated textures. These must be reinjected into
// any texture cache which has a stale copy of it. However, we don't have a this-pointer to the texture cache
// so instead we defer this to NewFrame() where we force reinject.
// Ideally we'd build up a list here of textures which are to be reinjected but unfortunately the texture we receive
// is an intermediate one and not the final compressed one. So instead we will have to reinject all in NewFrame().
internal class AssetReloader : UnityEditor.AssetPostprocessor
{
void OnPostprocessTexture(Texture texture)
{
s_ForceReinjectGlobalFirst = true;
s_ForceReinjectGlobalSecond = false;
s_GlobalSecondSetByTexCacheID = -1;
}
}
#endif
public static bool isMobileBuildTarget
{
get

{
public uint texId;
public uint countLRU;
#if UNITY_EDITOR
#endif
};
private int m_NumTextures;

return sliceIndex;
var texId = (uint)texture.GetInstanceID();
#if UNITY_EDITOR
#endif
//assert(TexID!=g_InvalidTexID);
if (texId == g_InvalidTexID) return 0;

Debug.Assert(m_SliceArray[sliceIndex].texId == texId);
bFoundAvailOrExistingSlice = true;
#if UNITY_EDITOR
#endif
}
// If no existing copy found in the array

if (bFoundAvailOrExistingSlice)
{
m_SliceArray[sliceIndex].countLRU = 0; // mark slice as in use this frame
m_SliceArray[sliceIndex].hash = hash;
#if UNITY_EDITOR
m_SliceArray[sliceIndex].hash = hash;
#endif
// transfer new slice to sliceIndex from source texture
TransferToSlice(sliceIndex, texture);
}

//for(int q=1; q<m_numTextures; q++)
// assert(m_SliceArray[m_SortedIdxArray[q-1]].CountLRU>=m_SliceArray[m_SortedIdxArray[q]].CountLRU);
#if UNITY_EDITOR
// one or more textures got updated in editor. Unfortunately we do not know exactly which since
// OnPostprocessTexture() receives intermediate uncompressed textures. So we will have to reinject all slices to force an update.
if(s_ForceReinjectGlobalSecond && s_GlobalSecondSetByTexCacheID==m_TextureCacheId)
{
s_ForceReinjectGlobalSecond = false;
s_GlobalSecondSetByTexCacheID = -1;
}
if(s_ForceReinjectGlobalFirst)
{
s_ForceReinjectGlobalSecond = true;
s_GlobalSecondSetByTexCacheID = m_TextureCacheId;
s_ForceReinjectGlobalFirst = false;
}
if(s_ForceReinjectGlobalSecond)
{
// all texture caches must loop through and force a reinject on all entries when this is true.
for(int i = 0; i < m_NumTextures; i++)
{
var texID = m_SliceArray[i].texId;
if(texID!=g_InvalidTexID)
{
Texture texture = (Texture) EditorUtility.InstanceIDToObject((int) texID);
if(texture!=null) TransferToSlice(i, texture);
}
}
}
#endif
}
protected TextureCache()

#if UNITY_EDITOR
m_TextureCacheId = s_TextureCacheIdGenerator; // assign an ID so we can tell the caches apart
++s_TextureCacheIdGenerator; // static/global
#endif
}
public virtual void TransferToSlice(int sliceIndex, Texture texture)

66
ScriptableRenderPipeline/HDRenderPipeline/Camera/HDCamera.cs


public Matrix4x4 projMatrix;
public Matrix4x4 nonJitteredProjMatrix;
public Vector4 screenSize;
public Plane[] frustumPlanes;
public Vector4[] frustumPlaneEquations;
public Camera camera;

get { return nonJitteredProjMatrix * viewMatrix; }
}
public bool isFirstFrame
{
get { return m_FirstFrame; }
}
// Always true for cameras that just got added to the pool - needed for previous matrices to
// avoid one-frame jumps/hiccups with temporal effects (motion blur, TAA...)
public bool isFirstFrame { get; private set; }
get { var p = projMatrix; return new Vector4(p.m20 / (p.m00 * p.m23), p.m21 / (p.m11 * p.m23), -1.0f / p.m23, (-p.m22 + p.m20 * p.m02 / p.m00 + p.m21 * p.m12 / p.m11) / p.m23); }
get
{
var p = projMatrix;
return new Vector4(
p.m20 / (p.m00 * p.m23),
p.m21 / (p.m11 * p.m23),
-1f / p.m23,
(-p.m22 + p.m20 * p.m02 / p.m00 + p.m21 * p.m12 / p.m11) / p.m23
);
}
}
// View-projection matrix from the previous frame.

// happen, but you never know...
int m_LastFrameActive;
// Always true for cameras that just got added to the pool - needed for previous matrices to
// avoid one-frame jumps/hiccups with temporal effects (motion blur, TAA...)
bool m_FirstFrame;
static Dictionary<Camera, HDCamera> s_Cameras = new Dictionary<Camera, HDCamera>();
static List<Camera> s_Cleanup = new List<Camera>(); // Recycled to reduce GC pressure
frustumPlanes = new Plane[6];
frustumPlaneEquations = new Vector4[6];
Reset();
}

bool taaEnabled = camera.cameraType == CameraType.Game
&& CoreUtils.IsTemporalAntialiasingActive(postProcessLayer);
Matrix4x4 nonJitteredCameraProj = camera.projectionMatrix;
Matrix4x4 cameraProj = taaEnabled
var nonJitteredCameraProj = camera.projectionMatrix;
var cameraProj = taaEnabled
Matrix4x4 gpuProj = GL.GetGPUProjectionMatrix(cameraProj, true); // Had to change this from 'false'
Matrix4x4 gpuView = camera.worldToCameraMatrix;
Matrix4x4 gpuNonJitteredProj = GL.GetGPUProjectionMatrix(nonJitteredCameraProj, true);
var gpuProj = GL.GetGPUProjectionMatrix(cameraProj, true); // Had to change this from 'false'
var gpuView = camera.worldToCameraMatrix;
var gpuNonJitteredProj = GL.GetGPUProjectionMatrix(nonJitteredCameraProj, true);
Vector3 pos = camera.transform.position;
var pos = camera.transform.position;
if (ShaderConfig.s_CameraRelativeRendering != 0)
{

Matrix4x4 gpuVP = gpuNonJitteredProj * gpuView;
var gpuVP = gpuNonJitteredProj * gpuView;
if (m_FirstFrame)
if (isFirstFrame)
{
prevCameraPos = pos;
prevViewProjMatrix = gpuVP;

prevViewProjMatrix = nonJitteredViewProjMatrix;
}
m_FirstFrame = false;
isFirstFrame = false;
}
viewMatrix = gpuView;

screenSize = new Vector4(camera.pixelWidth, camera.pixelHeight, 1.0f / camera.pixelWidth, 1.0f / camera.pixelHeight);
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(viewProjMatrix);
GeometryUtility.CalculateFrustumPlanes(viewProjMatrix, frustumPlanes);
frustumPlaneEquations[i] = new Vector4(planes[i].normal.x, planes[i].normal.y, planes[i].normal.z, planes[i].distance);
frustumPlaneEquations[i] = new Vector4(frustumPlanes[i].normal.x, frustumPlanes[i].normal.y, frustumPlanes[i].normal.z, frustumPlanes[i].distance);
}
m_LastFrameActive = Time.frameCount;

{
m_LastFrameActive = -1;
m_FirstFrame = true;
isFirstFrame = true;
static Dictionary<Camera, HDCamera> m_Cameras = new Dictionary<Camera, HDCamera>();
static List<Camera> m_Cleanup = new List<Camera>(); // Recycled to reduce GC pressure
if (!m_Cameras.TryGetValue(camera, out hdcam))
if (!s_Cameras.TryGetValue(camera, out hdcam))
m_Cameras.Add(camera, hdcam);
s_Cameras.Add(camera, hdcam);
}
hdcam.Update(postProcessLayer);

{
int frameCheck = Time.frameCount - 1;
foreach (var kvp in m_Cameras)
foreach (var kvp in s_Cameras)
m_Cleanup.Add(kvp.Key);
s_Cleanup.Add(kvp.Key);
foreach (var cam in m_Cleanup)
m_Cameras.Remove(cam);
foreach (var cam in s_Cleanup)
s_Cameras.Remove(cam);
m_Cleanup.Clear();
s_Cleanup.Clear();
}
public void SetupGlobalParams(CommandBuffer cmd)

3
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs


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

{
if (!isDebugViewMaterialInit)
{
List<RenderPipelineMaterial> materialList = CoreUtils.GetRenderPipelineMaterialList();
List<RenderPipelineMaterial> materialList = HDUtils.GetRenderPipelineMaterialList();
// TODO: Share this code to retrieve deferred material with HDRenderPipeline
// Find first material that have non 0 Gbuffer count and assign it as deferredMaterial

4
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayLatlong.shader


Pass
{
ZWrite Off
ZTest Off
Blend One Zero
ZTest Always
Blend Off
Cull Off
HLSLPROGRAM

4
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugFullScreen.shader


Pass
{
ZWrite Off
ZTest Off
Blend One Zero
ZTest Always
Blend Off
Cull Off
HLSLPROGRAM

4
ScriptableRenderPipeline/HDRenderPipeline/Debug/LightingDebugPanel.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine;
using System;
#if UNITY_EDITOR

1
ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineInspector.cs


using System;
using System.Reflection;
using System.Linq.Expressions;
using UnityEditor;
using UnityEditor.Experimental.Rendering;

85
ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs


using UnityEngine;
using UnityEditor;
using UnityEngine.SceneManagement;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityObject = UnityEngine.Object;
[UnityEditor.MenuItem("HDRenderPipeline/Add \"Additional Light-shadow Data\" (if not present)")]
[MenuItem("HDRenderPipeline/Add \"Additional Light-shadow Data\" (if not present)")]
Light[] lights = GameObject.FindObjectsOfType(typeof(Light)) as Light[];
var lights = UnityObject.FindObjectsOfType(typeof(Light)) as Light[];
foreach (Light light in lights)
foreach (var light in lights)
{
}
{
}
[UnityEditor.MenuItem("HDRenderPipeline/Add \"Additional Camera Data\" (if not present)")]
[MenuItem("HDRenderPipeline/Add \"Additional Camera Data\" (if not present)")]
Camera[] cameras = GameObject.FindObjectsOfType(typeof(Camera)) as Camera[];
var cameras = UnityObject.FindObjectsOfType(typeof(Camera)) as Camera[];
foreach (Camera camera in cameras)
foreach (var camera in cameras)
{
}
}
}

{
Object[] materials = Resources.FindObjectsOfTypeAll<Material>();
foreach (Object obj in materials)
var materials = Resources.FindObjectsOfTypeAll<Material>();
foreach (var mat in materials)
Material mat = obj as Material;
if (mat.shader.name == "HDRenderPipeline/LayeredLit" || mat.shader.name == "HDRenderPipeline/LayeredLitTessellation")
{
LayeredLitGUI.SynchronizeAllLayers(mat);

static void RemoveMaterialKeywords(Material material)
{
string[] keywordsToRemove = material.shaderKeywords;
foreach (var keyword in keywordsToRemove)
{
foreach (var keyword in material.shaderKeywords)
}
}
// The goal of this script is to help maintenance of data that have already been produced but need to update to the latest shader code change.

{
try
{
Object[] materials = Resources.FindObjectsOfTypeAll<Material>();
var materials = Resources.FindObjectsOfTypeAll<Material>();
Material mat = materials[i] as Material;
var mat = materials[i];
EditorUtility.DisplayProgressBar(
"Setup materials Keywords...",

[MenuItem("HDRenderPipeline/Test/Remove tessellation materials (not reversible)")]
static void RemoveTessellationMaterials()
{
Object[] materials = Resources.FindObjectsOfTypeAll<Material>();
var materials = Resources.FindObjectsOfTypeAll<Material>();
Shader litShader = Shader.Find("HDRenderPipeline/Lit");
Shader layeredLitShader = Shader.Find("HDRenderPipeline/LayeredLit");
var litShader = Shader.Find("HDRenderPipeline/Lit");
var layeredLitShader = Shader.Find("HDRenderPipeline/LayeredLit");
foreach (Object obj in materials)
foreach (var mat in materials)
Material mat = obj as Material;
if (mat.shader.name == "HDRenderPipeline/LitTessellation")
{
mat.shader = litShader;

[MenuItem("HDRenderPipeline/Export Sky to Image")]
static void ExportSkyToImage()
{
HDRenderPipeline renderpipeline = UnityEngine.Experimental.Rendering.RenderPipelineManager.currentPipeline as HDRenderPipeline;
if(renderpipeline == null)
var renderpipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
if (renderpipeline == null)
Texture2D result = renderpipeline.ExportSkyToTexture();
if(result == null)
{
var result = renderpipeline.ExportSkyToTexture();
if (result == null)
}
byte[] bytes = null;
bytes = result.EncodeToEXR(Texture2D.EXRFlags.CompressZIP);
Object.DestroyImmediate(result);
byte[] bytes = result.EncodeToEXR(Texture2D.EXRFlags.CompressZIP);
UnityObject.DestroyImmediate(result);
string assetPath = EditorUtility.SaveFilePanel("Export Sky", "Assets", "SkyExport", "exr");
if (!string.IsNullOrEmpty(assetPath))

[MenuItem("GameObject/HD Render Pipeline/Scene Settings", false, 10)]
static void CreateCustomGameObject(MenuCommand menuCommand)
{
GameObject sceneSettings = new GameObject("Scene Settings");
var sceneSettings = new GameObject("Scene Settings");
GameObjectUtility.SetParentAndAlign(sceneSettings, menuCommand.context as GameObject);
Undo.RegisterCreatedObjectUndo(sceneSettings, "Create " + sceneSettings.name);
Selection.activeObject = sceneSettings;

class DoCreateNewAsset<AssetType> : UnityEditor.ProjectWindowCallback.EndNameEditAction where AssetType : ScriptableObject
class DoCreateNewAsset<TAssetType> : ProjectWindowCallback.EndNameEditAction where TAssetType : ScriptableObject
var newAsset = ScriptableObject.CreateInstance<AssetType>();
newAsset.name = System.IO.Path.GetFileName(pathName);
var newAsset = CreateInstance<TAssetType>();
newAsset.name = Path.GetFileName(pathName);
AssetDatabase.CreateAsset(newAsset, pathName);
ProjectWindowUtil.ShowCreatedAsset(newAsset);
}

class DoCreateNewAssetHDRISkySettings : DoCreateNewAsset<HDRISkySettings> {}
class DoCreateNewAssetProceduralSkySettings : DoCreateNewAsset<ProceduralSkySettings> {}
class DoCreateNewAssetSSAOSettings : DoCreateNewAsset<ScreenSpaceAmbientOcclusionSettings> {}
Texture2D icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetSSSProfile>(), "New SSS Profile.asset", icon, null);
}

Texture2D icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetCommonSettings>(), "New CommonSettings.asset", icon, null);
}

Texture2D icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetHDRISkySettings>(), "New HDRISkySettings.asset", icon, null);
}

Texture2D icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetProceduralSkySettings>(), "New ProceduralSkySettings.asset", icon, null);
}

Texture2D icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetSSAOSettings>(), "New AmbientOcclusionSettings.asset", icon, null);
}
}

326
ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs


using System.Collections.Generic;
using UnityEngine.Rendering;
using System;
using System.Diagnostics;
using System.Linq;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.Experimental.Rendering.HDPipeline.TilePass;

[Serializable]
public class RenderingSettings
{
public bool useForwardRenderingOnly = false; // TODO: Currently there is no way to strip the extra forward shaders generated by the shaders compiler, so we can switch dynamically.
public bool useDepthPrepassWithDeferredRendering = false;
public bool renderAlphaTestOnlyInDeferredPrepass = false;
public bool useForwardRenderingOnly; // TODO: Currently there is no way to strip the extra forward shaders generated by the shaders compiler, so we can switch dynamically.
public bool useDepthPrepassWithDeferredRendering;
public bool renderAlphaTestOnlyInDeferredPrepass;
// We have to fall back to forward-only rendering when scene view is using wireframe rendering mode --
// as rendering everything in wireframe + deferred do not play well together

public class GBufferManager
{
public const int MaxGbuffer = 8;
public const int k_MaxGbuffer = 8;
public int gbufferCount { get; set; }
int[] m_IDs = new int[k_MaxGbuffer];
RenderTargetIdentifier[] m_ColorMRTs;
RenderTargetIdentifier[] m_RTIDs = new RenderTargetIdentifier[k_MaxGbuffer];
RenderTextureFormat[] m_Formats = new RenderTextureFormat[k_MaxGbuffer];
RenderTextureReadWrite[] m_sRGBWrites = new RenderTextureReadWrite[k_MaxGbuffer];
IDs[index] = Shader.PropertyToID(stringId);
RTIDs[index] = new RenderTargetIdentifier(IDs[index]);
formats[index] = inFormat;
sRGBWrites[index] = inSRGBWrite;
m_IDs[index] = Shader.PropertyToID(stringId);
m_RTIDs[index] = new RenderTargetIdentifier(m_IDs[index]);
m_Formats[index] = inFormat;
m_sRGBWrites[index] = inSRGBWrite;
}
public void InitGBuffers(int width, int height, CommandBuffer cmd)

cmd.GetTemporaryRT(IDs[index], width, height, 0, FilterMode.Point, formats[index], sRGBWrites[index]);
cmd.GetTemporaryRT(m_IDs[index], width, height, 0, FilterMode.Point, m_Formats[index], m_sRGBWrites[index]);
private RenderTargetIdentifier[] m_ColorMRTs;
public RenderTargetIdentifier[] GetGBuffers()
{
if (m_ColorMRTs == null || m_ColorMRTs.Length != gbufferCount)

{
m_ColorMRTs[index] = RTIDs[index];
m_ColorMRTs[index] = m_RTIDs[index];
public int gbufferCount { get; set; }
int[] IDs = new int[MaxGbuffer];
RenderTargetIdentifier[] RTIDs = new RenderTargetIdentifier[MaxGbuffer];
RenderTextureFormat[] formats = new RenderTextureFormat[MaxGbuffer];
RenderTextureReadWrite[] sRGBWrites = new RenderTextureReadWrite[MaxGbuffer];
}
public partial class HDRenderPipeline : RenderPipeline

readonly RenderPipelineMaterial m_DeferredMaterial;
readonly List<RenderPipelineMaterial> m_MaterialList = new List<RenderPipelineMaterial>();
readonly GBufferManager m_gbufferManager = new GBufferManager();
readonly GBufferManager m_GbufferManager = new GBufferManager();
GPUCopy m_GPUCopy;
// Various set of material use in render loop
ComputeShader m_SubsurfaceScatteringCS { get { return m_Asset.renderPipelineResources.subsurfaceScatteringCS; } }

Material m_DebugViewMaterialGBuffer;
Material m_DebugDisplayLatlong;
Material m_DebugFullScreen;
#if UNITY_EDITOR
#endif
// Various buffer
readonly int m_CameraColorBuffer;

readonly RenderTargetIdentifier m_DeferredShadowBufferRT;
private RenderTexture m_CameraDepthStencilBuffer = null;
private RenderTexture m_CameraDepthBufferCopy = null;
private RenderTexture m_CameraStencilBufferCopy = null;
private RenderTexture m_HTile = null; // If the hardware does not expose it, we compute our own, optimized to only contain the SSS bit
RenderTexture m_CameraDepthStencilBuffer;
RenderTexture m_CameraDepthBufferCopy;
RenderTexture m_CameraStencilBufferCopy;
RenderTexture m_HTile; // If the hardware does not expose it, we compute our own, optimized to only contain the SSS bit
RenderTargetIdentifier m_CameraDepthStencilBufferRT;
RenderTargetIdentifier m_CameraDepthBufferCopyRT;
RenderTargetIdentifier m_CameraStencilBufferCopyRT;
RenderTargetIdentifier m_HTileRT;
// The pass "SRPDefaultUnlit" is a fallback to legacy unlit rendering and is required to support unity 2d + unity UI that render in the scene.
ShaderPassName[] m_ForwardPassNames = { new ShaderPassName(), HDShaderPassNames.s_SRPDefaultUnlitName};
ShaderPassName[] m_ForwardErrorPassNames = { HDShaderPassNames.s_AlwaysName, HDShaderPassNames.s_ForwardBaseName, HDShaderPassNames.s_DeferredName, HDShaderPassNames.s_PrepassBaseName, HDShaderPassNames.s_VertexName, HDShaderPassNames.s_VertexLMRGBMName, HDShaderPassNames.s_VertexLMName };
ShaderPassName[] m_SinglePassName = new ShaderPassName[1];
private RenderTargetIdentifier m_CameraDepthStencilBufferRT;
private RenderTargetIdentifier m_CameraDepthBufferCopyRT;
private RenderTargetIdentifier m_CameraStencilBufferCopyRT;
private RenderTargetIdentifier m_HTileRT;
RenderTargetIdentifier[] m_MRTCache2 = new RenderTargetIdentifier[2];
// Post-processing context and screen-space effects (recycled on every frame to avoid GC alloc)
readonly PostProcessRenderContext m_PostProcessContext;

MaterialPropertyBlock m_SharedPropertyBlock = new MaterialPropertyBlock();
DebugDisplaySettings m_DebugDisplaySettings = new DebugDisplaySettings();
static DebugDisplaySettings s_NeutralDebugDisplaySettings = new DebugDisplaySettings();
DebugDisplaySettings m_CurrentDebugDisplaySettings = null;
DebugDisplaySettings m_CurrentDebugDisplaySettings;
private int m_DebugFullScreenTempRT;
private bool m_FullScreenDebugPushed = false;
int m_DebugFullScreenTempRT;
bool m_FullScreenDebugPushed;
public SubsurfaceScatteringSettings sssSettings
{

private CommonSettings.Settings m_CommonSettings = CommonSettings.Settings.s_Defaultsettings;
private SkySettings m_SkySettings = null;
private ScreenSpaceAmbientOcclusionSettings.Settings m_SsaoSettings = ScreenSpaceAmbientOcclusionSettings.Settings.s_Defaultsettings;
CommonSettings.Settings m_CommonSettings = CommonSettings.Settings.s_Defaultsettings;
SkySettings m_SkySettings = null;
ScreenSpaceAmbientOcclusionSettings.Settings m_SsaoSettings = ScreenSpaceAmbientOcclusionSettings.Settings.s_Defaultsettings;
public CommonSettings.Settings commonSettingsToUse
{

public HDRenderPipeline(HDRenderPipelineAsset asset)
{
m_Asset = asset;
m_GPUCopy = new GPUCopy(asset.renderPipelineResources.copyChannelCS);
m_MaterialList = CoreUtils.GetRenderPipelineMaterialList();
m_MaterialList = HDUtils.GetRenderPipelineMaterialList();
foreach (RenderPipelineMaterial material in m_MaterialList)
foreach (var material in m_MaterialList)
{
}
}
// TODO: Handle the case of no Gbuffer material

InitializeDebugMaterials();
// Init Gbuffer description
m_gbufferManager.gbufferCount = m_DeferredMaterial.GetMaterialGBufferCount();
RenderTextureFormat[] RTFormat;
RenderTextureReadWrite[] RTReadWrite;
m_DeferredMaterial.GetMaterialGBufferDescription(out RTFormat, out RTReadWrite);
m_GbufferManager.gbufferCount = m_DeferredMaterial.GetMaterialGBufferCount();
RenderTextureFormat[] rtFormat;
RenderTextureReadWrite[] rtReadWrite;
m_DeferredMaterial.GetMaterialGBufferDescription(out rtFormat, out rtReadWrite);
for (int gbufferIndex = 0; gbufferIndex < m_gbufferManager.gbufferCount; ++gbufferIndex)
for (int gbufferIndex = 0; gbufferIndex < m_GbufferManager.gbufferCount; ++gbufferIndex)
m_gbufferManager.SetBufferDescription(gbufferIndex, "_GBufferTexture" + gbufferIndex, RTFormat[gbufferIndex], RTReadWrite[gbufferIndex]);
m_GbufferManager.SetBufferDescription(gbufferIndex, "_GBufferTexture" + gbufferIndex, rtFormat[gbufferIndex], rtReadWrite[gbufferIndex]);
}
m_VelocityBuffer = HDShaderIDs._VelocityTexture;

m_gbufferManager.SetBufferDescription(m_gbufferManager.gbufferCount, "_VelocityTexture", Builtin.GetVelocityBufferFormat(), Builtin.GetVelocityBufferReadWrite());
m_gbufferManager.gbufferCount++;
m_GbufferManager.SetBufferDescription(m_GbufferManager.gbufferCount, "_VelocityTexture", Builtin.GetVelocityBufferFormat(), Builtin.GetVelocityBufferReadWrite());
m_GbufferManager.gbufferCount++;
}
m_VelocityBufferRT = new RenderTargetIdentifier(m_VelocityBuffer);

void RegisterDebug()
{
// These need to be Runtime Only because those values are hold by the HDRenderPipeline asset so if user change them through the editor debug menu they might change the value in the asset without noticing it.
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Forward Only", () => (bool)m_Asset.renderingSettings.useForwardRenderingOnly, (value) => m_Asset.renderingSettings.useForwardRenderingOnly = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Deferred Depth Prepass", () => (bool)m_Asset.renderingSettings.useDepthPrepassWithDeferredRendering, (value) => m_Asset.renderingSettings.useDepthPrepassWithDeferredRendering = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Deferred Depth Prepass ATest Only", () => (bool)m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass, (value) => m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Forward Only", () => m_Asset.renderingSettings.useForwardRenderingOnly, (value) => m_Asset.renderingSettings.useForwardRenderingOnly = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Deferred Depth Prepass", () => m_Asset.renderingSettings.useDepthPrepassWithDeferredRendering, (value) => m_Asset.renderingSettings.useDepthPrepassWithDeferredRendering = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Deferred Depth Prepass ATest Only", () => m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass, (value) => m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Tile/Cluster", () => (bool)m_Asset.tileSettings.enableTileAndCluster, (value) => m_Asset.tileSettings.enableTileAndCluster = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Big Tile", () => (bool)m_Asset.tileSettings.enableBigTilePrepass, (value) => m_Asset.tileSettings.enableBigTilePrepass = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Cluster", () => (bool)m_Asset.tileSettings.enableClustered, (value) => m_Asset.tileSettings.enableClustered = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Compute Lighting", () => (bool)m_Asset.tileSettings.enableComputeLightEvaluation, (value) => m_Asset.tileSettings.enableComputeLightEvaluation = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Light Classification", () => (bool)m_Asset.tileSettings.enableComputeLightVariants, (value) => m_Asset.tileSettings.enableComputeLightVariants = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Material Classification", () => (bool)m_Asset.tileSettings.enableComputeMaterialVariants, (value) => m_Asset.tileSettings.enableComputeMaterialVariants = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Tile/Cluster", () => m_Asset.tileSettings.enableTileAndCluster, (value) => m_Asset.tileSettings.enableTileAndCluster = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Big Tile", () => m_Asset.tileSettings.enableBigTilePrepass, (value) => m_Asset.tileSettings.enableBigTilePrepass = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Cluster", () => m_Asset.tileSettings.enableClustered, (value) => m_Asset.tileSettings.enableClustered = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Compute Lighting", () => m_Asset.tileSettings.enableComputeLightEvaluation, (value) => m_Asset.tileSettings.enableComputeLightEvaluation = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Light Classification", () => m_Asset.tileSettings.enableComputeLightVariants, (value) => m_Asset.tileSettings.enableComputeLightVariants = (bool)value, DebugItemFlag.RuntimeOnly);
DebugMenuManager.instance.AddDebugItem<bool>("HDRP", "Enable Material Classification", () => m_Asset.tileSettings.enableComputeMaterialVariants, (value) => m_Asset.tileSettings.enableComputeMaterialVariants = (bool)value, DebugItemFlag.RuntimeOnly);
}
void InitializeDebugMaterials()

m_DebugFullScreen = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugFullScreenShader);
#if UNITY_EDITOR
#endif
}
public void CreateSssMaterials(bool useDisneySSS)

void InitializeRenderStateBlocks()
{
m_DepthStateOpaque.depthState = new DepthState(true, CompareFunction.LessEqual);
m_DepthStateOpaque.mask = RenderStateMask.Depth;
m_DepthStateOpaque = new RenderStateBlock
{
depthState = new DepthState(true, CompareFunction.LessEqual),
mask = RenderStateMask.Depth
};
m_DepthStateOpaqueWithPrepass.depthState = new DepthState(false, CompareFunction.Equal);
m_DepthStateOpaqueWithPrepass.mask = RenderStateMask.Depth;
m_DepthStateOpaqueWithPrepass = new RenderStateBlock
{
depthState = new DepthState(false, CompareFunction.Equal),
mask = RenderStateMask.Depth
};
}
public void OnSceneLoad()

CoreUtils.Destroy(m_DebugViewMaterialGBuffer);
CoreUtils.Destroy(m_DebugDisplayLatlong);
CoreUtils.Destroy(m_DebugFullScreen);
#if UNITY_EDITOR
#endif
m_SkyManager.Cleanup();

}
#if UNITY_EDITOR
private static readonly SupportedRenderingFeatures s_NeededFeatures = new SupportedRenderingFeatures()
static readonly SupportedRenderingFeatures s_NeededFeatures = new SupportedRenderingFeatures()
{
reflectionProbe = SupportedRenderingFeatures.ReflectionProbe.Rotation
};

{
if (m_CameraDepthStencilBuffer != null)
{
}
m_CameraDepthStencilBuffer = new RenderTexture(camera.pixelWidth, camera.pixelHeight, 24, RenderTextureFormat.Depth);
m_CameraDepthStencilBuffer.filterMode = FilterMode.Point;

if (NeedDepthBufferCopy())
{
if (m_CameraDepthBufferCopy != null)
{
}
m_CameraDepthBufferCopy = new RenderTexture(camera.pixelWidth, camera.pixelHeight, 24, RenderTextureFormat.Depth);
m_CameraDepthBufferCopy.filterMode = FilterMode.Point;
m_CameraDepthBufferCopy.Create();

if (NeedStencilBufferCopy())
{
if (m_CameraStencilBufferCopy != null)
{
}
m_CameraStencilBufferCopy = new RenderTexture(camera.pixelWidth, camera.pixelHeight, 0, RenderTextureFormat.R8, RenderTextureReadWrite.Linear); // DXGI_FORMAT_R8_UINT is not supported by Unity
m_CameraStencilBufferCopy.filterMode = FilterMode.Point;
m_CameraStencilBufferCopy.Create();

if (NeedHTileCopy())
{
if (m_HTile!= null)
{
}
// We use 8x8 tiles in order to match the native GCN HTile as closely as possible.
m_HTile = new RenderTexture((camera.pixelWidth + 7) / 8, (camera.pixelHeight + 7) / 8, 0, RenderTextureFormat.R8, RenderTextureReadWrite.Linear); // DXGI_FORMAT_R8_UINT is not supported by Unity
m_HTile.filterMode = FilterMode.Point;

bool resolutionChanged = camera.pixelWidth != m_CurrentWidth || camera.pixelHeight != m_CurrentHeight;
if (resolutionChanged || m_CameraDepthStencilBuffer == null)
{
}
{
}
{
}
// update recorded window resolution
m_CurrentWidth = camera.pixelWidth;

// Broadcast SSS parameters to all shaders.
Shader.SetGlobalInt( HDShaderIDs._EnableSSSAndTransmission, m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission ? 1 : 0);
Shader.SetGlobalInt( HDShaderIDs._TexturingModeFlags, (int)sssParameters.texturingModeFlags);
Shader.SetGlobalInt( HDShaderIDs._TransmissionFlags, (int)sssParameters.transmissionFlags);
Shader.SetGlobalInt( HDShaderIDs._TexturingModeFlags, sssParameters.texturingModeFlags);
Shader.SetGlobalInt( HDShaderIDs._TransmissionFlags, sssParameters.transmissionFlags);
Shader.SetGlobalInt( HDShaderIDs._UseDisneySSS, sssParameters.useDisneySSS ? 1 : 0);
cmd.SetGlobalVectorArray(HDShaderIDs._ThicknessRemaps, sssParameters.thicknessRemaps);
cmd.SetGlobalVectorArray(HDShaderIDs._ShapeParams, sssParameters.shapeParams);

return m_HTileRT;
}
private void CopyDepthBufferIfNeeded(CommandBuffer cmd)
void CopyDepthBufferIfNeeded(CommandBuffer cmd)
{
using (new ProfilingSample(cmd, NeedDepthBufferCopy() ? "Copy DepthBuffer" : "Set DepthBuffer"))
{

}
}
private void PrepareAndBindStencilTexture(CommandBuffer cmd)
void PrepareAndBindStencilTexture(CommandBuffer cmd)
{
if (NeedStencilBufferCopy())
{

}
// This is the main command buffer used for the frame.
CommandBuffer cmd = CommandBufferPool.Get("");
var cmd = CommandBufferPool.Get("");
m_MaterialList.ForEach(material => material.RenderInit(cmd));
foreach (var material in m_MaterialList)
material.RenderInit(cmd);
// Do anything we need to do upon a new frame.
m_LightLoop.NewFrame();

Camera camera = null;
foreach (var cam in cameras)
{

break;
}
}

renderContext.SetupCameraProperties(camera);
var postProcessLayer = camera.GetComponent<PostProcessLayer>();
HDCamera hdCamera = HDCamera.Get(camera, postProcessLayer);
var hdCamera = HDCamera.Get(camera, postProcessLayer);
PushGlobalParams(hdCamera, cmd, m_Asset.sssSettings);
// TODO: Find a correct place to bind these material textures

using (new ProfilingSample(cmd, "Forward"))
{
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Color | ClearFlag.Depth);
ShaderPassName[] arrayShaderPassName = { HDShaderPassNames.m_ForwardName };
RenderOpaqueRenderList(m_CullResults, camera, renderContext, cmd, arrayShaderPassName);
RenderTransparentRenderList(m_CullResults, camera, renderContext, cmd, arrayShaderPassName);
RenderOpaqueRenderList(m_CullResults, camera, renderContext, cmd, HDShaderPassNames.s_ForwardName);
RenderTransparentRenderList(m_CullResults, camera, renderContext, cmd, HDShaderPassNames.s_ForwardName);
}
renderContext.ExecuteCommandBuffer(cmd);

m_LightLoop.BuildGPULightLists(camera, cmd, m_CameraDepthStencilBufferRT, GetStencilTexture());
}
// Don't update the sky environment if we are rendering a cubemap (it should be update already)
if (camera.cameraType != CameraType.Reflection)
{

SubsurfaceScatteringPass(hdCamera, cmd, m_Asset.sssSettings);
RenderForward(m_CullResults, camera, renderContext, cmd, true);
#if UNITY_EDITOR
#endif
RenderLightingDebug(hdCamera, cmd, m_CameraColorBufferRT, m_CurrentDebugDisplaySettings);

// Render all type of transparent forward (unlit, lit, complex (hair...)) to keep the sorting between transparent objects.
RenderForward(m_CullResults, camera, renderContext, cmd, false);
#if UNITY_EDITOR
#endif
// Render volumetric lighting
VolumetricLightingPass(hdCamera, cmd);

// Simple blit
cmd.Blit(m_CameraColorBufferRT, BuiltinRenderTextureType.CameraTarget);
}
}
else
{

#if UNITY_EDITOR
// bind depth surface for editor grid/gizmo/selection rendering
if (camera.cameraType == CameraType.SceneView)
{
}
#endif
renderContext.ExecuteCommandBuffer(cmd);

CommandBuffer cmd,
ShaderPassName passName,
RendererConfiguration rendererConfiguration = 0,
RenderQueueRange? inRenderQueueRange = null,
RenderQueueRange? inRenderQueueRange = null,
RenderOpaqueRenderList(cull, camera, renderContext, cmd, new ShaderPassName[] { passName }, rendererConfiguration, inRenderQueueRange, stateBlock, overrideMaterial);
m_SinglePassName[0] = passName;
RenderOpaqueRenderList(cull, camera, renderContext, cmd, m_SinglePassName, rendererConfiguration, inRenderQueueRange, stateBlock, overrideMaterial);
}
void RenderOpaqueRenderList(CullResults cull,

}
if (overrideMaterial != null)
{
}
var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = inRenderQueueRange == null ? RenderQueueRange.opaque : inRenderQueueRange.Value };
var filterSettings = new FilterRenderersSettings(true)
{
renderQueueRange = inRenderQueueRange == null
? RenderQueueRange.opaque
: inRenderQueueRange.Value
};
if(stateBlock == null)
renderContext.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);
else

void RenderTransparentRenderList( CullResults cull,
Camera camera,
ScriptableRenderContext renderContext,
CommandBuffer cmd,
ShaderPassName passName,
RendererConfiguration rendererConfiguration = 0,
RenderStateBlock? stateBlock = null,
Material overrideMaterial = null)
void RenderTransparentRenderList(CullResults cull,
Camera camera,
ScriptableRenderContext renderContext,
CommandBuffer cmd,
ShaderPassName passName,
RendererConfiguration rendererConfiguration = 0,
RenderStateBlock? stateBlock = null,
Material overrideMaterial = null)
RenderTransparentRenderList(cull, camera, renderContext, cmd, new ShaderPassName[] { passName }, rendererConfiguration, stateBlock, overrideMaterial);
m_SinglePassName[0] = passName;
RenderTransparentRenderList(cull, camera, renderContext, cmd, m_SinglePassName, rendererConfiguration, stateBlock, overrideMaterial);
void RenderTransparentRenderList( CullResults cull,
Camera camera,
ScriptableRenderContext renderContext,
CommandBuffer cmd,
ShaderPassName[] passNames,
RendererConfiguration rendererConfiguration = 0,
RenderStateBlock? stateBlock = null,
Material overrideMaterial = null)
void RenderTransparentRenderList(CullResults cull,
Camera camera,
ScriptableRenderContext renderContext,
CommandBuffer cmd,
ShaderPassName[] passNames,
RendererConfiguration rendererConfiguration = 0,
RenderStateBlock? stateBlock = null,
Material overrideMaterial = null)
{
if (!m_CurrentDebugDisplaySettings.renderingDebugSettings.displayTransparentObjects)
return;

}
if (overrideMaterial != null)
{
}
if(stateBlock == null)
renderContext.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);
else

using (new ProfilingSample(cmd, addDepthPrepass ? "Depth Prepass" : "Depth Prepass forward opaque"))
{
// Default depth prepass (forward and deferred) will render all opaque geometry.
RenderQueueRange renderQueueRange = RenderQueueRange.opaque;
var renderQueueRange = RenderQueueRange.opaque;
// If we want only alpha tested geometry in prepass for deferred we change the RenderQueueRange
if (!m_Asset.renderingSettings.ShouldUseForwardRenderingOnly() && m_Asset.renderingSettings.useDepthPrepassWithDeferredRendering && m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass)
renderQueueRange = new RenderQueueRange { min = (int)RenderQueue.AlphaTest, max = (int)RenderQueue.GeometryLast - 1 };

CoreUtils.SetRenderTarget(cmd, m_CameraDepthStencilBufferRT);
// Note: addDepthPrepass and addForwardOnlyOpaqueDepthPrepass can't be both true at the same time. And if we are here both are not false
RenderOpaqueRenderList(cull, camera, renderContext, cmd, addDepthPrepass ? HDShaderPassNames.m_DepthOnlyName : HDShaderPassNames.m_ForwardOnlyOpaqueDepthOnlyName, 0, renderQueueRange);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, addDepthPrepass ? HDShaderPassNames.s_DepthOnlyName : HDShaderPassNames.s_ForwardOnlyOpaqueDepthOnlyName, 0, renderQueueRange);
}
}

using (new ProfilingSample(cmd, m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() ? "GBufferDebugDisplay" : "GBuffer"))
{
// setup GBuffer for rendering
CoreUtils.SetRenderTarget(cmd, m_gbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT);
CoreUtils.SetRenderTarget(cmd, m_GbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.m_GBufferDebugDisplayName, HDUtils.k_RendererConfigurationBakedLighting, RenderQueueRange.opaque, m_DepthStateOpaque);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferDebugDisplayName, HDUtils.k_RendererConfigurationBakedLighting, RenderQueueRange.opaque, m_DepthStateOpaque);
RenderQueueRange rangeOpaqueNoAlphaTest = new RenderQueueRange { min = (int)RenderQueue.Geometry, max = (int)RenderQueue.AlphaTest - 1 };
RenderQueueRange rangeOpaqueAlphaTest = new RenderQueueRange { min = (int)RenderQueue.AlphaTest, max = (int)RenderQueue.GeometryLast - 1 };
var rangeOpaqueNoAlphaTest = new RenderQueueRange { min = (int)RenderQueue.Geometry, max = (int)RenderQueue.AlphaTest - 1 };
var rangeOpaqueAlphaTest = new RenderQueueRange { min = (int)RenderQueue.AlphaTest, max = (int)RenderQueue.GeometryLast - 1 };
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.m_GBufferName, HDUtils.k_RendererConfigurationBakedLighting, rangeOpaqueNoAlphaTest, m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass ? m_DepthStateOpaque : m_DepthStateOpaqueWithPrepass);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, HDUtils.k_RendererConfigurationBakedLighting, rangeOpaqueNoAlphaTest, m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass ? m_DepthStateOpaque : m_DepthStateOpaqueWithPrepass);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.m_GBufferWithPrepassName, HDUtils.k_RendererConfigurationBakedLighting, rangeOpaqueAlphaTest, m_DepthStateOpaqueWithPrepass);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferWithPrepassName, HDUtils.k_RendererConfigurationBakedLighting, rangeOpaqueAlphaTest, m_DepthStateOpaqueWithPrepass);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.m_GBufferName, HDUtils.k_RendererConfigurationBakedLighting, RenderQueueRange.opaque, m_DepthStateOpaque);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, HDUtils.k_RendererConfigurationBakedLighting, RenderQueueRange.opaque, m_DepthStateOpaque);
}
}
}

{
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.All, Color.black);
// Render Opaque forward
RenderOpaqueRenderList(cull, hdCamera.camera, renderContext, cmd, HDShaderPassNames.m_ForwardDisplayDebugName, HDUtils.k_RendererConfigurationBakedLighting);
RenderOpaqueRenderList(cull, hdCamera.camera, renderContext, cmd, HDShaderPassNames.s_ForwardDisplayDebugName, HDUtils.k_RendererConfigurationBakedLighting);
RenderTransparentRenderList(cull, hdCamera.camera, renderContext, cmd, HDShaderPassNames.m_ForwardDisplayDebugName, HDUtils.k_RendererConfigurationBakedLighting);
RenderTransparentRenderList(cull, hdCamera.camera, renderContext, cmd, HDShaderPassNames.s_ForwardDisplayDebugName, HDUtils.k_RendererConfigurationBakedLighting);
}
}

void RenderDeferredLighting(HDCamera hdCamera, CommandBuffer cmd)
{
if (m_Asset.renderingSettings.ShouldUseForwardRenderingOnly())
{
}
RenderTargetIdentifier[] colorRTs = { m_CameraColorBufferRT, m_CameraSssDiffuseLightingBufferRT };
RenderTargetIdentifier depthTexture = GetDepthTexture();
m_MRTCache2[0] = m_CameraColorBufferRT;
m_MRTCache2[1] = m_CameraSssDiffuseLightingBufferRT;
var depthTexture = GetDepthTexture();
LightLoop.LightingPassOptions options = new LightLoop.LightingPassOptions();
var options = new LightLoop.LightingPassOptions();
options.volumetricLightingEnabled = m_VolumetricLightingEnabled;
if (m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission)

m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, colorRTs, m_CameraDepthStencilBufferRT, depthTexture, m_DeferredShadowBuffer, options);
m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, m_MRTCache2, m_CameraDepthStencilBufferRT, depthTexture, m_DeferredShadowBuffer, options);
m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, colorRTs, m_CameraDepthStencilBufferRT, depthTexture, m_DeferredShadowBuffer, options);
m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, m_MRTCache2, m_CameraDepthStencilBufferRT, depthTexture, m_DeferredShadowBuffer, options);
}
// Combines specular lighting and diffuse lighting with subsurface scattering.

cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._FilterKernels, sssParameters.filterKernels);
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._ShapeParams, sssParameters.shapeParams);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture0, m_gbufferManager.GetGBuffers()[0]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture1, m_gbufferManager.GetGBuffers()[1]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture2, m_gbufferManager.GetGBuffers()[2]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture3, m_gbufferManager.GetGBuffers()[3]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture0, m_GbufferManager.GetGBuffers()[0]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture1, m_GbufferManager.GetGBuffers()[1]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture2, m_GbufferManager.GetGBuffers()[2]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture3, m_GbufferManager.GetGBuffers()[3]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._DepthTexture, GetDepthTexture());
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._StencilTexture, GetStencilTexture());
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._HTile, GetHTile());

string profileName;
if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled())
{
passName = addForwardPass ? HDShaderPassNames.m_ForwardDisplayDebugName : HDShaderPassNames.m_ForwardOnlyOpaqueDisplayDebugName;
passName = addForwardPass ? HDShaderPassNames.s_ForwardDisplayDebugName : HDShaderPassNames.s_ForwardOnlyOpaqueDisplayDebugName;
passName = addForwardPass ? HDShaderPassNames.m_ForwardName : HDShaderPassNames.m_ForwardOnlyOpaqueName;
passName = addForwardPass ? HDShaderPassNames.s_ForwardName : HDShaderPassNames.s_ForwardOnlyOpaqueName;
profileName = addForwardPass ? (renderOpaque ? "Forward Opaque" : "Forward Transparent") : "Forward Only Opaque";
}

m_LightLoop.RenderForward(camera, cmd, renderOpaque);
// The pass "SRPDefaultUnlit" is a fallback to legacy unlit rendering and is required to support unity 2d + unity UI that render in the scene.
ShaderPassName[] arrayNames = { passName, HDShaderPassNames.m_SRPDefaultUnlitName};
m_ForwardPassNames[0] = passName;
RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, arrayNames, HDUtils.k_RendererConfigurationBakedLighting, null, m_DepthStateOpaqueWithPrepass);
RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, m_ForwardPassNames, HDUtils.k_RendererConfigurationBakedLighting, null, m_DepthStateOpaqueWithPrepass);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, arrayNames, HDUtils.k_RendererConfigurationBakedLighting);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, m_ForwardPassNames, HDUtils.k_RendererConfigurationBakedLighting);
#if UNITY_EDITOR
[Conditional("DEVELOPMENT_BUILD"), Conditional("UNITY_EDITOR")]
void RenderForwardError(CullResults cullResults, Camera camera, ScriptableRenderContext renderContext, CommandBuffer cmd, bool renderOpaque)
{
using (new ProfilingSample(cmd, "Render Forward Error"))

ShaderPassName[] arrayNames = { HDShaderPassNames.m_AlwaysName, HDShaderPassNames.m_ForwardBaseName, HDShaderPassNames.m_DeferredName, HDShaderPassNames.m_PrepassBaseName, HDShaderPassNames.m_VertexName, HDShaderPassNames.m_VertexLMRGBMName, HDShaderPassNames.m_VertexLMName };
RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, arrayNames, 0, null, null, m_ErrorMaterial);
RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, m_ForwardErrorPassNames, 0, null, null, m_ErrorMaterial);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, arrayNames, 0, null, m_ErrorMaterial);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, m_ForwardErrorPassNames, 0, null, m_ErrorMaterial);
#endif
void RenderVelocity(CullResults cullResults, HDCamera hdcam, ScriptableRenderContext renderContext, CommandBuffer cmd)
{

CoreUtils.DrawFullScreen(cmd, m_CameraMotionVectorsMaterial, m_VelocityBufferRT, null, 0);
cmd.SetRenderTarget(m_VelocityBufferRT, m_CameraDepthStencilBufferRT);
RenderOpaqueRenderList(cullResults, hdcam.camera, renderContext, cmd, HDShaderPassNames.m_MotionVectorsName, RendererConfiguration.PerObjectMotionVectors);
RenderOpaqueRenderList(cullResults, hdcam.camera, renderContext, cmd, HDShaderPassNames.s_MotionVectorsName, RendererConfiguration.PerObjectMotionVectors);
PushFullScreenDebugTexture(cmd, m_VelocityBuffer, hdcam.camera, renderContext, FullScreenDebugMode.MotionVectors);
}

cmd.SetGlobalVector(HDShaderIDs._DepthPyramidMipSize, new Vector4(size, size, lodCount, 0));
cmd.GetTemporaryRT(HDShaderIDs._DepthPyramidMips[0], size, size, 0, FilterMode.Bilinear, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear, 1, true);
HDUtils.SampleCopyChannel_xyzw2x(cmd, GetDepthTexture(), HDShaderIDs._DepthPyramidMips[0], new Vector2(size, size), m_Asset.renderPipelineResources);
m_GPUCopy.SampleCopyChannel_xyzw2x(cmd, GetDepthTexture(), HDShaderIDs._DepthPyramidMips[0], new Vector2(size, size));
cmd.CopyTexture(HDShaderIDs._DepthPyramidMips[0], 0, 0, m_DepthPyramidBuffer, 0, 0);
for (int i = 0; i < lodCount; i++)

cmd.ClearRenderTarget(false, true, Color.black); // TODO: can we avoid this clear for performance ?
// Only transparent object can render distortion vectors
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, HDShaderPassNames.m_DistortionVectorsName);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, HDShaderPassNames.s_DistortionVectorsName);
}
}

{
m_ShadowSettings.enabled = m_CurrentDebugDisplaySettings.lightingDebugSettings.enableShadows;
LightingDebugSettings lightingDebugSettings = m_CurrentDebugDisplaySettings.lightingDebugSettings;
Vector4 debugAlbedo = new Vector4(lightingDebugSettings.debugLightingAlbedo.r, lightingDebugSettings.debugLightingAlbedo.g, lightingDebugSettings.debugLightingAlbedo.b, 0.0f);
Vector4 debugSmoothness = new Vector4(lightingDebugSettings.overrideSmoothness ? 1.0f : 0.0f, lightingDebugSettings.overrideSmoothnessValue, 0.0f, 0.0f);
var lightingDebugSettings = m_CurrentDebugDisplaySettings.lightingDebugSettings;
var debugAlbedo = new Vector4(lightingDebugSettings.debugLightingAlbedo.r, lightingDebugSettings.debugLightingAlbedo.g, lightingDebugSettings.debugLightingAlbedo.b, 0.0f);
var debugSmoothness = new Vector4(lightingDebugSettings.overrideSmoothness ? 1.0f : 0.0f, lightingDebugSettings.overrideSmoothnessValue, 0.0f, 0.0f);
Shader.SetGlobalInt(HDShaderIDs._DebugViewMaterial, (int)m_CurrentDebugDisplaySettings.GetDebugMaterialIndex());
Shader.SetGlobalInt(HDShaderIDs._DebugLightingMode, (int)m_CurrentDebugDisplaySettings.GetDebugLightingMode());

float overlaySize = Math.Min(camera.camera.pixelHeight, camera.camera.pixelWidth) * overlayRatio;
float y = camera.camera.pixelHeight - overlaySize;
LightingDebugSettings lightingDebug = m_CurrentDebugDisplaySettings.lightingDebugSettings;
var lightingDebug = m_CurrentDebugDisplaySettings.lightingDebugSettings;
Texture skyReflection = m_SkyManager.skyReflection;
var skyReflection = m_SkyManager.skyReflection;
m_SharedPropertyBlock.SetTexture(HDShaderIDs._InputCubemap, skyReflection);
m_SharedPropertyBlock.SetFloat(HDShaderIDs._Mipmap, lightingDebug.skyReflectionMipmap);
cmd.SetViewport(new Rect(x, y, overlaySize, overlaySize));

// End
if (!m_Asset.renderingSettings.ShouldUseForwardRenderingOnly())
{
m_gbufferManager.InitGBuffers(w, h, cmd);
}
m_GbufferManager.InitGBuffers(w, h, cmd);
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Depth);
}

}
if (m_VolumetricLightingEnabled)
{
}
// TEMP: As we are in development and have not all the setup pass we still clear the color in emissive buffer and gbuffer, but this will be removed later.

{
using (new ProfilingSample(cmd, "Clear GBuffer"))
{
CoreUtils.SetRenderTarget(cmd, m_gbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT, ClearFlag.Color, Color.black);
CoreUtils.SetRenderTarget(cmd, m_GbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT, ClearFlag.Color, Color.black);
}
}
// END TEMP

34
ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.cs


using UnityEngine.Rendering;
using System;
using System.Linq;
using UnityEngine.Rendering.PostProcessing;
#if UNITY_EDITOR
using UnityEditor;
#endif
// This HDRenderPipeline assume linear lighting. Don't work with gamma.
// The HDRenderPipeline assumes linear lighting. Doesn't work with gamma.
#if UNITY_EDITOR
[MenuItem("RenderPipeline/HDRenderPipeline/Create Pipeline Asset", false, 16)]
static void CreateHDRenderPipeline()
HDRenderPipelineAsset()
var instance = CreateInstance<HDRenderPipelineAsset>();
AssetDatabase.CreateAsset(instance, HDUtils.GetHDRenderPipelinePath() + "HDRenderPipelineAsset.asset");
// If it exist, load renderPipelineResources
instance.renderPipelineResources = AssetDatabase.LoadAssetAtPath<RenderPipelineResources>(RenderPipelineResources.GetRenderPipelineResourcesPath());
#endif
private HDRenderPipelineAsset()
{ }
protected override IRenderPipeline InternalCreatePipeline()
{

[SerializeField]
private RenderPipelineResources m_RenderPipelineResources;
RenderPipelineResources m_RenderPipelineResources;
public RenderPipelineResources renderPipelineResources
{
get { return m_RenderPipelineResources; }

// NOTE: All those properties are public because of how HDRenderPipelineInspector retrieve those properties via serialization/reflection
// Doing it this way allow to change parameters name and still retrieve correct serialized value
// NOTE: All those properties are public because of how HDRenderPipelineInspector retrieves those properties via serialization/reflection
// Doing it this way allows to change parameters name and still retrieve correct serialized values
// Renderer Settings
public RenderingSettings renderingSettings = new RenderingSettings();

[SerializeField]
Shader m_DefaultShader;
public Material DefaultDiffuseMaterial
public Material defaultDiffuseMaterial
public Shader DefaultShader
public Shader defaultShader
{
get { return m_DefaultShader; }
private set { m_DefaultShader = value; }

{
return null;
}
public void OnValidate()
{

367
ScriptableRenderPipeline/HDRenderPipeline/HDStringConstants.cs


namespace UnityEngine.Experimental.Rendering.HDPipeline
{
static class HDShaderPassNames
public static class HDShaderPassNames
internal static readonly ShaderPassName s_EmptyName = new ShaderPassName("");
internal static readonly ShaderPassName m_ForwardName = new ShaderPassName("Forward");
internal static readonly ShaderPassName m_ForwardDisplayDebugName = new ShaderPassName("ForwardDisplayDebug");
internal static readonly ShaderPassName m_DepthOnlyName = new ShaderPassName("DepthOnly");
internal static readonly ShaderPassName m_ForwardOnlyOpaqueDepthOnlyName = new ShaderPassName("ForwardOnlyOpaqueDepthOnly");
internal static readonly ShaderPassName m_ForwardOnlyOpaqueName = new ShaderPassName("ForwardOnlyOpaque");
internal static readonly ShaderPassName m_ForwardOnlyOpaqueDisplayDebugName = new ShaderPassName("ForwardOnlyOpaqueDisplayDebug");
internal static readonly ShaderPassName m_GBufferName = new ShaderPassName("GBuffer");
internal static readonly ShaderPassName m_GBufferWithPrepassName = new ShaderPassName("GBufferWithPrepass");
internal static readonly ShaderPassName m_GBufferDebugDisplayName = new ShaderPassName("GBufferDebugDisplay");
internal static readonly ShaderPassName m_SRPDefaultUnlitName = new ShaderPassName("SRPDefaultUnlit");
internal static readonly ShaderPassName m_MotionVectorsName = new ShaderPassName("MotionVectors");
internal static readonly ShaderPassName m_DistortionVectorsName = new ShaderPassName("DistortionVectors");
public static readonly ShaderPassName s_EmptyName = new ShaderPassName("");
public static readonly ShaderPassName s_ForwardName = new ShaderPassName("Forward");
public static readonly ShaderPassName s_ForwardDisplayDebugName = new ShaderPassName("ForwardDisplayDebug");
public static readonly ShaderPassName s_DepthOnlyName = new ShaderPassName("DepthOnly");
public static readonly ShaderPassName s_ForwardOnlyOpaqueDepthOnlyName = new ShaderPassName("ForwardOnlyOpaqueDepthOnly");
public static readonly ShaderPassName s_ForwardOnlyOpaqueName = new ShaderPassName("ForwardOnlyOpaque");
public static readonly ShaderPassName s_ForwardOnlyOpaqueDisplayDebugName = new ShaderPassName("ForwardOnlyOpaqueDisplayDebug");
public static readonly ShaderPassName s_GBufferName = new ShaderPassName("GBuffer");
public static readonly ShaderPassName s_GBufferWithPrepassName = new ShaderPassName("GBufferWithPrepass");
public static readonly ShaderPassName s_GBufferDebugDisplayName = new ShaderPassName("GBufferDebugDisplay");
public static readonly ShaderPassName s_SRPDefaultUnlitName = new ShaderPassName("SRPDefaultUnlit");
public static readonly ShaderPassName s_MotionVectorsName = new ShaderPassName("MotionVectors");
public static readonly ShaderPassName s_DistortionVectorsName = new ShaderPassName("DistortionVectors");
internal static readonly ShaderPassName m_AlwaysName = new ShaderPassName("Always");
internal static readonly ShaderPassName m_ForwardBaseName = new ShaderPassName("ForwardBase");
internal static readonly ShaderPassName m_DeferredName = new ShaderPassName("Deferred");
internal static readonly ShaderPassName m_PrepassBaseName = new ShaderPassName("PrepassBase");
internal static readonly ShaderPassName m_VertexName = new ShaderPassName("Vertex");
internal static readonly ShaderPassName m_VertexLMRGBMName = new ShaderPassName("VertexLMRGBM");
internal static readonly ShaderPassName m_VertexLMName = new ShaderPassName("VertexLM");
public static readonly ShaderPassName s_AlwaysName = new ShaderPassName("Always");
public static readonly ShaderPassName s_ForwardBaseName = new ShaderPassName("ForwardBase");
public static readonly ShaderPassName s_DeferredName = new ShaderPassName("Deferred");
public static readonly ShaderPassName s_PrepassBaseName = new ShaderPassName("PrepassBase");
public static readonly ShaderPassName s_VertexName = new ShaderPassName("Vertex");
public static readonly ShaderPassName s_VertexLMRGBMName = new ShaderPassName("VertexLMRGBM");
public static readonly ShaderPassName s_VertexLMName = new ShaderPassName("VertexLM");
// fields names as in the shaders for ease of use... Would be nice to clean this up at some
// point.
static class HDShaderIDs
// fields names as in the shaders for ease of use...
// TODO: Would be nice to clean this up at some point
public static class HDShaderIDs
internal static readonly int _ShadowDatasExp = Shader.PropertyToID("_ShadowDatasExp");
internal static readonly int _ShadowPayloads = Shader.PropertyToID("_ShadowPayloads");
internal static readonly int _ShadowmapExp_VSM_0 = Shader.PropertyToID("_ShadowmapExp_VSM_0");
internal static readonly int _ShadowmapExp_VSM_1 = Shader.PropertyToID("_ShadowmapExp_VSM_1");
internal static readonly int _ShadowmapExp_VSM_2 = Shader.PropertyToID("_ShadowmapExp_VSM_2");
internal static readonly int _ShadowmapExp_PCF = Shader.PropertyToID("_ShadowmapExp_PCF");
public static readonly int _ShadowDatasExp = Shader.PropertyToID("_ShadowDatasExp");
public static readonly int _ShadowPayloads = Shader.PropertyToID("_ShadowPayloads");
public static readonly int _ShadowmapExp_VSM_0 = Shader.PropertyToID("_ShadowmapExp_VSM_0");
public static readonly int _ShadowmapExp_VSM_1 = Shader.PropertyToID("_ShadowmapExp_VSM_1");
public static readonly int _ShadowmapExp_VSM_2 = Shader.PropertyToID("_ShadowmapExp_VSM_2");
public static readonly int _ShadowmapExp_PCF = Shader.PropertyToID("_ShadowmapExp_PCF");
internal static readonly int g_LayeredSingleIdxBuffer = Shader.PropertyToID("g_LayeredSingleIdxBuffer");
internal static readonly int _EnvLightIndexShift = Shader.PropertyToID("_EnvLightIndexShift");
internal static readonly int g_isOrthographic = Shader.PropertyToID("g_isOrthographic");
internal static readonly int g_iNrVisibLights = Shader.PropertyToID("g_iNrVisibLights");
internal static readonly int g_mScrProjection = Shader.PropertyToID("g_mScrProjection");
internal static readonly int g_mInvScrProjection = Shader.PropertyToID("g_mInvScrProjection");
internal static readonly int g_iLog2NumClusters = Shader.PropertyToID("g_iLog2NumClusters");
internal static readonly int g_fNearPlane = Shader.PropertyToID("g_fNearPlane");
internal static readonly int g_fFarPlane = Shader.PropertyToID("g_fFarPlane");
internal static readonly int g_fClustScale = Shader.PropertyToID("g_fClustScale");
internal static readonly int g_fClustBase = Shader.PropertyToID("g_fClustBase");
internal static readonly int g_depth_tex = Shader.PropertyToID("g_depth_tex");
internal static readonly int g_vLayeredLightList = Shader.PropertyToID("g_vLayeredLightList");
internal static readonly int g_LayeredOffset = Shader.PropertyToID("g_LayeredOffset");
internal static readonly int g_vBigTileLightList = Shader.PropertyToID("g_vBigTileLightList");
internal static readonly int g_logBaseBuffer = Shader.PropertyToID("g_logBaseBuffer");
internal static readonly int g_vBoundsBuffer = Shader.PropertyToID("g_vBoundsBuffer");
internal static readonly int _LightVolumeData = Shader.PropertyToID("_LightVolumeData");
internal static readonly int g_data = Shader.PropertyToID("g_data");
internal static readonly int g_mProjection = Shader.PropertyToID("g_mProjection");
internal static readonly int g_mInvProjection = Shader.PropertyToID("g_mInvProjection");
internal static readonly int g_viDimensions = Shader.PropertyToID("g_viDimensions");
internal static readonly int g_vLightList = Shader.PropertyToID("g_vLightList");
public static readonly int g_LayeredSingleIdxBuffer = Shader.PropertyToID("g_LayeredSingleIdxBuffer");
public static readonly int _EnvLightIndexShift = Shader.PropertyToID("_EnvLightIndexShift");
public static readonly int g_isOrthographic = Shader.PropertyToID("g_isOrthographic");
public static readonly int g_iNrVisibLights = Shader.PropertyToID("g_iNrVisibLights");
public static readonly int g_mScrProjection = Shader.PropertyToID("g_mScrProjection");
public static readonly int g_mInvScrProjection = Shader.PropertyToID("g_mInvScrProjection");
public static readonly int g_iLog2NumClusters = Shader.PropertyToID("g_iLog2NumClusters");
public static readonly int g_fNearPlane = Shader.PropertyToID("g_fNearPlane");
public static readonly int g_fFarPlane = Shader.PropertyToID("g_fFarPlane");
public static readonly int g_fClustScale = Shader.PropertyToID("g_fClustScale");
public static readonly int g_fClustBase = Shader.PropertyToID("g_fClustBase");
public static readonly int g_depth_tex = Shader.PropertyToID("g_depth_tex");
public static readonly int g_vLayeredLightList = Shader.PropertyToID("g_vLayeredLightList");
public static readonly int g_LayeredOffset = Shader.PropertyToID("g_LayeredOffset");
public static readonly int g_vBigTileLightList = Shader.PropertyToID("g_vBigTileLightList");
public static readonly int g_logBaseBuffer = Shader.PropertyToID("g_logBaseBuffer");
public static readonly int g_vBoundsBuffer = Shader.PropertyToID("g_vBoundsBuffer");
public static readonly int _LightVolumeData = Shader.PropertyToID("_LightVolumeData");
public static readonly int g_data = Shader.PropertyToID("g_data");
public static readonly int g_mProjection = Shader.PropertyToID("g_mProjection");
public static readonly int g_mInvProjection = Shader.PropertyToID("g_mInvProjection");
public static readonly int g_viDimensions = Shader.PropertyToID("g_viDimensions");
public static readonly int g_vLightList = Shader.PropertyToID("g_vLightList");
internal static readonly int g_BaseFeatureFlags = Shader.PropertyToID("g_BaseFeatureFlags");
internal static readonly int g_TileFeatureFlags = Shader.PropertyToID("g_TileFeatureFlags");
public static readonly int g_BaseFeatureFlags = Shader.PropertyToID("g_BaseFeatureFlags");
public static readonly int g_TileFeatureFlags = Shader.PropertyToID("g_TileFeatureFlags");
internal static readonly int _GBufferTexture0 = Shader.PropertyToID("_GBufferTexture0");
internal static readonly int _GBufferTexture1 = Shader.PropertyToID("_GBufferTexture1");
internal static readonly int _GBufferTexture2 = Shader.PropertyToID("_GBufferTexture2");
internal static readonly int _GBufferTexture3 = Shader.PropertyToID("_GBufferTexture3");
public static readonly int _GBufferTexture0 = Shader.PropertyToID("_GBufferTexture0");
public static readonly int _GBufferTexture1 = Shader.PropertyToID("_GBufferTexture1");
public static readonly int _GBufferTexture2 = Shader.PropertyToID("_GBufferTexture2");
public static readonly int _GBufferTexture3 = Shader.PropertyToID("_GBufferTexture3");
internal static readonly int g_DispatchIndirectBuffer = Shader.PropertyToID("g_DispatchIndirectBuffer");
internal static readonly int g_TileList = Shader.PropertyToID("g_TileList");
internal static readonly int g_NumTiles = Shader.PropertyToID("g_NumTiles");
internal static readonly int g_NumTilesX = Shader.PropertyToID("g_NumTilesX");
public static readonly int g_DispatchIndirectBuffer = Shader.PropertyToID("g_DispatchIndirectBuffer");
public static readonly int g_TileList = Shader.PropertyToID("g_TileList");
public static readonly int g_NumTiles = Shader.PropertyToID("g_NumTiles");
public static readonly int g_NumTilesX = Shader.PropertyToID("g_NumTilesX");
internal static readonly int _NumTiles = Shader.PropertyToID("_NumTiles");
public static readonly int _NumTiles = Shader.PropertyToID("_NumTiles");
internal static readonly int _CookieTextures = Shader.PropertyToID("_CookieTextures");
internal static readonly int _CookieCubeTextures = Shader.PropertyToID("_CookieCubeTextures");
internal static readonly int _EnvTextures = Shader.PropertyToID("_EnvTextures");
internal static readonly int _DirectionalLightDatas = Shader.PropertyToID("_DirectionalLightDatas");
internal static readonly int _DirectionalLightCount = Shader.PropertyToID("_DirectionalLightCount");
internal static readonly int _LightDatas = Shader.PropertyToID("_LightDatas");
internal static readonly int _PunctualLightCount = Shader.PropertyToID("_PunctualLightCount");
internal static readonly int _AreaLightCount = Shader.PropertyToID("_AreaLightCount");
internal static readonly int g_vLightListGlobal = Shader.PropertyToID("g_vLightListGlobal");
internal static readonly int _EnvLightDatas = Shader.PropertyToID("_EnvLightDatas");
internal static readonly int _EnvLightCount = Shader.PropertyToID("_EnvLightCount");
internal static readonly int _ShadowDatas = Shader.PropertyToID("_ShadowDatas");
internal static readonly int _DirShadowSplitSpheres = Shader.PropertyToID("_DirShadowSplitSpheres");
internal static readonly int _NumTileFtplX = Shader.PropertyToID("_NumTileFtplX");
internal static readonly int _NumTileFtplY = Shader.PropertyToID("_NumTileFtplY");
internal static readonly int _NumTileClusteredX = Shader.PropertyToID("_NumTileClusteredX");
internal static readonly int _NumTileClusteredY = Shader.PropertyToID("_NumTileClusteredY");
public static readonly int _CookieTextures = Shader.PropertyToID("_CookieTextures");
public static readonly int _CookieCubeTextures = Shader.PropertyToID("_CookieCubeTextures");
public static readonly int _EnvTextures = Shader.PropertyToID("_EnvTextures");
public static readonly int _DirectionalLightDatas = Shader.PropertyToID("_DirectionalLightDatas");
public static readonly int _DirectionalLightCount = Shader.PropertyToID("_DirectionalLightCount");
public static readonly int _LightDatas = Shader.PropertyToID("_LightDatas");
public static readonly int _PunctualLightCount = Shader.PropertyToID("_PunctualLightCount");
public static readonly int _AreaLightCount = Shader.PropertyToID("_AreaLightCount");
public static readonly int g_vLightListGlobal = Shader.PropertyToID("g_vLightListGlobal");
public static readonly int _EnvLightDatas = Shader.PropertyToID("_EnvLightDatas");
public static readonly int _EnvLightCount = Shader.PropertyToID("_EnvLightCount");
public static readonly int _ShadowDatas = Shader.PropertyToID("_ShadowDatas");
public static readonly int _DirShadowSplitSpheres = Shader.PropertyToID("_DirShadowSplitSpheres");
public static readonly int _NumTileFtplX = Shader.PropertyToID("_NumTileFtplX");
public static readonly int _NumTileFtplY = Shader.PropertyToID("_NumTileFtplY");
public static readonly int _NumTileClusteredX = Shader.PropertyToID("_NumTileClusteredX");
public static readonly int _NumTileClusteredY = Shader.PropertyToID("_NumTileClusteredY");
internal static readonly int g_isLogBaseBufferEnabled = Shader.PropertyToID("g_isLogBaseBufferEnabled");
internal static readonly int g_vLayeredOffsetsBuffer = Shader.PropertyToID("g_vLayeredOffsetsBuffer");
public static readonly int g_isLogBaseBufferEnabled = Shader.PropertyToID("g_isLogBaseBufferEnabled");
public static readonly int g_vLayeredOffsetsBuffer = Shader.PropertyToID("g_vLayeredOffsetsBuffer");
internal static readonly int _ViewTilesFlags = Shader.PropertyToID("_ViewTilesFlags");
internal static readonly int _MousePixelCoord = Shader.PropertyToID("_MousePixelCoord");
public static readonly int _ViewTilesFlags = Shader.PropertyToID("_ViewTilesFlags");
public static readonly int _MousePixelCoord = Shader.PropertyToID("_MousePixelCoord");
internal static readonly int _DebugViewMaterial = Shader.PropertyToID("_DebugViewMaterial");
internal static readonly int _DebugLightingMode = Shader.PropertyToID("_DebugLightingMode");
internal static readonly int _DebugLightingAlbedo = Shader.PropertyToID("_DebugLightingAlbedo");
internal static readonly int _DebugLightingSmoothness = Shader.PropertyToID("_DebugLightingSmoothness");
internal static readonly int _AmbientOcclusionTexture = Shader.PropertyToID("_AmbientOcclusionTexture");
public static readonly int _DebugViewMaterial = Shader.PropertyToID("_DebugViewMaterial");
public static readonly int _DebugLightingMode = Shader.PropertyToID("_DebugLightingMode");
public static readonly int _DebugLightingAlbedo = Shader.PropertyToID("_DebugLightingAlbedo");
public static readonly int _DebugLightingSmoothness = Shader.PropertyToID("_DebugLightingSmoothness");
public static readonly int _AmbientOcclusionTexture = Shader.PropertyToID("_AmbientOcclusionTexture");
internal static readonly int _UseTileLightList = Shader.PropertyToID("_UseTileLightList");
internal static readonly int _Time = Shader.PropertyToID("_Time");
internal static readonly int _SinTime = Shader.PropertyToID("_SinTime");
internal static readonly int _CosTime = Shader.PropertyToID("_CosTime");
internal static readonly int unity_DeltaTime = Shader.PropertyToID("unity_DeltaTime");
internal static readonly int _EnvLightSkyEnabled = Shader.PropertyToID("_EnvLightSkyEnabled");
internal static readonly int _AmbientOcclusionDirectLightStrenght = Shader.PropertyToID("_AmbientOcclusionDirectLightStrenght");
internal static readonly int _SkyTexture = Shader.PropertyToID("_SkyTexture");
public static readonly int _UseTileLightList = Shader.PropertyToID("_UseTileLightList");
public static readonly int _Time = Shader.PropertyToID("_Time");
public static readonly int _SinTime = Shader.PropertyToID("_SinTime");
public static readonly int _CosTime = Shader.PropertyToID("_CosTime");
public static readonly int unity_DeltaTime = Shader.PropertyToID("unity_DeltaTime");
public static readonly int _EnvLightSkyEnabled = Shader.PropertyToID("_EnvLightSkyEnabled");
public static readonly int _AmbientOcclusionDirectLightStrenght = Shader.PropertyToID("_AmbientOcclusionDirectLightStrenght");
public static readonly int _SkyTexture = Shader.PropertyToID("_SkyTexture");
internal static readonly int _UseDisneySSS = Shader.PropertyToID("_UseDisneySSS");
internal static readonly int _EnableSSSAndTransmission = Shader.PropertyToID("_EnableSSSAndTransmission");
internal static readonly int _TexturingModeFlags = Shader.PropertyToID("_TexturingModeFlags");
internal static readonly int _TransmissionFlags = Shader.PropertyToID("_TransmissionFlags");
internal static readonly int _ThicknessRemaps = Shader.PropertyToID("_ThicknessRemaps");
internal static readonly int _ShapeParams = Shader.PropertyToID("_ShapeParams");
internal static readonly int _HalfRcpVariancesAndWeights = Shader.PropertyToID("_HalfRcpVariancesAndWeights");
internal static readonly int _TransmissionTints = Shader.PropertyToID("_TransmissionTints");
internal static readonly int specularLightingUAV = Shader.PropertyToID("specularLightingUAV");
internal static readonly int diffuseLightingUAV = Shader.PropertyToID("diffuseLightingUAV");
public static readonly int _UseDisneySSS = Shader.PropertyToID("_UseDisneySSS");
public static readonly int _EnableSSSAndTransmission = Shader.PropertyToID("_EnableSSSAndTransmission");
public static readonly int _TexturingModeFlags = Shader.PropertyToID("_TexturingModeFlags");
public static readonly int _TransmissionFlags = Shader.PropertyToID("_TransmissionFlags");
public static readonly int _ThicknessRemaps = Shader.PropertyToID("_ThicknessRemaps");
public static readonly int _ShapeParams = Shader.PropertyToID("_ShapeParams");
public static readonly int _HalfRcpVariancesAndWeights = Shader.PropertyToID("_HalfRcpVariancesAndWeights");
public static readonly int _TransmissionTints = Shader.PropertyToID("_TransmissionTints");
public static readonly int specularLightingUAV = Shader.PropertyToID("specularLightingUAV");
public static readonly int diffuseLightingUAV = Shader.PropertyToID("diffuseLightingUAV");
internal static readonly int g_TileListOffset = Shader.PropertyToID("g_TileListOffset");
public static readonly int g_TileListOffset = Shader.PropertyToID("g_TileListOffset");
internal static readonly int _LtcData = Shader.PropertyToID("_LtcData");
internal static readonly int _PreIntegratedFGD = Shader.PropertyToID("_PreIntegratedFGD");
internal static readonly int _LtcGGXMatrix = Shader.PropertyToID("_LtcGGXMatrix");
internal static readonly int _LtcDisneyDiffuseMatrix = Shader.PropertyToID("_LtcDisneyDiffuseMatrix");
internal static readonly int _LtcMultiGGXFresnelDisneyDiffuse = Shader.PropertyToID("_LtcMultiGGXFresnelDisneyDiffuse");
public static readonly int _LtcData = Shader.PropertyToID("_LtcData");
public static readonly int _PreIntegratedFGD = Shader.PropertyToID("_PreIntegratedFGD");
public static readonly int _LtcGGXMatrix = Shader.PropertyToID("_LtcGGXMatrix");
public static readonly int _LtcDisneyDiffuseMatrix = Shader.PropertyToID("_LtcDisneyDiffuseMatrix");
public static readonly int _LtcMultiGGXFresnelDisneyDiffuse = Shader.PropertyToID("_LtcMultiGGXFresnelDisneyDiffuse");
internal static readonly int _MainDepthTexture = Shader.PropertyToID("_MainDepthTexture");
public static readonly int _MainDepthTexture = Shader.PropertyToID("_MainDepthTexture");
internal static readonly int _DeferredShadowTexture = Shader.PropertyToID("_DeferredShadowTexture");
internal static readonly int _DeferredShadowTextureUAV = Shader.PropertyToID("_DeferredShadowTextureUAV");
internal static readonly int _DirectionalShadowIndex = Shader.PropertyToID("_DirectionalShadowIndex");
public static readonly int _DeferredShadowTexture = Shader.PropertyToID("_DeferredShadowTexture");
public static readonly int _DeferredShadowTextureUAV = Shader.PropertyToID("_DeferredShadowTextureUAV");
public static readonly int _DirectionalShadowIndex = Shader.PropertyToID("_DirectionalShadowIndex");
internal static readonly int unity_OrthoParams = Shader.PropertyToID("unity_OrthoParams");
internal static readonly int _ZBufferParams = Shader.PropertyToID("_ZBufferParams");
internal static readonly int _ScreenParams = Shader.PropertyToID("_ScreenParams");
internal static readonly int _ProjectionParams = Shader.PropertyToID("_ProjectionParams");
internal static readonly int _WorldSpaceCameraPos = Shader.PropertyToID("_WorldSpaceCameraPos");
public static readonly int unity_OrthoParams = Shader.PropertyToID("unity_OrthoParams");
public static readonly int _ZBufferParams = Shader.PropertyToID("_ZBufferParams");
public static readonly int _ScreenParams = Shader.PropertyToID("_ScreenParams");
public static readonly int _ProjectionParams = Shader.PropertyToID("_ProjectionParams");
public static readonly int _WorldSpaceCameraPos = Shader.PropertyToID("_WorldSpaceCameraPos");
public static readonly int _StencilRef = Shader.PropertyToID("_StencilRef");
public static readonly int _StencilCmp = Shader.PropertyToID("_StencilCmp");
internal static readonly int _StencilRef = Shader.PropertyToID("_StencilRef");
internal static readonly int _StencilCmp = Shader.PropertyToID("_StencilCmp");
public static readonly int _SrcBlend = Shader.PropertyToID("_SrcBlend");
public static readonly int _DstBlend = Shader.PropertyToID("_DstBlend");
internal static readonly int _SrcBlend = Shader.PropertyToID("_SrcBlend");
internal static readonly int _DstBlend = Shader.PropertyToID("_DstBlend");
public static readonly int _HTile = Shader.PropertyToID("_HTile");
public static readonly int _StencilTexture = Shader.PropertyToID("_StencilTexture");
internal static readonly int _HTile = Shader.PropertyToID("_HTile");
internal static readonly int _StencilTexture = Shader.PropertyToID("_StencilTexture");
public static readonly int _ViewMatrix = Shader.PropertyToID("_ViewMatrix");
public static readonly int _InvViewMatrix = Shader.PropertyToID("_InvViewMatrix");
public static readonly int _ProjMatrix = Shader.PropertyToID("_ProjMatrix");
public static readonly int _InvProjMatrix = Shader.PropertyToID("_InvProjMatrix");
public static readonly int _NonJitteredViewProjMatrix = Shader.PropertyToID("_NonJitteredViewProjMatrix");
public static readonly int _ViewProjMatrix = Shader.PropertyToID("_ViewProjMatrix");
public static readonly int _InvViewProjMatrix = Shader.PropertyToID("_InvViewProjMatrix");
public static readonly int _InvProjParam = Shader.PropertyToID("_InvProjParam");
public static readonly int _ScreenSize = Shader.PropertyToID("_ScreenSize");
public static readonly int _PrevViewProjMatrix = Shader.PropertyToID("_PrevViewProjMatrix");
public static readonly int _FrustumPlanes = Shader.PropertyToID("_FrustumPlanes");
internal static readonly int _ViewMatrix = Shader.PropertyToID("_ViewMatrix");
internal static readonly int _InvViewMatrix = Shader.PropertyToID("_InvViewMatrix");
internal static readonly int _ProjMatrix = Shader.PropertyToID("_ProjMatrix");
internal static readonly int _InvProjMatrix = Shader.PropertyToID("_InvProjMatrix");
internal static readonly int _NonJitteredViewProjMatrix = Shader.PropertyToID("_NonJitteredViewProjMatrix");
internal static readonly int _ViewProjMatrix = Shader.PropertyToID("_ViewProjMatrix");
internal static readonly int _InvViewProjMatrix = Shader.PropertyToID("_InvViewProjMatrix");
internal static readonly int _InvProjParam = Shader.PropertyToID("_InvProjParam");
internal static readonly int _ScreenSize = Shader.PropertyToID("_ScreenSize");
internal static readonly int _PrevViewProjMatrix = Shader.PropertyToID("_PrevViewProjMatrix");
internal static readonly int _FrustumPlanes = Shader.PropertyToID("_FrustumPlanes");
public static readonly int _DepthTexture = Shader.PropertyToID("_DepthTexture");
public static readonly int _CameraColorTexture = Shader.PropertyToID("_CameraColorTexture");
public static readonly int _CameraSssDiffuseLightingBuffer = Shader.PropertyToID("_CameraSssDiffuseLightingTexture");
public static readonly int _CameraFilteringBuffer = Shader.PropertyToID("_CameraFilteringTexture");
public static readonly int _IrradianceSource = Shader.PropertyToID("_IrradianceSource");
internal static readonly int _DepthTexture = Shader.PropertyToID("_DepthTexture");
internal static readonly int _CameraColorTexture = Shader.PropertyToID("_CameraColorTexture");
internal static readonly int _CameraSssDiffuseLightingBuffer = Shader.PropertyToID("_CameraSssDiffuseLightingTexture");
internal static readonly int _CameraFilteringBuffer = Shader.PropertyToID("_CameraFilteringTexture");
internal static readonly int _IrradianceSource = Shader.PropertyToID("_IrradianceSource");
internal static readonly int _VelocityTexture = Shader.PropertyToID("_VelocityTexture");
internal static readonly int _DistortionTexture = Shader.PropertyToID("_DistortionTexture");
internal static readonly int _GaussianPyramidColorTexture = Shader.PropertyToID("_GaussianPyramidColorTexture");
internal static readonly int _DepthPyramidTexture = Shader.PropertyToID("_PyramidDepthTexture");
internal static readonly int _GaussianPyramidColorMipSize = Shader.PropertyToID("_GaussianPyramidColorMipSize");
internal static readonly int[] _GaussianPyramidColorMips =
public static readonly int _VelocityTexture = Shader.PropertyToID("_VelocityTexture");
public static readonly int _DistortionTexture = Shader.PropertyToID("_DistortionTexture");
public static readonly int _GaussianPyramidColorTexture = Shader.PropertyToID("_GaussianPyramidColorTexture");
public static readonly int _DepthPyramidTexture = Shader.PropertyToID("_PyramidDepthTexture");
public static readonly int _GaussianPyramidColorMipSize = Shader.PropertyToID("_GaussianPyramidColorMipSize");
public static readonly int[] _GaussianPyramidColorMips =
{
Shader.PropertyToID("_GaussianColorMip0"),
Shader.PropertyToID("_GaussianColorMip1"),

Shader.PropertyToID("_GaussianColorMip13"),
Shader.PropertyToID("_GaussianColorMip14"),
};
internal static readonly int _DepthPyramidMipSize = Shader.PropertyToID("_PyramidDepthMipSize");
internal static readonly int[] _DepthPyramidMips =
public static readonly int _DepthPyramidMipSize = Shader.PropertyToID("_PyramidDepthMipSize");
public static readonly int[] _DepthPyramidMips =
{
Shader.PropertyToID("_DepthPyramidMip0"),
Shader.PropertyToID("_DepthPyramidMip1"),

Shader.PropertyToID("_DepthPyramidMip13"),
Shader.PropertyToID("_DepthPyramidMip14"),
};
internal static readonly int _DebugFullScreenTexture = Shader.PropertyToID("_DebugFullScreenTexture");
public static readonly int _DebugFullScreenTexture = Shader.PropertyToID("_DebugFullScreenTexture");
internal static readonly int _WorldScales = Shader.PropertyToID("_WorldScales");
internal static readonly int _FilterKernels = Shader.PropertyToID("_FilterKernels");
internal static readonly int _FilterKernelsBasic = Shader.PropertyToID("_FilterKernelsBasic");
internal static readonly int _HalfRcpWeightedVariances = Shader.PropertyToID("_HalfRcpWeightedVariances");
public static readonly int _WorldScales = Shader.PropertyToID("_WorldScales");
public static readonly int _FilterKernels = Shader.PropertyToID("_FilterKernels");
public static readonly int _FilterKernelsBasic = Shader.PropertyToID("_FilterKernelsBasic");
public static readonly int _HalfRcpWeightedVariances = Shader.PropertyToID("_HalfRcpWeightedVariances");
internal static readonly int _CameraPosDiff = Shader.PropertyToID("_CameraPosDiff");
public static readonly int _CameraPosDiff = Shader.PropertyToID("_CameraPosDiff");
internal static readonly int _CameraDepthTexture = Shader.PropertyToID("_CameraDepthTexture");
internal static readonly int _CameraMotionVectorsTexture = Shader.PropertyToID("_CameraMotionVectorsTexture");
internal static readonly int _FullScreenDebugMode = Shader.PropertyToID("_FullScreenDebugMode");
public static readonly int _CameraDepthTexture = Shader.PropertyToID("_CameraDepthTexture");
public static readonly int _CameraMotionVectorsTexture = Shader.PropertyToID("_CameraMotionVectorsTexture");
public static readonly int _FullScreenDebugMode = Shader.PropertyToID("_FullScreenDebugMode");
internal static readonly int _InputCubemap = Shader.PropertyToID("_InputCubemap");
internal static readonly int _Mipmap = Shader.PropertyToID("_Mipmap");
public static readonly int _InputCubemap = Shader.PropertyToID("_InputCubemap");
public static readonly int _Mipmap = Shader.PropertyToID("_Mipmap");
public static readonly int _MaxRadius = Shader.PropertyToID("_MaxRadius");
public static readonly int _ShapeParam = Shader.PropertyToID("_ShapeParam");
public static readonly int _StdDev1 = Shader.PropertyToID("_StdDev1");
public static readonly int _StdDev2 = Shader.PropertyToID("_StdDev2");
public static readonly int _LerpWeight = Shader.PropertyToID("_LerpWeight");
public static readonly int _HalfRcpVarianceAndWeight1 = Shader.PropertyToID("_HalfRcpVarianceAndWeight1");
public static readonly int _HalfRcpVarianceAndWeight2 = Shader.PropertyToID("_HalfRcpVarianceAndWeight2");
public static readonly int _TransmissionTint = Shader.PropertyToID("_TransmissionTint");
public static readonly int _ThicknessRemap = Shader.PropertyToID("_ThicknessRemap");
internal static readonly int _MaxRadius = Shader.PropertyToID("_MaxRadius");
internal static readonly int _ShapeParam = Shader.PropertyToID("_ShapeParam");
internal static readonly int _StdDev1 = Shader.PropertyToID("_StdDev1");
internal static readonly int _StdDev2 = Shader.PropertyToID("_StdDev2");
internal static readonly int _LerpWeight = Shader.PropertyToID("_LerpWeight");
internal static readonly int _HalfRcpVarianceAndWeight1 = Shader.PropertyToID("_HalfRcpVarianceAndWeight1");
internal static readonly int _HalfRcpVarianceAndWeight2 = Shader.PropertyToID("_HalfRcpVarianceAndWeight2");
internal static readonly int _TransmissionTint = Shader.PropertyToID("_TransmissionTint");
internal static readonly int _ThicknessRemap = Shader.PropertyToID("_ThicknessRemap");
public static readonly int _Cubemap = Shader.PropertyToID("_Cubemap");
public static readonly int _SkyParam = Shader.PropertyToID("_SkyParam");
public static readonly int _PixelCoordToViewDirWS = Shader.PropertyToID("_PixelCoordToViewDirWS");
internal static readonly int _Cubemap = Shader.PropertyToID("_Cubemap");
internal static readonly int _SkyParam = Shader.PropertyToID("_SkyParam");
internal static readonly int _PixelCoordToViewDirWS = Shader.PropertyToID("_PixelCoordToViewDirWS");
internal static readonly int _GlobalFog_Extinction = Shader.PropertyToID("_GlobalFog_Extinction");
internal static readonly int _GlobalFog_Asymmetry = Shader.PropertyToID("_GlobalFog_Asymmetry");
internal static readonly int _GlobalFog_Scattering = Shader.PropertyToID("_GlobalFog_Scattering");
public static readonly int _GlobalFog_Extinction = Shader.PropertyToID("_GlobalFog_Extinction");
public static readonly int _GlobalFog_Asymmetry = Shader.PropertyToID("_GlobalFog_Asymmetry");
public static readonly int _GlobalFog_Scattering = Shader.PropertyToID("_GlobalFog_Scattering");
internal static readonly int _Size = Shader.PropertyToID("_Size");
internal static readonly int _Source4 = Shader.PropertyToID("_Source4");
internal static readonly int _Result1 = Shader.PropertyToID("_Result1");
public static readonly int _Size = Shader.PropertyToID("_Size");
public static readonly int _Source4 = Shader.PropertyToID("_Source4");
public static readonly int _Result1 = Shader.PropertyToID("_Result1");
}
}

59
ScriptableRenderPipeline/HDRenderPipeline/HDUtils.cs


#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEngine.Rendering;
#endif
using System;
using System.Collections.Generic;
using System.Linq;
#if UNITY_EDITOR
public static string GetHDRenderPipelinePath()
public const RendererConfiguration k_RendererConfigurationBakedLighting = RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbeProxyVolume;
public static List<RenderPipelineMaterial> GetRenderPipelineMaterialList()
// User can create their own directory for SRP, so we need to find the current path that they use.
// We know that DefaultHDMaterial exist and we know where it is, let's use that to find the current directory.
var guid = AssetDatabase.FindAssets("DefaultHDMaterial t:material");
string path = AssetDatabase.GUIDToAssetPath(guid[0]);
path = Path.GetDirectoryName(path); // Asset is in HDRenderPipeline/RenderPipelineResources/DefaultHDMaterial.mat
path = path.Replace("RenderPipelineResources", ""); // Keep only path with HDRenderPipeline
var baseType = typeof(RenderPipelineMaterial);
var assembly = baseType.Assembly;
var types = assembly.GetTypes()
.Where(t => t.IsSubclassOf(baseType))
.Select(Activator.CreateInstance)
.Cast<RenderPipelineMaterial>()
.ToList();
return path;
}
// Note: If there is a need for an optimization in the future of this function, user can
// simply fill the materialList manually by commenting the code abode and returning a
// custom list of materials they use in their game.
//
// return new List<RenderPipelineMaterial>
// {
// new Lit(),
// new Unlit(),
// ...
// };
public static string GetPostProcessingPath()
{
var hdrpPath = GetHDRenderPipelinePath();
var fullPath = Path.GetFullPath(hdrpPath + "../../PostProcessing/PostProcessing");
var relativePath = fullPath.Substring(fullPath.IndexOf("Assets"));
return relativePath.Replace("\\", "/") + "/";
return types;
#endif
public const RendererConfiguration k_RendererConfigurationBakedLighting = RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbeProxyVolume;
public static Matrix4x4 GetViewProjectionMatrix(Matrix4x4 worldToViewMatrix, Matrix4x4 projectionMatrix)
{

y -= s_OverlayLineHeight;
s_OverlayLineHeight = -1.0f;
}
}
public static void SampleCopyChannel_xyzw2x(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier target, Vector2 size, RenderPipelineResources resources)
{
var s = new Vector4(size.x, size.y, 1f / size.x, 1f / size.y);
cmd.SetComputeVectorParam(resources.copyChannelCS, HDShaderIDs._Size, s);
cmd.SetComputeTextureParam(resources.copyChannelCS, resources.copyChannelKernel_xyzw2x, HDShaderIDs._Source4, source);
cmd.SetComputeTextureParam(resources.copyChannelCS, resources.copyChannelKernel_xyzw2x, HDShaderIDs._Result1, target);
cmd.DispatchCompute(resources.copyChannelCS, resources.copyChannelKernel_xyzw2x, (int)(size.x) / 8, (int)(size.y) / 8, 1);
}
}
}

3
ScriptableRenderPipeline/HDRenderPipeline/Lighting/Editor/HDLightEditor.Styles.cs


using System;
using System.Linq;
using UnityEngine;
namespace UnityEngine.Experimental.Rendering.HDPipeline
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
// TODO: Missing UI tooltips
partial class HDLightEditor

15
ScriptableRenderPipeline/HDRenderPipeline/Lighting/Editor/HDLightEditor.cs


using System;
using System.Linq;
using UnityEditor;
using UnityEditor.Experimental.Rendering;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEngine.Experimental.Rendering.HDPipeline
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
// TODO: Simplify this editor once we can target 2018.1
[CanEditMultipleObjects]

bool m_IsRealtime { get { return m_BaseData.lightmapping.intValue == 4; } }
Light light { get { return serializedObject.targetObject as Light; } }
Texture m_Cookie { get { return m_BaseData.cookie.objectReferenceValue as Texture; } }
bool m_BakingWarningValue { get { return !Lightmapping.bakedGI && m_LightmappingTypeIsSame && !m_IsRealtime; } }
bool m_BakingWarningValue { get { return !UnityEditor.Lightmapping.bakedGI && m_LightmappingTypeIsSame && !m_IsRealtime; } }
bool m_BounceWarningValue
{
get

if (m_BaseData.shadowsType.enumValueIndex != (int)LightShadows.None)
DrawFoldout(m_BaseData.shadowsType, "Shadows", DrawShadows);
EditorLightUtilities.DrawSplitter();
CoreEditorUtils.DrawSplitter();
EditorGUILayout.Space();
m_SerializedAdditionalShadowData.ApplyModifiedProperties();

void DrawFoldout(SerializedProperty foldoutProperty, string title, Action func)
{
EditorLightUtilities.DrawSplitter();
CoreEditorUtils.DrawSplitter();
state = EditorLightUtilities.DrawHeaderFoldout(title, state);
state = CoreEditorUtils.DrawHeaderFoldout(title, state);
if (state)
{

130
ScriptableRenderPipeline/HDRenderPipeline/Lighting/EditorLightUtilities.cs


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

Gizmos.DrawLine(m_transform.position, m_transform.position + m_transform.TransformVector(m_transform.root.up * -gizmoSize / m_transform.localScale.y));
Gizmos.DrawLine(m_transform.position, m_transform.position + m_transform.TransformVector(m_transform.root.right * gizmoSize / m_transform.localScale.x));
Gizmos.DrawLine(m_transform.position, m_transform.position + m_transform.TransformVector(m_transform.root.right * -gizmoSize / m_transform.localScale.x));
}
public static bool DrawHeader(string title, bool activeField)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 16f;
labelRect.xMax -= 20f;
var toggleRect = backgroundRect;
toggleRect.y += 2f;
toggleRect.width = 13f;
toggleRect.height = 13f;
var menuIcon = EditorGUIUtility.isProSkin
? (Texture2D)EditorGUIUtility.Load("Builtin Skins/DarkSkin/Images/pane options.png")
: (Texture2D)EditorGUIUtility.Load("Builtin Skins/LightSkin/Images/pane options.png");
var menuRect = new Rect(labelRect.xMax + 4f, labelRect.y + 4f, menuIcon.width, menuIcon.height);
// Background rect should be full-width
backgroundRect.xMin = 0f;
backgroundRect.width += 4f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
using (new EditorGUI.DisabledScope(!activeField))
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
// Active checkbox
activeField = GUI.Toggle(toggleRect, activeField, GUIContent.none, new GUIStyle("ShurikenCheckMark"));
var e = Event.current;
if (e.type == EventType.MouseDown && backgroundRect.Contains(e.mousePosition) && e.button == 0)
{
activeField = !activeField;
e.Use();
}
EditorGUILayout.Space();
return activeField;
}
public static void DrawHeader(string title)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 16f;
labelRect.xMax -= 20f;
var foldoutRect = backgroundRect;
foldoutRect.y += 1f;
foldoutRect.width = 13f;
foldoutRect.height = 13f;
// Background rect should be full-width
backgroundRect.xMin = 0f;
backgroundRect.width += 4f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
EditorGUILayout.Space();
}
public static void DrawSplitter()
{
var rect = GUILayoutUtility.GetRect(1f, 1f);
// Splitter rect should be full-width
rect.xMin = 0f;
rect.width += 4f;
if (Event.current.type != EventType.Repaint)
return;
EditorGUI.DrawRect(rect, !EditorGUIUtility.isProSkin
? new Color(0.6f, 0.6f, 0.6f, 1.333f)
: new Color(0.12f, 0.12f, 0.12f, 1.333f));
}
public static bool DrawHeaderFoldout(string title, bool state)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 16f;
labelRect.xMax -= 20f;
var foldoutRect = backgroundRect;
foldoutRect.y += 1f;
foldoutRect.width = 13f;
foldoutRect.height = 13f;
// Background rect should be full-width
backgroundRect.xMin = 0f;
backgroundRect.width += 4f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
// Active checkbox
state = GUI.Toggle(foldoutRect, state, GUIContent.none, EditorStyles.foldout);
var e = Event.current;
if (e.type == EventType.MouseDown && backgroundRect.Contains(e.mousePosition) && e.button == 0)
{
state = !state;
e.Use();
}
return state;
}
}
#endif

2
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs


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

6
ScriptableRenderPipeline/HDRenderPipeline/Lighting/Volumetrics/HomogeneousFog.cs


using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[ExecuteInEditMode]

4
ScriptableRenderPipeline/HDRenderPipeline/Lighting/Volumetrics/VolumetricLighting.cs


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

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs


using UnityEngine;
//-----------------------------------------------------------------------------
// structure definition
//-----------------------------------------------------------------------------

3
ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/Editor/LayeredLitUI.cs


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

private class StylesLayer
{
public readonly Color[] layerColors =
public readonly Color[] layerColors =
{
Color.white,
Color.red,

5
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs


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

public static GUIContent materialIDText = new GUIContent("Material type", "Subsurface Scattering: enable for translucent materials such as skin, vegetation, fruit, marble, wax and milk.");
// Displacement mapping (POM, tessellation, per vertex)
public static GUIContent lockWithObjectScaleText = new GUIContent("Lock with object scale", "Displacement mapping will take the absolute value of the scale of the object into account.");
public static GUIContent lockWithObjectScaleText = new GUIContent("Lock with object scale", "Displacement mapping will take the absolute value of the scale of the object into account.");
public static GUIContent lockWithTilingRateText = new GUIContent("Lock with height map tiling rate", "Displacement mapping will take the absolute value of the tiling rate of the height map into account.");
// Per pixel displacement

invPrimScale.vectorValue = new Vector4(1.0f / ppdPrimitiveLength.floatValue, 1.0f / ppdPrimitiveWidth.floatValue); // Precompute
m_MaterialEditor.ShaderProperty(perPixelDisplacementObjectScale, StylesBaseLit.lockWithObjectScaleText);
m_MaterialEditor.ShaderProperty(perPixelDisplacementTilingScale, StylesBaseLit.lockWithTilingRateText);
m_MaterialEditor.ShaderProperty(depthOffsetEnable, StylesBaseLit.depthOffsetEnableText);
m_MaterialEditor.ShaderProperty(depthOffsetEnable, StylesBaseLit.depthOffsetEnableText);
EditorGUI.indentLevel--;
}

18
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/LitUI.cs


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

{
m_MaterialEditor.ShaderProperty(ior, Styles.refractionIORText);
if (thicknessMap.textureValue == null)
m_MaterialEditor.ShaderProperty(thickness, Styles.refractionThicknessText);
m_MaterialEditor.TexturePropertySingleLine(Styles.refractionThicknessMapText, thicknessMap);
if (mode != Lit.RefractionMode.ThinPlane)
{
if (thicknessMap.textureValue == null)
m_MaterialEditor.ShaderProperty(thickness, Styles.refractionThicknessText);
m_MaterialEditor.TexturePropertySingleLine(Styles.refractionThicknessMapText, thicknessMap);
++EditorGUI.indentLevel;
m_MaterialEditor.ShaderProperty(thicknessMultiplier, Styles.refractionThicknessMultiplierText);
--EditorGUI.indentLevel;
++EditorGUI.indentLevel;
m_MaterialEditor.ShaderProperty(thicknessMultiplier, Styles.refractionThicknessMultiplierText);
--EditorGUI.indentLevel;
}
m_MaterialEditor.ShaderProperty(transmittanceColor, Styles.transmittanceColorText);
++EditorGUI.indentLevel;

8
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl


//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// SurfaceData and BSDFData
//-----------------------------------------------------------------------------

bsdfData.ior = ior;
// Absorption coefficient from Disney: http://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf
bsdfData.absorptionCoefficient = -log(transmittanceColor + 0.00001) / max(atDistance, 0.000001);
bsdfData.thickness = max(0.0001, thickness);
#if defined(_REFRACTION_THINPLANE)
bsdfData.thickness = 0.03;
#else
bsdfData.thickness = max(0.000001, thickness);
#endif
}
// For image based lighting, a part of the BSDF is pre-integrated.

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitData.hlsl


int numSteps = (int)lerp(_PPDMinSamples, _PPDMaxSamples, unitAngle);
float2 offset = ParallaxOcclusionMapping(lod, _PPDLodThreshold, numSteps, viewDirUV, 1, ppdParam, planeHeight);
layerTexCoord.base.uvXZ += offset;
layerTexCoord.base.uvXZ += offset;
layerTexCoord.details.uvXZ += offset;
height += layerTexCoord.triplanarWeights.y * planeHeight;
NdotV += layerTexCoord.triplanarWeights.y * viewDirTS.z;

1
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.DisneyDiffuse.cs


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

1
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.GGX.cs


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

259
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringProfile.cs


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

BuildKernel();
}
public void Validate()
{
thicknessRemap.y = Mathf.Max(thicknessRemap.y, 0f);
thicknessRemap.x = Mathf.Clamp(thicknessRemap.x, 0f, thicknessRemap.y);
worldScale = Mathf.Max(worldScale, 0.001f);
// Old SSS Model >>>
var c = new Color();
c.r = Mathf.Max(0.05f, scatterDistance1.r);
c.g = Mathf.Max(0.05f, scatterDistance1.g);
c.b = Mathf.Max(0.05f, scatterDistance1.b);
c.a = 0.0f;
scatterDistance1 = c;
c.r = Mathf.Max(0.05f, scatterDistance2.r);
c.g = Mathf.Max(0.05f, scatterDistance2.g);
c.b = Mathf.Max(0.05f, scatterDistance2.b);
c.a = 0.0f;
scatterDistance2 = c;
// <<< Old SSS Model
BuildKernel();
}
// Ref: Approximate Reflectance Profiles for Efficient Subsurface Scattering by Pixar.
public void BuildKernel()
{

}
// Clamp to avoid artifacts.
m_ShapeParam = new Vector3();
m_ShapeParam.x = 1.0f / Mathf.Max(0.001f, scatteringDistance.r);
m_ShapeParam.y = 1.0f / Mathf.Max(0.001f, scatteringDistance.g);
m_ShapeParam.z = 1.0f / Mathf.Max(0.001f, scatteringDistance.b);

}
}
for (int i = 0; i < numProfiles; i++)
foreach (var profile in profiles)
// Skip unassigned profiles.
if (profiles[i] == null) continue;
profiles[i].thicknessRemap.y = Mathf.Max(profiles[i].thicknessRemap.y, 0);
profiles[i].thicknessRemap.x = Mathf.Clamp(profiles[i].thicknessRemap.x, 0, profiles[i].thicknessRemap.y);
profiles[i].worldScale = Mathf.Max(profiles[i].worldScale, 0.001f);
// Old SSS Model >>>
Color c = new Color();
c.r = Mathf.Max(0.05f, profiles[i].scatterDistance1.r);
c.g = Mathf.Max(0.05f, profiles[i].scatterDistance1.g);
c.b = Mathf.Max(0.05f, profiles[i].scatterDistance1.b);
c.a = 0.0f;
profiles[i].scatterDistance1 = c;
c.r = Mathf.Max(0.05f, profiles[i].scatterDistance2.r);
c.g = Mathf.Max(0.05f, profiles[i].scatterDistance2.g);
c.b = Mathf.Max(0.05f, profiles[i].scatterDistance2.b);
c.a = 0.0f;
profiles[i].scatterDistance2 = c;
// <<< Old SSS Model
profiles[i].BuildKernel();
if (profile != null)
profile.Validate();
}
UpdateCache();

// UpdateCache();
}
}
#if UNITY_EDITOR
[CustomEditor(typeof(SubsurfaceScatteringProfile))]
public class SubsurfaceScatteringProfileEditor : Editor
{
private class Styles
{
public readonly GUIContent sssProfilePreview0 = new GUIContent("Profile Preview");
public readonly GUIContent sssProfilePreview1 = new GUIContent("Shows the fraction of light scattered from the source (center).");
public readonly GUIContent sssProfilePreview2 = new GUIContent("The distance to the boundary of the image corresponds to the Max Radius.");
public readonly GUIContent sssProfilePreview3 = new GUIContent("Note that the intensity of pixels around the center may be clipped.");
public readonly GUIContent sssTransmittancePreview0 = new GUIContent("Transmittance Preview");
public readonly GUIContent sssTransmittancePreview1 = new GUIContent("Shows the fraction of light passing through the object for thickness values from the remap.");
public readonly GUIContent sssTransmittancePreview2 = new GUIContent("Can be viewed as a cross section of a slab of material illuminated by white light from the left.");
public readonly GUIContent sssProfileScatteringDistance = new GUIContent("Scattering Distance", "Determines the shape of the profile, and the blur radius of the filter per color channel. Alpha is ignored.");
public readonly GUIContent sssProfileTransmissionTint = new GUIContent("Transmission tint", "Color which tints transmitted light. Alpha is ignored.");
public readonly GUIContent sssProfileMaxRadius = new GUIContent("Max Radius", "Effective radius of the filter (in millimeters). The blur is energy-preserving, so a wide filter results in a large area with small contributions of individual samples. Reducing the distance increases the sharpness of the result.");
public readonly GUIContent sssTexturingMode = new GUIContent("Texturing Mode", "Specifies when the diffuse texture should be applied.");
public readonly GUIContent[] sssTexturingModeOptions = new GUIContent[2]
{
new GUIContent("Pre- and post-scatter", "Texturing is performed during both the lighting and the SSS passes. Slightly blurs the diffuse texture. Choose this mode if your diffuse texture contains little to no SSS lighting."),
new GUIContent("Post-scatter", "Texturing is performed only during the SSS pass. Effectively preserves the sharpness of the diffuse texture. Choose this mode if your diffuse texture already contains SSS lighting (e.g. a photo of skin).")
};
public readonly GUIContent sssProfileTransmissionMode = new GUIContent("Transmission Mode", "Configures the simulation of light passing through thin objects. Depends on the thickness value (which is applied in the normal direction).");
public readonly GUIContent[] sssTransmissionModeOptions = new GUIContent[3]
{
new GUIContent("None", "Disables transmission. Choose this mode for completely opaque, or very thick translucent objects."),
new GUIContent("Thin Object", "Choose this mode for thin objects, such as paper or leaves. Transmitted light reuses the shadowing state of the surface."),
new GUIContent("Regular", "Choose this mode for moderately thick objects. For performance reasons, transmitted light ignores occlusion (shadows).")
};
public readonly GUIContent sssProfileMinMaxThickness = new GUIContent("Min-Max Thickness", "Shows the values of the thickness remap below (in millimeters).");
public readonly GUIContent sssProfileThicknessRemap = new GUIContent("Thickness Remap", "Remaps the thickness parameter from [0, 1] to the desired range (in millimeters).");
public readonly GUIContent sssProfileWorldScale = new GUIContent("World Scale", "Size of the world unit in meters.");
// Old SSS Model >>>
public readonly GUIContent sssProfileScatterDistance1 = new GUIContent("Scattering Distance #1", "The radius (in centimeters) of the 1st Gaussian filter, one per color channel. Alpha is ignored. The blur is energy-preserving, so a wide filter results in a large area with small contributions of individual samples. Smaller values increase the sharpness.");
public readonly GUIContent sssProfileScatterDistance2 = new GUIContent("Scattering Distance #2", "The radius (in centimeters) of the 2nd Gaussian filter, one per color channel. Alpha is ignored. The blur is energy-preserving, so a wide filter results in a large area with small contributions of individual samples. Smaller values increase the sharpness.");
public readonly GUIContent sssProfileLerpWeight = new GUIContent("Filter Interpolation", "Controls linear interpolation between the two Gaussian filters.");
// <<< Old SSS Model
public readonly GUIStyle centeredMiniBoldLabel = new GUIStyle(GUI.skin.label);
public Styles()
{
centeredMiniBoldLabel.alignment = TextAnchor.MiddleCenter;
centeredMiniBoldLabel.fontSize = 10;
centeredMiniBoldLabel.fontStyle = FontStyle.Bold;
}
}
private static Styles styles
{
get
{
if (s_Styles == null)
{
s_Styles = new Styles();
}
return s_Styles;
}
}
private static Styles s_Styles = null;
private RenderTexture m_ProfileImage, m_TransmittanceImage;
private Material m_ProfileMaterial, m_TransmittanceMaterial;
private SerializedProperty m_ScatteringDistance, m_MaxRadius, m_ShapeParam, m_TransmissionTint,
m_TexturingMode, m_TransmissionMode, m_ThicknessRemap, m_WorldScale;
// Old SSS Model >>>
private SerializedProperty m_ScatterDistance1, m_ScatterDistance2, m_LerpWeight;
// <<< Old SSS Model
void OnEnable()
{
m_ScatteringDistance = serializedObject.FindProperty("scatteringDistance");
m_MaxRadius = serializedObject.FindProperty("m_MaxRadius");
m_ShapeParam = serializedObject.FindProperty("m_ShapeParam");
m_TransmissionTint = serializedObject.FindProperty("transmissionTint");
m_TexturingMode = serializedObject.FindProperty("texturingMode");
m_TransmissionMode = serializedObject.FindProperty("transmissionMode");
m_ThicknessRemap = serializedObject.FindProperty("thicknessRemap");
m_WorldScale = serializedObject.FindProperty("worldScale");
// Old SSS Model >>>
m_ScatterDistance1 = serializedObject.FindProperty("scatterDistance1");
m_ScatterDistance2 = serializedObject.FindProperty("scatterDistance2");
m_LerpWeight = serializedObject.FindProperty("lerpWeight");
// <<< Old SSS Model
// These shaders don't need to be reference by RenderPipelineResource as they are not use at runtime
m_ProfileMaterial = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/DrawSssProfile");
m_TransmittanceMaterial = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/DrawTransmittanceGraph");
m_ProfileImage = new RenderTexture(256, 256, 0, RenderTextureFormat.DefaultHDR);
m_TransmittanceImage = new RenderTexture( 16, 256, 0, RenderTextureFormat.DefaultHDR);
}
public override void OnInspectorGUI()
{
serializedObject.Update();
// Old SSS Model >>>
bool useDisneySSS;
{
HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
useDisneySSS = hdPipeline.sssSettings.useDisneySSS;
}
// <<< Old SSS Model
EditorGUI.BeginChangeCheck();
{
if (useDisneySSS)
{
EditorGUILayout.PropertyField(m_ScatteringDistance, styles.sssProfileScatteringDistance);
GUI.enabled = false;
EditorGUILayout.PropertyField(m_MaxRadius, styles.sssProfileMaxRadius);
GUI.enabled = true;
}
else
{
EditorGUILayout.PropertyField(m_ScatterDistance1, styles.sssProfileScatterDistance1);
EditorGUILayout.PropertyField(m_ScatterDistance2, styles.sssProfileScatterDistance2);
EditorGUILayout.PropertyField(m_LerpWeight, styles.sssProfileLerpWeight);
}
m_TexturingMode.intValue = EditorGUILayout.Popup(styles.sssTexturingMode, m_TexturingMode.intValue, styles.sssTexturingModeOptions);
m_TransmissionMode.intValue = EditorGUILayout.Popup(styles.sssProfileTransmissionMode, m_TransmissionMode.intValue, styles.sssTransmissionModeOptions);
EditorGUILayout.PropertyField(m_TransmissionTint, styles.sssProfileTransmissionTint);
EditorGUILayout.PropertyField(m_ThicknessRemap, styles.sssProfileMinMaxThickness);
Vector2 thicknessRemap = m_ThicknessRemap.vector2Value;
EditorGUILayout.MinMaxSlider(styles.sssProfileThicknessRemap, ref thicknessRemap.x, ref thicknessRemap.y, 0.0f, 50.0f);
m_ThicknessRemap.vector2Value = thicknessRemap;
EditorGUILayout.PropertyField(m_WorldScale, styles.sssProfileWorldScale);
EditorGUILayout.Space();
EditorGUILayout.LabelField(styles.sssProfilePreview0, styles.centeredMiniBoldLabel);
EditorGUILayout.LabelField(styles.sssProfilePreview1, EditorStyles.centeredGreyMiniLabel);
EditorGUILayout.LabelField(styles.sssProfilePreview2, EditorStyles.centeredGreyMiniLabel);
EditorGUILayout.LabelField(styles.sssProfilePreview3, EditorStyles.centeredGreyMiniLabel);
EditorGUILayout.Space();
}
float r = m_MaxRadius.floatValue;
Vector3 S = m_ShapeParam.vector3Value;
Vector4 T = m_TransmissionTint.colorValue;
Vector2 R = m_ThicknessRemap.vector2Value;
bool transmissionEnabled = m_TransmissionMode.intValue != (int)SubsurfaceScatteringProfile.TransmissionMode.None;
m_ProfileMaterial.SetFloat(HDShaderIDs._MaxRadius, r);
m_ProfileMaterial.SetVector(HDShaderIDs._ShapeParam, S);
// Old SSS Model >>>
CoreUtils.SelectKeyword(m_ProfileMaterial, "SSS_MODEL_DISNEY", "SSS_MODEL_BASIC", useDisneySSS);
// Apply the three-sigma rule, and rescale.
float s = (1.0f / 3.0f) * SssConstants.SSS_BASIC_DISTANCE_SCALE;
float rMax = Mathf.Max(m_ScatterDistance1.colorValue.r, m_ScatterDistance1.colorValue.g, m_ScatterDistance1.colorValue.b,
m_ScatterDistance2.colorValue.r, m_ScatterDistance2.colorValue.g, m_ScatterDistance2.colorValue.b);
Vector4 stdDev1 = s * m_ScatterDistance1.colorValue;
Vector4 stdDev2 = s * m_ScatterDistance2.colorValue;
m_ProfileMaterial.SetVector(HDShaderIDs._StdDev1, stdDev1);
m_ProfileMaterial.SetVector(HDShaderIDs._StdDev2, stdDev2);
m_ProfileMaterial.SetFloat(HDShaderIDs._LerpWeight, m_LerpWeight.floatValue);
m_ProfileMaterial.SetFloat(HDShaderIDs._MaxRadius, rMax);
// <<< Old SSS Model
// Draw the profile.
EditorGUI.DrawPreviewTexture(GUILayoutUtility.GetRect(256, 256), m_ProfileImage, m_ProfileMaterial, ScaleMode.ScaleToFit, 1.0f);
EditorGUILayout.Space();
EditorGUILayout.LabelField(styles.sssTransmittancePreview0, styles.centeredMiniBoldLabel);
EditorGUILayout.LabelField(styles.sssTransmittancePreview1, EditorStyles.centeredGreyMiniLabel);
EditorGUILayout.LabelField(styles.sssTransmittancePreview2, EditorStyles.centeredGreyMiniLabel);
EditorGUILayout.Space();
// Old SSS Model >>>
// Multiply by 0.1 to convert from millimeters to centimeters. Apply the distance scale.
float a = 0.1f * SssConstants.SSS_BASIC_DISTANCE_SCALE;
Vector4 halfRcpVarianceAndWeight1 = new Vector4(a * a * 0.5f / (stdDev1.x * stdDev1.x), a * a * 0.5f / (stdDev1.y * stdDev1.y), a * a * 0.5f / (stdDev1.z * stdDev1.z), 4 * (1.0f - m_LerpWeight.floatValue));
Vector4 halfRcpVarianceAndWeight2 = new Vector4(a * a * 0.5f / (stdDev2.x * stdDev2.x), a * a * 0.5f / (stdDev2.y * stdDev2.y), a * a * 0.5f / (stdDev2.z * stdDev2.z), 4 * m_LerpWeight.floatValue);
m_TransmittanceMaterial.SetVector(HDShaderIDs._HalfRcpVarianceAndWeight1, halfRcpVarianceAndWeight1);
m_TransmittanceMaterial.SetVector(HDShaderIDs._HalfRcpVarianceAndWeight2, halfRcpVarianceAndWeight2);
// <<< Old SSS Model
m_TransmittanceMaterial.SetVector(HDShaderIDs._ShapeParam, S);
m_TransmittanceMaterial.SetVector(HDShaderIDs._TransmissionTint, transmissionEnabled ? T : Vector4.zero);
m_TransmittanceMaterial.SetVector(HDShaderIDs._ThicknessRemap, R);
// Draw the transmittance graph.
EditorGUI.DrawPreviewTexture(GUILayoutUtility.GetRect(16, 16), m_TransmittanceImage, m_TransmittanceMaterial, ScaleMode.ScaleToFit, 16.0f);
serializedObject.ApplyModifiedProperties();
if (EditorGUI.EndChangeCheck())
{
HDRenderPipeline hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
// Validate each individual asset and update caches.
hdPipeline.sssSettings.OnValidate();
}
}
}
#endif
}

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


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

1
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/UnlitUI.cs


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

1
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.cs


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

2
ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/HDRenderPipelineResources.asset


type: 3}
gaussianPyramidCS: {fileID: 7200000, guid: 6dba4103d23a7904fbc49099355aff3e, type: 3}
depthPyramidCS: {fileID: 7200000, guid: 64a553bb564274041906f78ffba955e4, type: 3}
copyChannelCS: {fileID: 7200000, guid: 4e910cec38a1ec640a03324015e036d0, type: 3}
copyChannelCS: {fileID: 7200000, guid: a68d8aaeb0956234d94e389f196381ee, type: 3}
clearDispatchIndirectShader: {fileID: 7200000, guid: fc1f553acb80a6446a32d33e403d0656,
type: 3}
buildDispatchIndirectShader: {fileID: 7200000, guid: 4eb1b418be7044c40bb5200496c50f14,

2
ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/HDRenderPipelineResources.asset.meta


fileFormatVersion: 2
guid: 42086e81f4f0c724f96f7f09cc995354
timeCreated: 1507102386
timeCreated: 1507124092
licenseType: Pro
NativeFormatImporter:
externalObjects: {}

73
ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/RenderPipelineResources.cs


{
public class RenderPipelineResources : ScriptableObject
{
#if UNITY_EDITOR
public static string GetRenderPipelineResourcesPath()
{
return HDUtils.GetHDRenderPipelinePath() + "RenderPipelineResources/HDRenderPipelineResources.asset";
}
// TODO skybox/cubemap
[UnityEditor.MenuItem("RenderPipeline/HDRenderPipeline/Create Resources Asset", false, 15)]
static void CreateRenderPipelineResources()
{
var instance = CreateInstance<RenderPipelineResources>();
string HDRenderPipelinePath = HDUtils.GetHDRenderPipelinePath();
string PostProcessingPath = HDUtils.GetPostProcessingPath();
instance.debugDisplayLatlongShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Debug/DebugDisplayLatlong.Shader");
instance.debugViewMaterialGBufferShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Debug/DebugViewMaterialGBuffer.Shader");
instance.debugViewTilesShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Debug/DebugViewTiles.Shader");
instance.debugFullScreenShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Debug/DebugFullScreen.Shader");
instance.deferredShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Lighting/Deferred.Shader");
instance.screenSpaceAmbientOcclusionShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Lighting/AmbientOcclusion/ScreenSpaceAmbientOcclusion.Shader");
instance.subsurfaceScatteringCS = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Material/Lit/Resources/SubsurfaceScattering.compute");
instance.volumetricLightingCS = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/Volumetrics/Resources/VolumetricLighting.compute");
instance.gaussianPyramidCS = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(PostProcessingPath + "Shaders/Builtins/GaussianDownsample.compute");
instance.depthPyramidCS = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/DepthDownsample.compute");
instance.copyChannelCS = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/CopyChannel.compute");
instance.clearDispatchIndirectShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/cleardispatchindirect.compute");
instance.buildDispatchIndirectShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/builddispatchindirect.compute");
instance.buildScreenAABBShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/scrbound.compute");
instance.buildPerTileLightListShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/lightlistbuild.compute");
instance.buildPerBigTileLightListShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/lightlistbuild-bigtile.compute");
instance.buildPerVoxelLightListShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/lightlistbuild-clustered.compute");
instance.buildMaterialFlagsShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/materialflags.compute");
instance.deferredComputeShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/Deferred.compute");
instance.deferredDirectionalShadowComputeShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/DeferredDirectionalShadow.compute");
// SceneSettings
// These shaders don't need to be reference by RenderPipelineResource as they are not use at runtime (only to draw in editor)
// instance.drawSssProfile = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "SceneSettings/DrawSssProfile.shader");
// instance.drawTransmittanceGraphShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "SceneSettings/DrawTransmittanceGraph.shader");
instance.cameraMotionVectors = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "RenderPipelineResources/CameraMotionVectors.shader");
// Sky
instance.blitCubemap = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Sky/BlitCubemap.shader");
instance.buildProbabilityTables = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Sky/BuildProbabilityTables.compute");
instance.computeGgxIblSampleData = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(HDRenderPipelinePath + "Sky/ComputeGgxIblSampleData.compute");
instance.GGXConvolve = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "Sky/GGXConvolve.shader");
// Skybox/Cubemap is a builtin shader, must use Sahder.Find to access it. It is fine because we are in the editor
instance.skyboxCubemap = Shader.Find("Skybox/Cubemap");
UnityEditor.AssetDatabase.CreateAsset(instance, GetRenderPipelineResourcesPath());
UnityEditor.AssetDatabase.SaveAssets();
UnityEditor.AssetDatabase.Refresh();
}
#endif
// Debug
public Shader debugDisplayLatlongShader;
public Shader debugViewMaterialGBufferShader;

public Shader GGXConvolve;
public Shader skyboxCubemap;
public int copyChannelKernel_xyzw2x { get; private set; }
public void OnEnable()
{
copyChannelKernel_xyzw2x = -1;
if (copyChannelCS != null)
{
copyChannelKernel_xyzw2x = copyChannelCS.FindKernel("KSampleCopy4_1_x");
}
}
}
}

4
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Editor/CommonSettingsEditor.cs


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

2
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawSssProfile.shader


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

2
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader


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

2
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/SceneSettings.cs


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

1
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/SceneSettingsManager.cs


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

1
ScriptableRenderPipeline/HDRenderPipeline/ShaderConfig.cs


using UnityEngine;
using UnityEngine.Rendering;
using System;
//-----------------------------------------------------------------------------
// Configuration

1
ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPass.cs


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

6
ScriptableRenderPipeline/HDRenderPipeline/Sky/GGXConvolve.shader


{
Pass
{
Cull Off
ZTest Always
ZTest Always
Blend One Zero
Cull Off
Blend Off
HLSLPROGRAM
#pragma target 4.5

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Editor/HDRISkyEditor.cs


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

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


using UnityEngine.Rendering;
private HDRISkySettings m_HdriSkyParams;
MaterialPropertyBlock m_PropertyBlock;
HDRISkySettings m_HdriSkyParams;
m_PropertyBlock = new MaterialPropertyBlock();
}
public override void Build()

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

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


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

4
ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Resources/SkyHDRI.shader


{
ZWrite Off
ZTest Always
Blend One Zero
Blend Off
Cull Off
HLSLPROGRAM

{
ZWrite Off
ZTest LEqual
Blend One Zero
Blend Off
Cull Off
HLSLPROGRAM

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/Editor/ProceduralSkyEditor.cs


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

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkyRenderer.cs


using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class ProceduralSkyRenderer : SkyRenderer

41
ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkySettings.cs


{
return new ProceduralSkyRenderer(this);
}
public override int GetHashCode()
{
int hash = base.GetHashCode();
unchecked
{
hash = hash * 23 + worldMieColorIntensity.GetHashCode();
hash = worldMieColorRamp != null ? hash * 23 + worldMieColorRamp.GetHashCode() : hash;
hash = hash * 23 + worldMieDensity.GetHashCode();
hash = hash * 23 + worldMieExtinctionFactor.GetHashCode();
hash = hash * 23 + worldMieNearScatterPush.GetHashCode();
hash = hash * 23 + worldMiePhaseAnisotropy.GetHashCode();
hash = hash * 23 + worldNormalDistance.GetHashCode();
hash = hash * 23 + worldRayleighColorIntensity.GetHashCode();
hash = worldRayleighColorRamp != null ? hash * 23 + worldRayleighColorRamp.GetHashCode() : hash;
hash = hash * 23 + worldRayleighDensity.GetHashCode();
hash = hash * 23 + worldRayleighExtinctionFactor.GetHashCode();
hash = hash * 23 + worldRayleighIndirectScatter.GetHashCode();
hash = hash * 23 + worldRayleighNearScatterPush.GetHashCode();
hash = hash * 23 + heightDistance.GetHashCode();
hash = hash * 23 + heightExtinctionFactor.GetHashCode();
hash = hash * 23 + heightMieDensity.GetHashCode();
hash = hash * 23 + heightMieNearScatterPush.GetHashCode();
hash = hash * 23 + heightNormalDistance.GetHashCode();
hash = hash * 23 + heightPlaneShift.GetHashCode();
hash = hash * 23 + heightRayleighColor.GetHashCode();
hash = hash * 23 + heightRayleighDensity.GetHashCode();
hash = hash * 23 + heightRayleighIntensity.GetHashCode();
hash = hash * 23 + heightRayleighNearScatterPush.GetHashCode();
hash = hash * 23 + heightSeaLevel.GetHashCode();
hash = skyHDRI != null ? hash * 23 + skyHDRI.GetHashCode() : hash;
hash = hash * 23 + worldScaleExponent.GetHashCode();
hash = hash * 23 + maxSkyDistance.GetHashCode();
hash = hash * 23 + debugMode.GetHashCode();
}
return hash;
}
}
}

50
ScriptableRenderPipeline/HDRenderPipeline/Sky/RuntimeFilterIBL.cs


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

RenderTexture m_GgxIblSampleData = null;
int k_GgxIblMaxSampleCount = TextureCache.isMobileBuildTarget ? 34 : 89; // Width
RenderTexture m_GgxIblSampleData;
int m_GgxIblMaxSampleCount = TextureCache.isMobileBuildTarget ? 34 : 89; // Width
ComputeShader m_ComputeGgxIblSampleDataCS = null;
ComputeShader m_ComputeGgxIblSampleDataCS;
ComputeShader m_BuildProbabilityTablesCS = null;
ComputeShader m_BuildProbabilityTablesCS;
Material m_GgxConvolveMaterial = null; // Convolves a cubemap with GGX
Material m_GgxConvolveMaterial; // Convolves a cubemap with GGX
bool m_SupportMIS = !TextureCache.isMobileBuildTarget;
RenderPipelineResources m_RenderPipelinesResources;
RenderPipelineResources m_RenderPipelinesResources;
public bool supportMis
{
get { return !TextureCache.isMobileBuildTarget; }
}
public IBLFilterGGX(RenderPipelineResources renderPipelinesResources)
{

return m_GgxIblSampleData != null;
}
public bool SupportMIS
{
get { return m_SupportMIS; }
}
public void Initialize(CommandBuffer cmd)
{
if (!m_ComputeGgxIblSampleDataCS)

}
if (!m_BuildProbabilityTablesCS && SupportMIS)
if (!m_BuildProbabilityTablesCS && supportMis)
{
m_BuildProbabilityTablesCS = m_RenderPipelinesResources.buildProbabilityTables;
m_ConditionalDensitiesKernel = m_BuildProbabilityTablesCS.FindKernel("ComputeConditionalDensities");

if (!m_GgxIblSampleData)
{
m_GgxIblSampleData = new RenderTexture(k_GgxIblMaxSampleCount, k_GgxIblMipCountMinusOne, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
m_GgxIblSampleData = new RenderTexture(m_GgxIblMaxSampleCount, k_GgxIblMipCountMinusOne, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
m_GgxIblSampleData.useMipMap = false;
m_GgxIblSampleData.autoGenerateMips = false;
m_GgxIblSampleData.enableRandomWrite = true;

for (int mip = 1; mip < ((int)EnvConstants.SpecCubeLodStep + 1); ++mip)
{
string sampleName = String.Format("Filter Cubemap Mip {0}", mip);
cmd.BeginSample(sampleName);
for (int face = 0; face < 6; ++face)
using (new ProfilingSample(cmd, "Filter Cubemap Mip {0}", mip))
Vector4 faceSize = new Vector4(source.width >> mip, source.height >> mip, 1.0f / (source.width >> mip), 1.0f / (source.height >> mip));
Matrix4x4 transform = SkyManager.ComputePixelCoordToWorldSpaceViewDirectionMatrix(0.5f * Mathf.PI, faceSize, worldToViewMatrices[face], true);
for (int face = 0; face < 6; ++face)
{
var faceSize = new Vector4(source.width >> mip, source.height >> mip, 1.0f / (source.width >> mip), 1.0f / (source.height >> mip));
var transform = SkyManager.ComputePixelCoordToWorldSpaceViewDirectionMatrix(0.5f * Mathf.PI, faceSize, worldToViewMatrices[face], true);
MaterialPropertyBlock props = new MaterialPropertyBlock();
props.SetFloat("_Level", mip);
props.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, transform);
var props = new MaterialPropertyBlock();
props.SetFloat("_Level", mip);
props.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, transform);
CoreUtils.SetRenderTarget(cmd, target, ClearFlag.None, mip, (CubemapFace)face);
CoreUtils.DrawFullScreen(cmd, m_GgxConvolveMaterial, props);
CoreUtils.SetRenderTarget(cmd, target, ClearFlag.None, mip, (CubemapFace)face);
CoreUtils.DrawFullScreen(cmd, m_GgxConvolveMaterial, props);
}
cmd.EndSample(sampleName);
}
}

178
ScriptableRenderPipeline/HDRenderPipeline/Sky/SkyManager.cs


public class SkyManager
{
RenderTexture m_SkyboxCubemapRT = null;
RenderTexture m_SkyboxGGXCubemapRT = null;
RenderTexture m_SkyboxMarginalRowCdfRT = null;
RenderTexture m_SkyboxConditionalCdfRT = null;
RenderTexture m_SkyboxCubemapRT;
RenderTexture m_SkyboxGGXCubemapRT;
RenderTexture m_SkyboxMarginalRowCdfRT;
RenderTexture m_SkyboxConditionalCdfRT;
Material m_StandardSkyboxMaterial = null; // This is the Unity standard skybox material. Used to pass the correct cubemap to Enlighten.
Material m_BlitCubemapMaterial = null;
Material m_StandardSkyboxMaterial; // This is the Unity standard skybox material. Used to pass the correct cubemap to Enlighten.
Material m_BlitCubemapMaterial;
IBLFilterGGX m_iblFilterGgx = null;
IBLFilterGGX m_iblFilterGgx;
Vector4 m_CubemapScreenSize;
Matrix4x4[] m_faceWorldToViewMatrixMatrices = new Matrix4x4[6];

BuiltinSkyParameters m_BuiltinParameters = new BuiltinSkyParameters();
SkyRenderer m_Renderer = null;
SkyRenderer m_Renderer;
bool m_NeedLowLevelUpdateEnvironment = false;
bool m_NeedLowLevelUpdateEnvironment;
float m_CurrentUpdateTime = 0.0f;
float m_CurrentUpdateTime;
// Ref: https://msdn.microsoft.com/en-us/library/windows/desktop/bb204881(v=vs.85).aspx
readonly Vector3[] m_LookAtList =
{
new Vector3(1.0f, 0.0f, 0.0f),
new Vector3(-1.0f, 0.0f, 0.0f),
new Vector3(0.0f, 1.0f, 0.0f),
new Vector3(0.0f, -1.0f, 0.0f),
new Vector3(0.0f, 0.0f, 1.0f),
new Vector3(0.0f, 0.0f, -1.0f),
};
private SkySettings m_SkySettings;
readonly Vector3[] m_UpVectorList =
{
new Vector3(0.0f, 1.0f, 0.0f),
new Vector3(0.0f, 1.0f, 0.0f),
new Vector3(0.0f, 0.0f, -1.0f),
new Vector3(0.0f, 0.0f, 1.0f),
new Vector3(0.0f, 1.0f, 0.0f),
new Vector3(0.0f, 1.0f, 0.0f),
};
SkySettings m_SkySettings;
public SkySettings skySettings
{
set

void RebuildTextures(SkySettings skySettings)
{
int resolution = 256;
// Parameters not set yet. We need them for the resolution.
if (skySettings != null)
resolution = (int)skySettings.resolution;

if (m_SkyboxCubemapRT == null)
{
m_SkyboxCubemapRT = new RenderTexture(resolution, resolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
m_SkyboxCubemapRT.dimension = TextureDimension.Cube;
m_SkyboxCubemapRT.useMipMap = true;
m_SkyboxCubemapRT.autoGenerateMips = false; // We will generate regular mipmap for filtered importance sampling manually
m_SkyboxCubemapRT.filterMode = FilterMode.Trilinear;
m_SkyboxCubemapRT = new RenderTexture(resolution, resolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear)
{
dimension = TextureDimension.Cube,
useMipMap = true,
autoGenerateMips = false, // We will generate regular mipmap for filtered importance sampling manually
filterMode = FilterMode.Trilinear
};
m_SkyboxGGXCubemapRT = new RenderTexture(resolution, resolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
m_SkyboxGGXCubemapRT.dimension = TextureDimension.Cube;
m_SkyboxGGXCubemapRT.useMipMap = true;
m_SkyboxGGXCubemapRT.autoGenerateMips = false;
m_SkyboxGGXCubemapRT.filterMode = FilterMode.Trilinear;
m_SkyboxGGXCubemapRT = new RenderTexture(resolution, resolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear)
{
dimension = TextureDimension.Cube,
useMipMap = true,
autoGenerateMips = false,
filterMode = FilterMode.Trilinear
};
m_SkyboxGGXCubemapRT.Create();
if (m_useMIS)

// + 1 because we store the value of the integral of the cubemap at the end of the texture.
m_SkyboxMarginalRowCdfRT = new RenderTexture(height + 1, 1, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear);
m_SkyboxMarginalRowCdfRT.useMipMap = false;
m_SkyboxMarginalRowCdfRT.autoGenerateMips = false;
m_SkyboxMarginalRowCdfRT.enableRandomWrite = true;
m_SkyboxMarginalRowCdfRT.filterMode = FilterMode.Point;
m_SkyboxMarginalRowCdfRT = new RenderTexture(height + 1, 1, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear)
{
useMipMap = false,
autoGenerateMips = false,
enableRandomWrite = true,
filterMode = FilterMode.Point
};
m_SkyboxConditionalCdfRT = new RenderTexture(width, height, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear);
m_SkyboxConditionalCdfRT.useMipMap = false;
m_SkyboxConditionalCdfRT.autoGenerateMips = false;
m_SkyboxConditionalCdfRT.enableRandomWrite = true;
m_SkyboxConditionalCdfRT.filterMode = FilterMode.Point;
m_SkyboxConditionalCdfRT = new RenderTexture(width, height, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear)
{
useMipMap = false,
autoGenerateMips = false,
enableRandomWrite = true,
filterMode = FilterMode.Point
};
m_SkyboxConditionalCdfRT.Create();
}

{
if (!m_SkySettings) return;
Matrix4x4 cubeProj = Matrix4x4.Perspective(90.0f, 1.0f, nearPlane, farPlane);
// Ref: https://msdn.microsoft.com/en-us/library/windows/desktop/bb204881(v=vs.85).aspx
Vector3[] lookAtList =
{
new Vector3(1.0f, 0.0f, 0.0f),
new Vector3(-1.0f, 0.0f, 0.0f),
new Vector3(0.0f, 1.0f, 0.0f),
new Vector3(0.0f, -1.0f, 0.0f),
new Vector3(0.0f, 0.0f, 1.0f),
new Vector3(0.0f, 0.0f, -1.0f),
};
Vector3[] upVectorList =
{
new Vector3(0.0f, 1.0f, 0.0f),
new Vector3(0.0f, 1.0f, 0.0f),
new Vector3(0.0f, 0.0f, -1.0f),
new Vector3(0.0f, 0.0f, 1.0f),
new Vector3(0.0f, 1.0f, 0.0f),
new Vector3(0.0f, 1.0f, 0.0f),
};
var cubeProj = Matrix4x4.Perspective(90.0f, 1.0f, nearPlane, farPlane);
Matrix4x4 lookAt = Matrix4x4.LookAt(Vector3.zero, lookAtList[i], upVectorList[i]);
Matrix4x4 worldToView = lookAt * Matrix4x4.Scale(new Vector3(1.0f, 1.0f, -1.0f)); // Need to scale -1.0 on Z to match what is being done in the camera.wolrdToCameraMatrix API. ...
Vector4 screenSize = new Vector4((int)m_SkySettings.resolution, (int)m_SkySettings.resolution, 1.0f / (int)m_SkySettings.resolution, 1.0f / (int)m_SkySettings.resolution);
var lookAt = Matrix4x4.LookAt(Vector3.zero, m_LookAtList[i], m_UpVectorList[i]);
var worldToView = lookAt * Matrix4x4.Scale(new Vector3(1.0f, 1.0f, -1.0f)); // Need to scale -1.0 on Z to match what is being done in the camera.wolrdToCameraMatrix API. ...
var screenSize = new Vector4((int)m_SkySettings.resolution, (int)m_SkySettings.resolution, 1.0f / (int)m_SkySettings.resolution, 1.0f / (int)m_SkySettings.resolution);
m_faceWorldToViewMatrixMatrices[i] = worldToView;
m_facePixelCoordToViewDirMatrices[i] = ComputePixelCoordToWorldSpaceViewDirectionMatrix(0.5f * Mathf.PI, screenSize, worldToView, true);

float m00 = -2.0f * screenSize.z * m20;
float m11 = -2.0f * screenSize.w * m21;
float m33 = -1.0f;
if (renderToCubemap)
{
// Flip Y.

Matrix4x4 viewSpaceRasterTransform = new Matrix4x4(new Vector4( m00, 0.0f, 0.0f, 0.0f),
new Vector4(0.0f, m11, 0.0f, 0.0f),
new Vector4( m20, m21, m33, 0.0f),
new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
var viewSpaceRasterTransform = new Matrix4x4(new Vector4( m00, 0.0f, 0.0f, 0.0f),
new Vector4(0.0f, m11, 0.0f, 0.0f),
new Vector4( m20, m21, m33, 0.0f),
new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
Vector4 homogeneousZero = new Vector4(0, 0, 0, 1);
var homogeneousZero = new Vector4(0, 0, 0, 1);
worldToViewMatrix.SetColumn(3, homogeneousZero);
// Flip the Z to make the coordinate system left-handed.

return m_Renderer != null && m_Renderer.IsSkyValid();
}
private void RenderSkyToCubemap(BuiltinSkyParameters builtinParams, SkySettings skySettings, RenderTexture target)
void RenderSkyToCubemap(BuiltinSkyParameters builtinParams, SkySettings skySettings, RenderTexture target)
{
for (int i = 0; i < 6; ++i)
{

builtinParams.commandBuffer.GenerateMips(target);
}
private void BlitCubemap(CommandBuffer cmd, Cubemap source, RenderTexture dest)
void BlitCubemap(CommandBuffer cmd, Cubemap source, RenderTexture dest)
MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
var propertyBlock = new MaterialPropertyBlock();
for (int i = 0; i < 6; ++i)
{

cmd.GenerateMips(dest);
}
private void RenderCubemapGGXConvolution(CommandBuffer cmd, BuiltinSkyParameters builtinParams, SkySettings skyParams, Texture input, RenderTexture target)
void RenderCubemapGGXConvolution(CommandBuffer cmd, BuiltinSkyParameters builtinParams, SkySettings skyParams, Texture input, RenderTexture target)
{
using (new ProfilingSample(cmd, "Update Env: GGX Convolution"))
{

}
if (!m_iblFilterGgx.IsInitialized())
{
}
// Copy the first mip
using (new ProfilingSample(cmd, "Copy Original Mip"))

using (new ProfilingSample(cmd, "GGX Convolution"))
{
if (m_useMIS && m_iblFilterGgx.SupportMIS)
{
if (m_useMIS && m_iblFilterGgx.supportMis)
}
{
}
}
}
}

m_StandardSkyboxMaterial.SetTexture("_Tex", m_SkyboxCubemapRT);
RenderSettings.skybox = IsSkyValid() ? m_StandardSkyboxMaterial : null; // Setup this material as the default to be use in RenderSettings
RenderSettings.ambientIntensity = 1.0f; // fix this to 1, this parameter should not exist!
RenderSettings.ambientMode = UnityEngine.Rendering.AmbientMode.Skybox; // Force skybox for our HDRI
RenderSettings.ambientMode = AmbientMode.Skybox; // Force skybox for our HDRI
RenderSettings.reflectionIntensity = 1.0f;
RenderSettings.customReflection = null;
DynamicGI.UpdateEnvironment();

m_BuiltinParameters.screenSize = m_CubemapScreenSize;
m_BuiltinParameters.cameraPosWS = camera.camera.transform.position;
if (
m_UpdatedFramesRequired > 0 ||
(skySettings.updateMode == EnvironementUpdateMode.OnChanged && skySettings.GetHash() != m_SkyParametersHash) ||
(skySettings.updateMode == EnvironementUpdateMode.Realtime && m_CurrentUpdateTime > skySettings.updatePeriod)
)
if (m_UpdatedFramesRequired > 0 ||
(skySettings.updateMode == EnvironementUpdateMode.OnChanged && skySettings.GetHashCode() != m_SkyParametersHash) ||
(skySettings.updateMode == EnvironementUpdateMode.Realtime && m_CurrentUpdateTime > skySettings.updatePeriod))
{
using (new ProfilingSample(cmd, "Sky Environment Pass"))
{

m_NeedLowLevelUpdateEnvironment = true;
m_UpdatedFramesRequired--;
m_SkyParametersHash = skySettings.GetHash();
m_SkyParametersHash = skySettings.GetHashCode();
m_SkyboxCubemapRT.imageContentsHash = new Hash128((uint)skySettings.GetHash(), 0, 0, 0);
m_SkyboxCubemapRT.imageContentsHash = new Hash128((uint)skySettings.GetHashCode(), 0, 0, 0);
#endif
}
}

int resolution = (int)m_SkySettings.resolution;
RenderTexture tempRT = new RenderTexture(resolution * 6, resolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
tempRT.dimension = TextureDimension.Tex2D;
tempRT.useMipMap = false;
tempRT.autoGenerateMips = false;
tempRT.filterMode = FilterMode.Trilinear;
var tempRT = new RenderTexture(resolution * 6, resolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear)
{
dimension = TextureDimension.Tex2D,
useMipMap = false,
autoGenerateMips = false,
filterMode = FilterMode.Trilinear
};
Texture2D temp = new Texture2D(resolution * 6, resolution, TextureFormat.RGBAFloat, false);
Texture2D result = new Texture2D(resolution * 6, resolution, TextureFormat.RGBAFloat, false);
var temp = new Texture2D(resolution * 6, resolution, TextureFormat.RGBAFloat, false);
var result = new Texture2D(resolution * 6, resolution, TextureFormat.RGBAFloat, false);
// Note: We need to invert in Y the cubemap faces because the current sky cubemap is inverted (because it's a RT)
// So to invert it again so that it's a proper cubemap image we need to do it in several steps because ReadPixels does not have scale parameters:

5
ScriptableRenderPipeline/HDRenderPipeline/Sky/SkyRenderer.cs


using System;
abstract public class SkyRenderer
public abstract class SkyRenderer
{
public abstract void Build();
public abstract void Cleanup();

35
ScriptableRenderPipeline/HDRenderPipeline/Sky/SkySettings.cs


using System.Reflection;
using System.Linq;
protected class Unhashed : System.Attribute {}
[Range(0,360)]
public float rotation = 0.0f;
public float exposure = 0.0f;

public float updatePeriod = 0.0f;
public Cubemap lightingOverride = null;
private FieldInfo[] m_Properties;
protected void OnEnable()
{
// Enumerate properties in order to compute the hash more quickly later on.
m_Properties = GetType()
.GetFields(BindingFlags.Public | BindingFlags.Instance)
.ToArray();
}
public int GetHash()
public override int GetHashCode()
foreach (var p in m_Properties)
{
bool unhashedAttribute = p.GetCustomAttributes(typeof(Unhashed), true).Length != 0;
object obj = p.GetValue(this);
if (obj != null && !unhashedAttribute) // Sometimes it can be a null reference.
hash = hash * 23 + obj.GetHashCode();
}
hash = hash * 23 + rotation.GetHashCode();
hash = hash * 23 + exposure.GetHashCode();
hash = hash * 23 + multiplier.GetHashCode();
// TODO: Fixme once we switch to .Net 4.6+
//>>>
hash = hash * 23 + ((int)resolution).GetHashCode(); // Enum.GetHashCode generates garbade on .NET 3.5... Wtf !?
hash = hash * 23 + ((int)updateMode).GetHashCode();
//<<<
hash = hash * 23 + updatePeriod.GetHashCode();
hash = lightingOverride != null ? hash * 23 + rotation.GetHashCode() : hash;
return hash;
}
}

6
ScriptableRenderPipeline/HDRenderPipeline/Sky/SkySettingsSingleton.cs


{
public class SkySettingsSingleton : Singleton<SkySettingsSingleton>
{
private SkySettings settings { get; set; }
SkySettings m_Settings { get; set; }
get { return instance.settings; }
set { instance.settings = value; }
get { return instance.m_Settings; }
set { instance.m_Settings = value; }
}
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/Wind/ShaderWindSettings.cs


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

2
ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardGUI.cs


public static readonly string[] specularSmoothnessChannelNames = {"Specular Alpha", "Albedo Alpha"};
}
#pragma warning disable CS0414
private MaterialProperty workflowMode = null;
private MaterialProperty blendMode = null;

private ColorPickerHDRConfig m_ColorPickerHDRConfig = new ColorPickerHDRConfig(0f, kMaxfp16, 1 / kMaxfp16, 3f);
private bool m_FirstTimeApply = true;
#pragma warning restore CS0414
public void FindProperties(MaterialProperty[] props)
{

1
ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightUnlitGUI.cs


using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor.Experimental.Rendering.LightweightPipeline;
public class LightweightUnlitGUI : ShaderGUI

1
ScriptableRenderPipeline/LightweightPipeline/LightweightPipeline.cs


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

4
TestbedPipelines/Fptl/FptlLighting.cs


}
else
{
#pragma warning disable CS0162
#pragma warning restore CS0162
}
CommandBuffer cmdShadow = CommandBufferPool.Get();

}
else
{
#pragma warning disable CS0162
#pragma warning restore CS0162
}
// do deferred lighting

2
TestbedPipelines/Fptl/SkyboxHelper.cs


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

2
TestbedPipelines/OnTileDeferredPipeline/OnTileDeferredRenderPipeline.cs


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

2
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/HDRPAsset/HDRenderPipelineResourcesTest.asset


type: 3}
gaussianPyramidCS: {fileID: 7200000, guid: 6dba4103d23a7904fbc49099355aff3e, type: 3}
depthPyramidCS: {fileID: 7200000, guid: 64a553bb564274041906f78ffba955e4, type: 3}
copyChannelCS: {fileID: 7200000, guid: 4e910cec38a1ec640a03324015e036d0, type: 3}
copyChannelCS: {fileID: 7200000, guid: a68d8aaeb0956234d94e389f196381ee, type: 3}
clearDispatchIndirectShader: {fileID: 7200000, guid: fc1f553acb80a6446a32d33e403d0656,
type: 3}
buildDispatchIndirectShader: {fileID: 7200000, guid: 4eb1b418be7044c40bb5200496c50f14,

87
ScriptableRenderPipeline/Core/Editor/CoreEditorUtils.cs


using UnityEngine;
namespace UnityEditor.Experimental.Rendering
{
public static class CoreEditorUtils
{
// UI Helpers
public static void DrawSplitter()
{
var rect = GUILayoutUtility.GetRect(1f, 1f);
// Splitter rect should be full-width
rect.xMin = 0f;
rect.width += 4f;
if (Event.current.type != EventType.Repaint)
return;
EditorGUI.DrawRect(rect, !EditorGUIUtility.isProSkin
? new Color(0.6f, 0.6f, 0.6f, 1.333f)
: new Color(0.12f, 0.12f, 0.12f, 1.333f));
}
public static void DrawHeader(string title)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 16f;
labelRect.xMax -= 20f;
var foldoutRect = backgroundRect;
foldoutRect.y += 1f;
foldoutRect.width = 13f;
foldoutRect.height = 13f;
// Background rect should be full-width
backgroundRect.xMin = 0f;
backgroundRect.width += 4f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
EditorGUILayout.Space();
}
public static bool DrawHeaderFoldout(string title, bool state)
{
var backgroundRect = GUILayoutUtility.GetRect(1f, 17f);
var labelRect = backgroundRect;
labelRect.xMin += 16f;
labelRect.xMax -= 20f;
var foldoutRect = backgroundRect;
foldoutRect.y += 1f;
foldoutRect.width = 13f;
foldoutRect.height = 13f;
// Background rect should be full-width
backgroundRect.xMin = 0f;
backgroundRect.width += 4f;
// Background
float backgroundTint = EditorGUIUtility.isProSkin ? 0.1f : 1f;
EditorGUI.DrawRect(backgroundRect, new Color(backgroundTint, backgroundTint, backgroundTint, 0.2f));
// Title
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
// Active checkbox
state = GUI.Toggle(foldoutRect, state, GUIContent.none, EditorStyles.foldout);
var e = Event.current;
if (e.type == EventType.MouseDown && backgroundRect.Contains(e.mousePosition) && e.button == 0)
{
state = !state;
e.Use();
}
return state;
}
}
}

13
ScriptableRenderPipeline/Core/Editor/CoreEditorUtils.cs.meta


fileFormatVersion: 2
guid: 744ceabda269e6c469964dda8c490d0d
timeCreated: 1507109827
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

10
ScriptableRenderPipeline/Core/Resources/Editor.meta


fileFormatVersion: 2
guid: f00a25194233f5c4392fa05f23ecc076
folderAsset: yes
timeCreated: 1507130547
licenseType: Pro
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

23
ScriptableRenderPipeline/Core/Resources/GPUCopy.compute


// Autogenerated file. Do not edit by hand
#include "../ShaderLibrary/Common.hlsl"
SamplerState sampler_LinearClamp;
CBUFFER_START(cb)
float4 _Size;
CBUFFER_END
RWTexture2D<float1> _Result1;
Texture2D<float4> _Source4;
#pragma kernel KSampleCopy4_1_x
[numthreads(8, 8, 1)]
void KSampleCopy4_1_x(uint2 dispatchThreadId : SV_DispatchThreadID)
{
_Result1[dispatchThreadId] = _Source4.SampleLevel(sampler_LinearClamp, float2(dispatchThreadId) * _Size.zw, 0.0).x;
}

10
ScriptableRenderPipeline/Core/Resources/GPUCopy.compute.meta


fileFormatVersion: 2
guid: a68d8aaeb0956234d94e389f196381ee
timeCreated: 1507123133
licenseType: Pro
ComputeShaderImporter:
externalObjects: {}
currentAPIMask: 4
userData:
assetBundleName:
assetBundleVariant:

33
ScriptableRenderPipeline/Core/Resources/GPUCopy.cs


// Autogenerated file. Do not edit by hand
using System;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering
{
public class GPUCopy
{
ComputeShader m_Shader;
int k_SampleKernel_xyzw2x;
public GPUCopy(ComputeShader shader)
{
m_Shader = shader;
k_SampleKernel_xyzw2x = m_Shader.FindKernel("KSampleCopy4_1_x");
}
static readonly int _Result1 = Shader.PropertyToID("_Result1");
static readonly int _Source4 = Shader.PropertyToID("_Source4");
static readonly int _Size = Shader.PropertyToID("_Size");
public void SampleCopyChannel_xyzw2x(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier target, Vector2 size)
{
if (size.x < 8 || size.y < 8)
Debug.LogWarning("Trying to copy a channel from a texture smaller than 8x* or *x8. ComputeShader cannot perform it.");
var s = new Vector4(size.x, size.y, 1f / size.x, 1f / size.y);
cmd.SetComputeVectorParam(m_Shader, _Size, s);
cmd.SetComputeTextureParam(m_Shader, k_SampleKernel_xyzw2x, _Source4, source);
cmd.SetComputeTextureParam(m_Shader, k_SampleKernel_xyzw2x, _Result1, target);
cmd.DispatchCompute(m_Shader, k_SampleKernel_xyzw2x, (int)(size.x) / 8, (int)(size.y) / 8, 1);
}
}
}

13
ScriptableRenderPipeline/Core/Resources/GPUCopy.cs.meta


fileFormatVersion: 2
guid: 584fa1be28adb3344ab9eec18571f46b
timeCreated: 1507123133
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

164
ScriptableRenderPipeline/Core/Resources/GPUCopyAsset.cs


using System;
using System.Collections.Generic;
using System.Text;
namespace UnityEngine.Experimental.Rendering
{
/// <summary>
/// Declares what should be generated in utility code.
/// It will generate a compute shader and a C# class to use the compute shader with a ComputeBuffer
///
/// Exemple:
/// - I add a CopyOperation { sourceChannel = 4, targetChannel = 2, subscript = "zx" }
/// => a Kernel will be generated to copy from a TextureRGBA the AR channels into a TextureRG
/// => A method will be added to call the kernel in the C# class GPUCopy (SampleCopy_xyzw2zx)
///
/// C# Exemple:
/// // Initialize the gpucopy
/// var gpuCopy = new CPUCopy(generatedComputeShaderAsset);
///
/// CommandBuffer cmb = ...
/// gpuCopy.SampleCopyChannel_xyzw2x(cmb, _SourceTexture, _TargetTexture, new Vector2(targetWidth, targetHeight));
///
/// Initialization:
/// - You must set the generated ComputeShader as argument of the constructor of the generated GPUCopy C# class
/// </summary>
public class GPUCopyAsset : ScriptableObject
{
static string[] k_ChannelIDS = { "x", "xy", "xyz", "xyzw" };
const int k_KernelSize = 8;
[Serializable]
public struct CopyOperation
{
public string subscript;
public int sourceChannel;
public int targetChannel;
}
[SerializeField]
CopyOperation[] m_CopyOperation = new CopyOperation[0];
public void Generate(out string computeShader, out string csharp)
{
var operations = m_CopyOperation;
var sources = new HashSet<int>();
var targets = new HashSet<int>();
var cc = new StringBuilder(); // Compute Shader out
var ccp = new StringBuilder(); // Compute properties
var cck = new StringBuilder(); // Compute kernel
var cs = new StringBuilder(); // CSharp out
var csm = new StringBuilder(); // CSharp methods
var csc = new StringBuilder(); // CSharp constructor
var csp = new StringBuilder(); // CSharp properties
for (var i = 0; i < operations.Length; i++)
{
var o = operations[i];
sources.Add(o.sourceChannel);
targets.Add(o.targetChannel);
}
ccp.AppendLine();
foreach (var target in targets)
{
ccp.AppendLine(string.Format("RWTexture2D<float{0}> _Result{0};", target.ToString()));
csm.AppendLine(string.Format(" static readonly int _Result{0} = Shader.PropertyToID(\"_Result{0}\");", target.ToString()));
}
ccp.AppendLine();
foreach (var source in sources)
{
ccp.AppendLine(string.Format("Texture2D<float{0}> _Source{0};", source.ToString()));
csm.AppendLine(string.Format(" static readonly int _Source{0} = Shader.PropertyToID(\"_Source{0}\");", source.ToString()));
}
ccp.AppendLine();
csc.AppendLine(" public GPUCopy(ComputeShader shader)");
csc.AppendLine(" {");
csc.AppendLine(" m_Shader = shader;");
csm.AppendLine(" static readonly int _Size = Shader.PropertyToID(\"_Size\");");
for (var i = 0; i < operations.Length; i++)
{
var o = operations[i];
// Compute kernel
var kernelName = string.Format("KSampleCopy{0}_{1}_{2}", o.sourceChannel.ToString(), o.targetChannel.ToString(), o.subscript);
cck.AppendLine(string.Format("#pragma kernel {0}", kernelName));
cck.AppendLine(string.Format(@"[numthreads({0}, {0}, 1)]",
k_KernelSize.ToString(), k_KernelSize.ToString()));
cck.AppendLine(string.Format(@"void {0}(uint2 dispatchThreadId : SV_DispatchThreadID)", kernelName));
cck.AppendLine("{");
cck.AppendLine(string.Format(" _Result{0}[dispatchThreadId] = _Source{1}.SampleLevel(sampler_LinearClamp, float2(dispatchThreadId) * _Size.zw, 0.0).{2};",
o.targetChannel.ToString(), o.sourceChannel.ToString(), o.subscript));
cck.AppendLine("}");
cck.AppendLine();
// CSharp kernel index
var channelName = k_ChannelIDS[o.sourceChannel - 1];
var kernelIndexName = string.Format("k_SampleKernel_{0}2{1}", channelName, o.subscript);
csp.AppendLine(string.Format(" int {0};", kernelIndexName));
// CSharp constructor
csc.AppendLine(string.Format(" {0} = m_Shader.FindKernel(\"{1}\");", kernelIndexName, kernelName));
// CSharp method
csm.AppendLine(string.Format(@" public void SampleCopyChannel_{0}2{1}(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier target, Vector2 size)", channelName, o.subscript));
csm.AppendLine(" {");
csm.AppendLine(string.Format(" if (size.x < {0} || size.y < {0})", k_KernelSize.ToString()));
csm.AppendLine(" Debug.LogWarning(\"Trying to copy a channel from a texture smaller than 8x* or *x8. ComputeShader cannot perform it.\");");
csm.AppendLine(" var s = new Vector4(size.x, size.y, 1f / size.x, 1f / size.y);");
csm.AppendLine(" cmd.SetComputeVectorParam(m_Shader, _Size, s);");
csm.AppendLine(string.Format(" cmd.SetComputeTextureParam(m_Shader, {0}, _Source{1}, source);", kernelIndexName, o.sourceChannel.ToString()));
csm.AppendLine(string.Format(" cmd.SetComputeTextureParam(m_Shader, {0}, _Result{1}, target);", kernelIndexName, o.targetChannel.ToString()));
csm.AppendLine(string.Format(" cmd.DispatchCompute(m_Shader, {0}, (int)(size.x) / {1}, (int)(size.y) / {1}, 1);", kernelIndexName, k_KernelSize.ToString()));
csm.AppendLine(" }");
}
csc.AppendLine(" }");
// Compute Shader
cc.AppendLine(@"// Autogenerated file. Do not edit by hand");
cc.AppendLine();
cc.AppendLine(@"#include ""../ShaderLibrary/Common.hlsl""");
cc.AppendLine();
cc.AppendLine(@"SamplerState sampler_LinearClamp;");
cc.AppendLine();
cc.AppendLine(@"CBUFFER_START(cb)");
cc.AppendLine(@" float4 _Size;");
cc.AppendLine(@"CBUFFER_END");
cc.AppendLine(ccp.ToString()); // Properties
cc.AppendLine(cck.ToString()); // Kernels
// CSharp
cs.AppendLine(@"// Autogenerated file. Do not edit by hand");
cs.AppendLine(@"using System;");
cs.AppendLine(@"using UnityEngine.Rendering;");
cs.AppendLine();
cs.AppendLine(@"namespace UnityEngine.Experimental.Rendering");
cs.AppendLine("{");
cs.AppendLine(" public class GPUCopy");
cs.AppendLine(" {");
cs.AppendLine(" ComputeShader m_Shader;");
cs.AppendLine(csp.ToString()); // Properties
cs.AppendLine(csc.ToString()); // Constructor
cs.AppendLine(csm.ToString()); // methods
cs.AppendLine(" }");
cs.AppendLine("}");
computeShader = cc.ToString();
csharp = cs.ToString();
}
void OnValidate()
{
for (var i = 0; i < m_CopyOperation.Length; i++)
{
var o = m_CopyOperation[i];
o.sourceChannel = Mathf.Clamp(o.sourceChannel, 1, k_ChannelIDS.Length);
o.targetChannel = Mathf.Clamp(o.targetChannel, 1, k_ChannelIDS.Length);
m_CopyOperation[i] = o;
}
}
}
}

13
ScriptableRenderPipeline/Core/Resources/GPUCopyAsset.cs.meta


fileFormatVersion: 2
guid: d6592d54c1ab4694eaabc84e14cc6385
timeCreated: 1507119931
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

17
ScriptableRenderPipeline/Core/Resources/GPUCopyDefinition.asset


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: d6592d54c1ab4694eaabc84e14cc6385, type: 3}
m_Name: GPUCopyDefinition
m_EditorClassIdentifier:
m_CopyOperation:
- subscript: x
sourceChannel: 4
targetChannel: 1

10
ScriptableRenderPipeline/Core/Resources/GPUCopyDefinition.asset.meta


fileFormatVersion: 2
guid: 6aece293b43f5fb4fb5ace0d22b0035a
timeCreated: 1507122722
licenseType: Pro
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

88
ScriptableRenderPipeline/HDRenderPipeline/Editor/HDAssetFactory.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
using UnityObject = UnityEngine.Object;
static class HDAssetFactory
{
static string s_RenderPipelineResourcesPath
{
get { return HDEditorUtils.GetHDRenderPipelinePath() + "RenderPipelineResources/HDRenderPipelineResources.asset"; }
}
[MenuItem("RenderPipeline/HDRenderPipeline/Create Pipeline Asset", false, 16)]
static void CreateHDRenderPipeline()
{
var instance = ScriptableObject.CreateInstance<HDRenderPipelineAsset>();
AssetDatabase.CreateAsset(instance, HDEditorUtils.GetHDRenderPipelinePath() + "HDRenderPipelineAsset.asset");
// If it exist, load renderPipelineResources
instance.renderPipelineResources = AssetDatabase.LoadAssetAtPath<RenderPipelineResources>(s_RenderPipelineResourcesPath);
}
// TODO skybox/cubemap
[MenuItem("RenderPipeline/HDRenderPipeline/Create Resources Asset", false, 15)]
static void CreateRenderPipelineResources()
{
string HDRenderPipelinePath = HDEditorUtils.GetHDRenderPipelinePath();
string PostProcessingPath = HDEditorUtils.GetPostProcessingPath();
string CorePath = HDEditorUtils.GetCorePath();
var instance = ScriptableObject.CreateInstance<RenderPipelineResources>();
instance.debugDisplayLatlongShader = Load<Shader>(HDRenderPipelinePath + "Debug/DebugDisplayLatlong.Shader");
instance.debugViewMaterialGBufferShader = Load<Shader>(HDRenderPipelinePath + "Debug/DebugViewMaterialGBuffer.Shader");
instance.debugViewTilesShader = Load<Shader>(HDRenderPipelinePath + "Debug/DebugViewTiles.Shader");
instance.debugFullScreenShader = Load<Shader>(HDRenderPipelinePath + "Debug/DebugFullScreen.Shader");
instance.deferredShader = Load<Shader>(HDRenderPipelinePath + "Lighting/Deferred.Shader");
instance.screenSpaceAmbientOcclusionShader = Load<Shader>(HDRenderPipelinePath + "Lighting/AmbientOcclusion/ScreenSpaceAmbientOcclusion.Shader");
instance.subsurfaceScatteringCS = Load<ComputeShader>(HDRenderPipelinePath + "Material/Lit/Resources/SubsurfaceScattering.compute");
instance.volumetricLightingCS = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/Volumetrics/Resources/VolumetricLighting.compute");
instance.gaussianPyramidCS = Load<ComputeShader>(PostProcessingPath + "Shaders/Builtins/GaussianDownsample.compute");
instance.depthPyramidCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/DepthDownsample.compute");
instance.copyChannelCS = Load<ComputeShader>(CorePath + "Resources/GPUCopy.compute");
instance.clearDispatchIndirectShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/cleardispatchindirect.compute");
instance.buildDispatchIndirectShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/builddispatchindirect.compute");
instance.buildScreenAABBShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/scrbound.compute");
instance.buildPerTileLightListShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/lightlistbuild.compute");
instance.buildPerBigTileLightListShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/lightlistbuild-bigtile.compute");
instance.buildPerVoxelLightListShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/lightlistbuild-clustered.compute");
instance.buildMaterialFlagsShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/materialflags.compute");
instance.deferredComputeShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/Deferred.compute");
instance.deferredDirectionalShadowComputeShader = Load<ComputeShader>(HDRenderPipelinePath + "Lighting/TilePass/DeferredDirectionalShadow.compute");
// SceneSettings
// These shaders don't need to be reference by RenderPipelineResource as they are not use at runtime (only to draw in editor)
// instance.drawSssProfile = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "SceneSettings/DrawSssProfile.shader");
// instance.drawTransmittanceGraphShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(HDRenderPipelinePath + "SceneSettings/DrawTransmittanceGraph.shader");
instance.cameraMotionVectors = Load<Shader>(HDRenderPipelinePath + "RenderPipelineResources/CameraMotionVectors.shader");
// Sky
instance.blitCubemap = Load<Shader>(HDRenderPipelinePath + "Sky/BlitCubemap.shader");
instance.buildProbabilityTables = Load<ComputeShader>(HDRenderPipelinePath + "Sky/BuildProbabilityTables.compute");
instance.computeGgxIblSampleData = Load<ComputeShader>(HDRenderPipelinePath + "Sky/ComputeGgxIblSampleData.compute");
instance.GGXConvolve = Load<Shader>(HDRenderPipelinePath + "Sky/GGXConvolve.shader");
// Skybox/Cubemap is a builtin shader, must use Sahder.Find to access it. It is fine because we are in the editor
instance.skyboxCubemap = Shader.Find("Skybox/Cubemap");
AssetDatabase.CreateAsset(instance, s_RenderPipelineResourcesPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
// Note: move this to a static using once we can target C#6+
static T Load<T>(string path)
where T : UnityObject
{
return AssetDatabase.LoadAssetAtPath<T>(path);
}
}
}

13
ScriptableRenderPipeline/HDRenderPipeline/Editor/HDAssetFactory.cs.meta


fileFormatVersion: 2
guid: c895a728829a6b94da9922c78197e403
timeCreated: 1507108008
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

36
ScriptableRenderPipeline/HDRenderPipeline/Editor/HDEditorUtils.cs


using System.IO;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
public class HDEditorUtils
{
public static string GetHDRenderPipelinePath()
{
// User can create their own directory for SRP, so we need to find the current path that they use.
// We know that DefaultHDMaterial exist and we know where it is, let's use that to find the current directory.
var guid = AssetDatabase.FindAssets("DefaultHDMaterial t:material");
string path = AssetDatabase.GUIDToAssetPath(guid[0]);
path = Path.GetDirectoryName(path); // Asset is in HDRenderPipeline/RenderPipelineResources/DefaultHDMaterial.mat
path = path.Replace("RenderPipelineResources", ""); // Keep only path with HDRenderPipeline
return path;
}
// TODO: The two following functions depend on HDRP, they should be made generic
public static string GetPostProcessingPath()
{
var hdrpPath = GetHDRenderPipelinePath();
var fullPath = Path.GetFullPath(hdrpPath + "../../PostProcessing/PostProcessing");
var relativePath = fullPath.Substring(fullPath.IndexOf("Assets"));
return relativePath.Replace("\\", "/") + "/";
}
public static string GetCorePath()
{
var hdrpPath = GetHDRenderPipelinePath();
var fullPath = Path.GetFullPath(hdrpPath + "../Core");
var relativePath = fullPath.Substring(fullPath.IndexOf("Assets"));
return relativePath.Replace("\\", "/") + "/";
}
}
}

13
ScriptableRenderPipeline/HDRenderPipeline/Editor/HDEditorUtils.cs.meta


fileFormatVersion: 2
guid: 7e04ef797263c2a47ad576cce5233df9
timeCreated: 1507109247
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

413
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs.orig


using System;
using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
// A Material can be authored from the shader graph or by hand. When written by hand we need to provide an inspector.
// Such a Material will share some properties between it various variant (shader graph variant or hand authored variant).
// This is the purpose of BaseLitGUI. It contain all properties that are common to all Material based on Lit template.
// For the default hand written Lit material see LitUI.cs that contain specific properties for our default implementation.
public abstract class BaseLitGUI : BaseUnlitGUI
{
protected static class StylesBaseLit
{
public static GUIContent doubleSidedNormalModeText = new GUIContent("Normal mode", "This will modify the normal base on the selected mode. None: untouch, Mirror: Mirror the normal with vertex normal plane, Flip: Flip the normal");
public static GUIContent depthOffsetEnableText = new GUIContent("Enable Depth Offset", "EnableDepthOffset on this shader (Use with heightmap)");
// Material ID
public static GUIContent materialIDText = new GUIContent("Material type", "Subsurface Scattering: enable for translucent materials such as skin, vegetation, fruit, marble, wax and milk.");
// Displacement mapping (POM, tessellation, per vertex)
public static GUIContent lockWithObjectScaleText = new GUIContent("Lock with object scale", "Displacement mapping will take the absolute value of the scale of the object into account.");
public static GUIContent lockWithTilingRateText = new GUIContent("Lock with height map tiling rate", "Displacement mapping will take the absolute value of the tiling rate of the height map into account.");
// Per pixel displacement
public static GUIContent enablePerPixelDisplacementText = new GUIContent("Enable Per Pixel Displacement", "Per pixel displacement work best with flat surfaces. This is an expensive features and should be enable wisely. Typical use case is paved road.");
public static GUIContent ppdMinSamplesText = new GUIContent("Minimum steps", "Minimum steps (texture sample) to use with per pixel displacement mapping");
public static GUIContent ppdMaxSamplesText = new GUIContent("Maximum steps", "Maximum steps (texture sample) to use with per pixel displacement mapping");
public static GUIContent ppdLodThresholdText = new GUIContent("Fading mip level start", "Starting heightmap mipmap lod number where the parallax occlusion mapping effect start to disappear");
<<<<<<< HEAD
public static GUIContent ppdPrimitiveLength = new GUIContent("Primitive length", "Dimensions of the primitive (with the scale of 1) to which the per-pixel displacement mapping is being applied. For example, the standard quad is 1 x 1 meter, while the standard plane is 10 x 10 meters.");
public static GUIContent ppdPrimitiveWidth = new GUIContent("Primitive width", "Dimensions of the primitive (with the scale of 1) to which the per-pixel displacement mapping is being applied. For example, the standard quad is 1 x 1 meter, while the standard plane is 10 x 10 meters.");
=======
public static GUIContent perPixelDisplacementObjectScaleText = new GUIContent("Lock with object scale", "Per Pixel displacement will take into account the tiling scale - Only work with uniform positive scale");
>>>>>>> Unity-2017.3
// Vertex displacement
public static string vertexDisplacementText = "Vertex displacement";
public static GUIContent enableVertexDisplacementText = new GUIContent("Enable vertex displacement", "Use heightmap as a displacement map. Displacement map is use to move vertex position in local space");
// Tessellation
public static string tessellationModeText = "Tessellation Mode";
public static readonly string[] tessellationModeNames = Enum.GetNames(typeof(TessellationMode));
public static GUIContent tessellationText = new GUIContent("Tessellation options", "Tessellation options");
public static GUIContent tessellationFactorText = new GUIContent("Tessellation factor", "This value is the tessellation factor use for tessellation, higher mean more tessellated");
public static GUIContent tessellationFactorMinDistanceText = new GUIContent("Start fade distance", "Distance (in unity unit) at which the tessellation start to fade out. Must be inferior at Max distance");
public static GUIContent tessellationFactorMaxDistanceText = new GUIContent("End fade distance", "Maximum distance (in unity unit) to the camera where triangle are tessellated");
public static GUIContent tessellationFactorTriangleSizeText = new GUIContent("Triangle size", "Desired screen space sized of triangle (in pixel). Smaller value mean smaller triangle.");
public static GUIContent tessellationShapeFactorText = new GUIContent("Shape factor", "Strength of Phong tessellation shape (lerp factor)");
public static GUIContent tessellationBackFaceCullEpsilonText = new GUIContent("Triangle culling Epsilon", "If -1.0 back face culling is enabled for tessellation, higher number mean more aggressive culling and better performance");
// Vertex animation
public static string vertexAnimation = "Vertex animation";
// Wind
public static GUIContent windText = new GUIContent("Enable Wind");
public static GUIContent windInitialBendText = new GUIContent("Initial Bend");
public static GUIContent windStiffnessText = new GUIContent("Stiffness");
public static GUIContent windDragText = new GUIContent("Drag");
public static GUIContent windShiverDragText = new GUIContent("Shiver Drag");
public static GUIContent windShiverDirectionalityText = new GUIContent("Shiver Directionality");
}
public enum DoubleSidedNormalMode
{
None,
Mirror,
Flip
}
public enum TessellationMode
{
None,
Phong
}
protected MaterialProperty doubleSidedNormalMode = null;
protected const string kDoubleSidedNormalMode = "_DoubleSidedNormalMode";
protected MaterialProperty depthOffsetEnable = null;
protected const string kDepthOffsetEnable = "_DepthOffsetEnable";
// Properties
// Material ID
protected MaterialProperty materialID = null;
protected const string kMaterialID = "_MaterialID";
protected const string kStencilRef = "_StencilRef";
// Per pixel displacement params
protected MaterialProperty enablePerPixelDisplacement = null;
protected const string kEnablePerPixelDisplacement = "_EnablePerPixelDisplacement";
protected MaterialProperty ppdMinSamples = null;
protected const string kPpdMinSamples = "_PPDMinSamples";
protected MaterialProperty ppdMaxSamples = null;
protected const string kPpdMaxSamples = "_PPDMaxSamples";
protected MaterialProperty ppdLodThreshold = null;
protected const string kPpdLodThreshold = "_PPDLodThreshold";
protected MaterialProperty ppdPrimitiveLength = null;
protected const string kPpdPrimitiveLength = "_PPDPrimitiveLength";
protected MaterialProperty ppdPrimitiveWidth = null;
protected const string kPpdPrimitiveWidth = "_PPDPrimitiveWidth";
protected MaterialProperty perPixelDisplacementObjectScale = null;
protected const string kPerPixelDisplacementObjectScale = "_PerPixelDisplacementObjectScale";
protected MaterialProperty perPixelDisplacementTilingScale = null;
protected const string kPerPixelDisplacementTilingScale = "_PerPixelDisplacementTilingScale";
// Vertex displacement
protected MaterialProperty enableVertexDisplacement = null;
protected const string kEnableVertexDisplacement = "_EnableVertexDisplacement";
protected MaterialProperty vertexDisplacementObjectScale = null;
protected const string kVertexDisplacementObjectScale = "_VertexDisplacementObjectScale";
protected MaterialProperty vertexDisplacementTilingScale = null;
protected const string kVertexDisplacementTilingScale = "_VertexDisplacementTilingScale";
// Wind
protected MaterialProperty windEnable = null;
protected const string kWindEnabled = "_EnableWind";
protected MaterialProperty windInitialBend = null;
protected const string kWindInitialBend = "_InitialBend";
protected MaterialProperty windStiffness = null;
protected const string kWindStiffness = "_Stiffness";
protected MaterialProperty windDrag = null;
protected const string kWindDrag = "_Drag";
protected MaterialProperty windShiverDrag = null;
protected const string kWindShiverDrag = "_ShiverDrag";
protected MaterialProperty windShiverDirectionality = null;
protected const string kWindShiverDirectionality = "_ShiverDirectionality";
// tessellation params
protected MaterialProperty tessellationMode = null;
protected const string kTessellationMode = "_TessellationMode";
protected MaterialProperty tessellationFactor = null;
protected const string kTessellationFactor = "_TessellationFactor";
protected MaterialProperty tessellationFactorMinDistance = null;
protected const string kTessellationFactorMinDistance = "_TessellationFactorMinDistance";
protected MaterialProperty tessellationFactorMaxDistance = null;
protected const string kTessellationFactorMaxDistance = "_TessellationFactorMaxDistance";
protected MaterialProperty tessellationFactorTriangleSize = null;
protected const string kTessellationFactorTriangleSize = "_TessellationFactorTriangleSize";
protected MaterialProperty tessellationShapeFactor = null;
protected const string kTessellationShapeFactor = "_TessellationShapeFactor";
protected MaterialProperty tessellationBackFaceCullEpsilon = null;
protected const string kTessellationBackFaceCullEpsilon = "_TessellationBackFaceCullEpsilon";
protected override void FindBaseMaterialProperties(MaterialProperty[] props)
{
base.FindBaseMaterialProperties(props);
doubleSidedNormalMode = FindProperty(kDoubleSidedNormalMode, props);
depthOffsetEnable = FindProperty(kDepthOffsetEnable, props);
// MaterialID
materialID = FindProperty(kMaterialID, props, false); // LayeredLit is force to be standard for now, so materialID could not exist
// Per pixel displacement
enablePerPixelDisplacement = FindProperty(kEnablePerPixelDisplacement, props);
ppdMinSamples = FindProperty(kPpdMinSamples, props);
ppdMaxSamples = FindProperty(kPpdMaxSamples, props);
ppdLodThreshold = FindProperty(kPpdLodThreshold, props);
<<<<<<< HEAD
ppdPrimitiveLength = FindProperty(kPpdPrimitiveLength, props);
ppdPrimitiveWidth = FindProperty(kPpdPrimitiveWidth, props);
perPixelDisplacementObjectScale = FindProperty(kPerPixelDisplacementObjectScale, props);
perPixelDisplacementTilingScale = FindProperty(kPerPixelDisplacementTilingScale, props);
=======
perPixelDisplacementObjectScale = FindProperty(kPerPixelDisplacementObjectScale, props);
>>>>>>> Unity-2017.3
// vertex displacement
enableVertexDisplacement = FindProperty(kEnableVertexDisplacement, props);
vertexDisplacementObjectScale = FindProperty(kVertexDisplacementObjectScale, props);
vertexDisplacementTilingScale = FindProperty(kVertexDisplacementTilingScale, props);
// tessellation specific, silent if not found
tessellationMode = FindProperty(kTessellationMode, props, false);
tessellationFactor = FindProperty(kTessellationFactor, props, false);
tessellationFactorMinDistance = FindProperty(kTessellationFactorMinDistance, props, false);
tessellationFactorMaxDistance = FindProperty(kTessellationFactorMaxDistance, props, false);
tessellationFactorTriangleSize = FindProperty(kTessellationFactorTriangleSize, props, false);
tessellationShapeFactor = FindProperty(kTessellationShapeFactor, props, false);
tessellationBackFaceCullEpsilon = FindProperty(kTessellationBackFaceCullEpsilon, props, false);
// Wind
windEnable = FindProperty(kWindEnabled, props);
windInitialBend = FindProperty(kWindInitialBend, props);
windStiffness = FindProperty(kWindStiffness, props);
windDrag = FindProperty(kWindDrag, props);
windShiverDrag = FindProperty(kWindShiverDrag, props);
windShiverDirectionality = FindProperty(kWindShiverDirectionality, props);
}
void TessellationModePopup()
{
EditorGUI.showMixedValue = tessellationMode.hasMixedValue;
var mode = (TessellationMode)tessellationMode.floatValue;
EditorGUI.BeginChangeCheck();
mode = (TessellationMode)EditorGUILayout.Popup(StylesBaseLit.tessellationModeText, (int)mode, StylesBaseLit.tessellationModeNames);
if (EditorGUI.EndChangeCheck())
{
m_MaterialEditor.RegisterPropertyChangeUndo("Tessellation Mode");
tessellationMode.floatValue = (float)mode;
}
EditorGUI.showMixedValue = false;
}
protected override void BaseMaterialPropertiesGUI()
{
base.BaseMaterialPropertiesGUI();
EditorGUI.indentLevel++;
// This follow double sided option
if (doubleSidedEnable.floatValue > 0.0f)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(doubleSidedNormalMode, StylesBaseLit.doubleSidedNormalModeText);
EditorGUI.indentLevel--;
}
if (materialID != null)
m_MaterialEditor.ShaderProperty(materialID, StylesBaseLit.materialIDText);
m_MaterialEditor.ShaderProperty(enablePerPixelDisplacement, StylesBaseLit.enablePerPixelDisplacementText);
if (enablePerPixelDisplacement.floatValue > 0.0f)
{
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);
<<<<<<< HEAD
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);
m_MaterialEditor.ShaderProperty(perPixelDisplacementObjectScale, StylesBaseLit.lockWithObjectScaleText);
m_MaterialEditor.ShaderProperty(perPixelDisplacementTilingScale, StylesBaseLit.lockWithTilingRateText);
m_MaterialEditor.ShaderProperty(depthOffsetEnable, StylesBaseLit.depthOffsetEnableText);
=======
//m_MaterialEditor.ShaderProperty(perPixelDisplacementObjectScale, StylesBaseLit.perPixelDisplacementObjectScaleText);
m_MaterialEditor.ShaderProperty(depthOffsetEnable, StylesBaseLit.depthOffsetEnableText);
>>>>>>> Unity-2017.3
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
// Vertex displacement options
EditorGUILayout.Space();
EditorGUILayout.LabelField(StylesBaseLit.vertexDisplacementText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(enableVertexDisplacement, StylesBaseLit.enableVertexDisplacementText);
if (enableVertexDisplacement.floatValue > 0.0f)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(vertexDisplacementObjectScale, StylesBaseLit.lockWithObjectScaleText);
m_MaterialEditor.ShaderProperty(vertexDisplacementTilingScale, StylesBaseLit.lockWithTilingRateText);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
// Display tessellation option if it exist
if (tessellationMode != null)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField(StylesBaseLit.tessellationText, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
TessellationModePopup();
m_MaterialEditor.ShaderProperty(tessellationFactor, StylesBaseLit.tessellationFactorText);
m_MaterialEditor.ShaderProperty(tessellationFactorMinDistance, StylesBaseLit.tessellationFactorMinDistanceText);
m_MaterialEditor.ShaderProperty(tessellationFactorMaxDistance, StylesBaseLit.tessellationFactorMaxDistanceText);
// clamp min distance to be below max distance
tessellationFactorMinDistance.floatValue = Math.Min(tessellationFactorMaxDistance.floatValue, tessellationFactorMinDistance.floatValue);
m_MaterialEditor.ShaderProperty(tessellationFactorTriangleSize, StylesBaseLit.tessellationFactorTriangleSizeText);
if ((TessellationMode)tessellationMode.floatValue == TessellationMode.Phong)
{
m_MaterialEditor.ShaderProperty(tessellationShapeFactor, StylesBaseLit.tessellationShapeFactorText);
}
if (doubleSidedEnable.floatValue == 0.0)
{
m_MaterialEditor.ShaderProperty(tessellationBackFaceCullEpsilon, StylesBaseLit.tessellationBackFaceCullEpsilonText);
}
EditorGUI.indentLevel--;
}
}
protected override void VertexAnimationPropertiesGUI()
{
EditorGUILayout.LabelField(StylesBaseLit.vertexAnimation, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(windEnable, StylesBaseLit.windText);
if (!windEnable.hasMixedValue && windEnable.floatValue > 0.0f)
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(windInitialBend, StylesBaseLit.windInitialBendText);
m_MaterialEditor.ShaderProperty(windStiffness, StylesBaseLit.windStiffnessText);
m_MaterialEditor.ShaderProperty(windDrag, StylesBaseLit.windDragText);
m_MaterialEditor.ShaderProperty(windShiverDrag, StylesBaseLit.windShiverDragText);
m_MaterialEditor.ShaderProperty(windShiverDirectionality, StylesBaseLit.windShiverDirectionalityText);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
}
// All Setup Keyword functions must be static. It allow to create script to automatically update the shaders with a script if code change
static public void SetupBaseLitKeywords(Material material)
{
SetupBaseUnlitKeywords(material);
bool doubleSidedEnable = material.GetFloat(kDoubleSidedEnable) > 0.0f;
if (doubleSidedEnable)
{
DoubleSidedNormalMode doubleSidedNormalMode = (DoubleSidedNormalMode)material.GetFloat(kDoubleSidedNormalMode);
switch (doubleSidedNormalMode)
{
case DoubleSidedNormalMode.None:
material.SetVector("_DoubleSidedConstants", new Vector4(1.0f, 1.0f, 1.0f, 0.0f));
break;
case DoubleSidedNormalMode.Mirror: // Mirror mode (in tangent space)
material.SetVector("_DoubleSidedConstants", new Vector4(1.0f, 1.0f, -1.0f, 0.0f));
break;
case DoubleSidedNormalMode.Flip: // Flip mode (in tangent space)
material.SetVector("_DoubleSidedConstants", new Vector4(-1.0f, -1.0f, -1.0f, 0.0f));
break;
}
}
// Depth offset is only enabled if per pixel displacement is
bool depthOffsetEnable = (material.GetFloat(kDepthOffsetEnable) > 0.0f) && (material.GetFloat(kEnablePerPixelDisplacement) > 0.0f);
SetKeyword(material, "_DEPTHOFFSET_ON", depthOffsetEnable);
// Set the reference value for the stencil test.
int stencilRef = (int)StencilLightingUsage.RegularLighting;
if (material.HasProperty(kMaterialID))
{
if ((int)material.GetFloat(kMaterialID) == (int)UnityEngine.Experimental.Rendering.HDPipeline.Lit.MaterialId.LitSSS)
{
stencilRef = (int)StencilLightingUsage.SplitLighting;
}
}
material.SetInt(kStencilRef, stencilRef);
bool enablePerPixelDisplacement = material.GetFloat(kEnablePerPixelDisplacement) > 0.0f;
SetKeyword(material, "_PER_PIXEL_DISPLACEMENT", enablePerPixelDisplacement);
bool perPixelDisplacementObjectScale = material.GetFloat(kPerPixelDisplacementObjectScale) > 0.0;
SetKeyword(material, "_PER_PIXEL_DISPLACEMENT_OBJECT_SCALE", perPixelDisplacementObjectScale && enablePerPixelDisplacement);
bool perPixelDisplacementTilingScale = material.GetFloat(kPerPixelDisplacementTilingScale) > 0.0;
SetKeyword(material, "_PER_PIXEL_DISPLACEMENT_TILING_SCALE", perPixelDisplacementTilingScale && enablePerPixelDisplacement);
bool enableVertexDisplacement = material.GetFloat(kEnableVertexDisplacement) > 0.0f;
SetKeyword(material, "_VERTEX_DISPLACEMENT", enableVertexDisplacement);
bool vertexDisplacementObjectScaleEnable = material.GetFloat(kVertexDisplacementObjectScale) > 0.0;
SetKeyword(material, "_VERTEX_DISPLACEMENT_OBJECT_SCALE", vertexDisplacementObjectScaleEnable && enableVertexDisplacement);
bool vertexDisplacementTilingScaleEnable = material.GetFloat(kVertexDisplacementTilingScale) > 0.0;
SetKeyword(material, "_VERTEX_DISPLACEMENT_TILING_SCALE", vertexDisplacementTilingScaleEnable && enableVertexDisplacement);
bool windEnabled = material.GetFloat(kWindEnabled) > 0.0f;
SetKeyword(material, "_VERTEX_WIND", windEnabled);
if (material.HasProperty(kTessellationMode))
{
TessellationMode tessMode = (TessellationMode)material.GetFloat(kTessellationMode);
SetKeyword(material, "_TESSELLATION_PHONG", tessMode == TessellationMode.Phong);
}
}
static public void SetupBaseLitMaterialPass(Material material)
{
bool distortionEnable = material.GetFloat(kDistortionEnable) > 0.0f;
bool distortionOnly = material.GetFloat(kDistortionOnly) > 0.0f;
if (distortionEnable && distortionOnly)
{
// Disable all passes except distortion (setup in BaseUnlitUI.cs) and debug passes (to visualize distortion)
material.SetShaderPassEnabled("GBuffer", false);
material.SetShaderPassEnabled("GBufferDisplayDebug", true);
material.SetShaderPassEnabled("Meta", false);
material.SetShaderPassEnabled("ShadowCaster", false);
material.SetShaderPassEnabled("DepthOnly", false);
material.SetShaderPassEnabled("MotionVectors", false);
material.SetShaderPassEnabled("Forward", false);
material.SetShaderPassEnabled("ForwardDisplayDebug", true);
}
else
{
// Enable all passes except distortion (setup in BaseUnlitUI.cs)
material.SetShaderPassEnabled("GBuffer", true);
material.SetShaderPassEnabled("GBufferDisplayDebug", true);
material.SetShaderPassEnabled("Meta", true);
material.SetShaderPassEnabled("ShadowCaster", true);
material.SetShaderPassEnabled("DepthOnly", true);
material.SetShaderPassEnabled("MotionVectors", true);
material.SetShaderPassEnabled("Forward", true);
material.SetShaderPassEnabled("ForwardDisplayDebug", true);
}
}
}
} // namespace UnityEditor

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

正在加载...
取消
保存