浏览代码

Merge pull request #451 from Unity-Technologies/refactor-episode-3

Refactoring: Episode 3 - The GC Apocalypse
/stochastic_alpha_test
GitHub 7 年前
当前提交
720185a2
共有 19 个文件被更改,包括 388 次插入342 次删除
  1. 19
      ScriptableRenderPipeline/Core/CommandBufferPool.cs
  2. 37
      ScriptableRenderPipeline/Core/CoreUtils.cs
  3. 6
      ScriptableRenderPipeline/HDRenderPipeline/Camera/HDCamera.cs
  4. 2
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs
  5. 286
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
  6. 29
      ScriptableRenderPipeline/HDRenderPipeline/HDUtils.cs
  7. 2
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs
  8. 9
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/HDRISkyRenderer.cs
  9. 16
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/HDRISkySettings.cs
  10. 41
      ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkySettings.cs
  11. 49
      ScriptableRenderPipeline/HDRenderPipeline/Sky/RuntimeFilterIBL.cs
  12. 178
      ScriptableRenderPipeline/HDRenderPipeline/Sky/SkyManager.cs
  13. 5
      ScriptableRenderPipeline/HDRenderPipeline/Sky/SkyRenderer.cs
  14. 35
      ScriptableRenderPipeline/HDRenderPipeline/Sky/SkySettings.cs
  15. 6
      ScriptableRenderPipeline/HDRenderPipeline/Sky/SkySettingsSingleton.cs
  16. 2
      ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardGUI.cs
  17. 4
      TestbedPipelines/Fptl/FptlLighting.cs
  18. 2
      TestbedPipelines/Fptl/SkyboxHelper.cs
  19. 2
      TestbedPipelines/OnTileDeferredPipeline/OnTileDeferredRenderPipeline.cs

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)

6
ScriptableRenderPipeline/HDRenderPipeline/Camera/HDCamera.cs


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

public HDCamera(Camera cam)
{
camera = cam;
frustumPlanes = new Plane[6];
frustumPlaneEquations = new Vector4[6];
Reset();
}

cameraPos = pos;
screenSize = new Vector4(camera.pixelWidth, camera.pixelHeight, 1.0f / camera.pixelWidth, 1.0f / camera.pixelHeight);
var 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;

2
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs


{
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

286
ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs


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();
Material m_CopyStencilForSplitLighting;
Material m_CopyStencilForRegularLighting;

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
private RenderTargetIdentifier m_CameraDepthStencilBufferRT;
private RenderTargetIdentifier m_CameraDepthBufferCopyRT;
private RenderTargetIdentifier m_CameraStencilBufferCopyRT;
private RenderTargetIdentifier m_HTileRT;
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];
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
{

m_GPUCopy = new GPUCopy(asset.renderPipelineResources.copyChannelCS);
// Scan material list and assign it
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()

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

}
#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.s_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);

renderContext.SetupCameraProperties(camera); // Need to recall SetupCameraProperties after m_ShadowPass.Render
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)

// 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 };

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);
// Render opaque objects into GBuffer
if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled())

{
if (m_Asset.renderingSettings.useDepthPrepassWithDeferredRendering)
{
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 };
// When using depth prepass for opaque alpha test only we need to use regular depth test for normal opaque objects.
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, HDUtils.k_RendererConfigurationBakedLighting, rangeOpaqueNoAlphaTest, m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass ? m_DepthStateOpaque : m_DepthStateOpaqueWithPrepass);

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

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.s_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);
}
}
}

{
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
ShaderPassName[] arrayNames = { HDShaderPassNames.s_AlwaysName, HDShaderPassNames.s_ForwardBaseName, HDShaderPassNames.s_DeferredName, HDShaderPassNames.s_PrepassBaseName, HDShaderPassNames.s_VertexName, HDShaderPassNames.s_VertexLMRGBMName, HDShaderPassNames.s_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);
}
}
}

{
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

29
ScriptableRenderPipeline/HDRenderPipeline/HDUtils.cs


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

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;
}
public static Matrix4x4 GetViewProjectionMatrix(Matrix4x4 worldToViewMatrix, Matrix4x4 projectionMatrix)
{

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)

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


public class HDRISkyRenderer : SkyRenderer
{
Material m_SkyHDRIMaterial; // Renders a cubemap into a render texture (can be cube or 2D)
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;
}
}
}

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

49
ScriptableRenderPipeline/HDRenderPipeline/Sky/RuntimeFilterIBL.cs


{
public class IBLFilterGGX
{
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/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)
{

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
{

正在加载...
取消
保存