浏览代码

Merge branch 'master' into Branch_Batching2

/Branch_Batching2
Arnaud Carre 8 年前
当前提交
e9b3071e
共有 68 个文件被更改,包括 1742 次插入2531 次删除
  1. 4
      Assets/Editor/Tests/RenderloopTests/CullResultsTest.cs
  2. 5
      Assets/Editor/Tests/RenderloopTests/RenderPipelineTestFixture.cs
  3. 14
      Assets/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/MultiplePointLights.unity
  4. 180
      Assets/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/Shaders/LDPipe_LitShaderMaps.unity
  5. 15
      Assets/ScriptableRenderPipeline/BasicRenderPipeline/BasicRenderPipeline.cs
  6. 3
      Assets/ScriptableRenderPipeline/BasicRenderPipeline/BasicRenderPipelineShader.shader
  7. 41
      Assets/ScriptableRenderPipeline/Core/Shadow/Shadow.cs
  8. 11
      Assets/ScriptableRenderPipeline/Core/TextureCache.cs
  9. 70
      Assets/ScriptableRenderPipeline/Fptl/FptlLighting.cs
  10. 4
      Assets/ScriptableRenderPipeline/Fptl/SkyboxHelper.cs
  11. 39
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs
  12. 6
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Editor/UpgradeStandardShaderMaterials.cs
  13. 298
      Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
  14. 17
      Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.cs
  15. 4
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/ScreenSpaceAmbientOcclusion.cs
  16. 64
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs
  17. 10
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.hlsl
  18. 20
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/lightlistbuild-clustered.compute
  19. 6
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/materialflags.compute
  20. 5
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/shadeopaque.compute
  21. 3
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader
  22. 3
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader
  23. 5
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs
  24. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl
  25. 3
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader
  26. 149
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitProperties.hlsl
  27. 3
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader
  28. 151
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CombineSubsurfaceScattering.shader
  29. 14
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringProfile.cs
  30. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/MaterialUtilities.hlsl
  31. 3
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.shader
  32. 1
      Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/HDRenderPipelineResources.asset
  33. 2
      Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/HDRenderPipelineResources.asset.meta
  34. 6
      Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/RenderPipelineResources.cs
  35. 8
      Assets/ScriptableRenderPipeline/HDRenderPipeline/ShaderConfig.cs
  36. 4
      Assets/ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassVelocity.hlsl
  37. 14
      Assets/ScriptableRenderPipeline/HDRenderPipeline/ShaderVariables.hlsl
  38. 4
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/HDRISkyRenderer.cs
  39. 6
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkyRenderer.cs
  40. 12
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Sky/RuntimeFilterIBL.cs
  41. 9
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Sky/SkyManager.cs
  42. 4
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Sky/SkySettingsSingleton.cs
  43. 100
      Assets/ScriptableRenderPipeline/HDRenderPipeline/Utilities.cs
  44. 2
      Assets/ScriptableRenderPipeline/LightweightPipeline.meta
  45. 5
      Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightAssetInspector.cs
  46. 189
      Assets/ScriptableRenderPipeline/LightweightPipeline/LightweightPipeline.cs
  47. 2
      Assets/ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset
  48. 18
      Assets/ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.cs
  49. 37
      Assets/ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPipeline.shader
  50. 38
      Assets/ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPipelineCore.cginc
  51. 27
      Assets/ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPipelineShadows.cginc
  52. 3
      Assets/ScriptableRenderPipeline/ShaderLibrary/Common.hlsl
  53. 427
      Assets/ScriptableRenderPipeline/ShaderLibrary/Fibonacci.hlsl
  54. 999
      ImageTemplates/LightweightPipeline/Scenes/MultiplePointLights.unity.png
  55. 999
      ImageTemplates/LightweightPipeline/Scenes/Shaders/LDPipe_LitShaderMaps.unity.png
  56. 2
      ProjectSettings/ProjectVersion.txt
  57. 10
      Assets/ScriptableRenderPipeline/HDRenderPipeline/AdditionalData.meta
  58. 54
      Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/CameraMotionVectors.shader
  59. 9
      Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/CameraMotionVectors.shader.meta
  60. 10
      Assets/TestScenes/HDTest/HDRenderLoopTest.meta
  61. 12
      Assets/ScriptableRenderPipeline/HDRenderPipeline/AdditionalData/HDAdditionalCameraData.cs
  62. 13
      Assets/ScriptableRenderPipeline/HDRenderPipeline/AdditionalData/HDAdditionalCameraData.cs.meta
  63. 12
      Assets/ScriptableRenderPipeline/core/CommandBufferPool.cs.meta
  64. 72
      Assets/ScriptableRenderPipeline/core/CommandBufferPool.cs
  65. 9
      Assets/LegacyLayered.meta

4
Assets/Editor/Tests/RenderloopTests/CullResultsTest.cs


{
void InspectCullResults(Camera camera, CullResults cullResults, ScriptableRenderContext renderContext)
{
VisibleReflectionProbe[] probes = cullResults.visibleReflectionProbes;
VisibleReflectionProbe[] probes = cullResults.visibleReflectionProbes.ToArray();
Assert.AreEqual(1, probes.Length, "Incorrect reflection probe count");

VisibleLight[] lights = cullResults.visibleLights;
VisibleLight[] lights = cullResults.visibleLights.ToArray();
Assert.AreEqual(3, lights.Length, "Incorrect light count");
LightType[] expectedTypes = new LightType[] { LightType.Directional, LightType.Spot, LightType.Point };

5
Assets/Editor/Tests/RenderloopTests/RenderPipelineTestFixture.cs


private static RenderLoopTestFixture m_Instance;
CullResults m_CullResults;
public override void Render(ScriptableRenderContext renderContext, Camera[] cameras)
{
base.Render(renderContext, cameras);

bool gotCullingParams = CullResults.GetCullingParameters(camera, out cullingParams);
Assert.IsTrue(gotCullingParams);
CullResults cullResults = CullResults.Cull(ref cullingParams, renderContext);
CullResults.Cull(ref cullingParams, renderContext, ref m_CullResults);
s_Callback(camera, cullResults, renderContext);
s_Callback(camera, m_CullResults, renderContext);
}
renderContext.Submit();

14
Assets/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/MultiplePointLights.unity


m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.12731749, g: 0.13414757, b: 0.1210787, a: 1}
m_IndirectSpecularColor: {r: 0.12732536, g: 0.13415334, b: 0.121077195, a: 1}
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0

m_PVRDirectSampleCount: 32
m_PVRSampleCount: 500
m_PVRBounces: 2
m_PVRFiltering: 0
m_PVRFilterTypeDirect: 0
m_PVRFilterTypeIndirect: 0
m_PVRFilterTypeAO: 0
m_PVRFilteringAtrousColorSigma: 1
m_PVRFilteringAtrousNormalSigma: 1
m_PVRFilteringAtrousPositionSigma: 1
m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_LightingDataAsset: {fileID: 0}
m_UseShadowmask: 1
--- !u!196 &4

m_Script: {fileID: 11500000, guid: c20dfc007a9a74ad8a2bfd0d59abe398, type: 3}
m_Name:
m_EditorClassIdentifier:
renderPipeline: {fileID: 0}
renderPipeline: {fileID: 11400000, guid: e6987eea1dd29074597d54ed91a54a26, type: 2}
cameraToUse: {fileID: 232121474}
hdr: 0
width: 1280

180
Assets/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/Shaders/LDPipe_LitShaderMaps.unity


m_PVRDirectSampleCount: 32
m_PVRSampleCount: 500
m_PVRBounces: 2
m_PVRFiltering: 0
m_PVRFilterTypeDirect: 0
m_PVRFilterTypeIndirect: 0
m_PVRFilterTypeAO: 0
m_PVRFilteringAtrousColorSigma: 1
m_PVRFilteringAtrousNormalSigma: 1
m_PVRFilteringAtrousPositionSigma: 1
m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_LightingDataAsset: {fileID: 0}
m_UseShadowmask: 1
--- !u!196 &4

m_Father: {fileID: 0}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &222008785
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 222008789}
- component: {fileID: 222008788}
- component: {fileID: 222008787}
- component: {fileID: 222008786}
m_Layer: 0
m_Name: Quad (1)
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!23 &222008786
MeshRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 222008785}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: 96f2a4d5f3b72eb468a638a4bed6ca76, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!64 &222008787
MeshCollider:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 222008785}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Convex: 0
m_InflateMesh: 0
m_SkinWidth: 0.01
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &222008788
MeshFilter:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 222008785}
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!4 &222008789
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 222008785}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0.68, y: 0.041, z: -2.541}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 11
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &316403771
GameObject:
m_ObjectHideFlags: 0

m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 7
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &576034924
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 576034928}
- component: {fileID: 576034927}
- component: {fileID: 576034926}
- component: {fileID: 576034925}
m_Layer: 0
m_Name: Quad
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!23 &576034925
MeshRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 576034924}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_Materials:
- {fileID: 2100000, guid: f51bbc8f90c3bf54588afe5d142636b3, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
--- !u!64 &576034926
MeshCollider:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 576034924}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Convex: 0
m_InflateMesh: 0
m_SkinWidth: 0.01
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &576034927
MeshFilter:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 576034924}
m_Mesh: {fileID: 10210, guid: 0000000000000000e000000000000000, type: 0}
--- !u!4 &576034928
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 576034924}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: -0.504, y: 0.041, z: -2.541}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 10
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &952102529
GameObject:

15
Assets/ScriptableRenderPipeline/BasicRenderPipeline/BasicRenderPipeline.cs


ScriptableCullingParameters cullingParams;
if (!CullResults.GetCullingParameters(camera, out cullingParams))
continue;
CullResults cull = CullResults.Cull(ref cullingParams, context);
CullResults cull = new CullResults();
CullResults.Cull(ref cullingParams, context, ref cull);
// Setup camera for rendering (sets render target, view/projection matrices and other
// per-camera built-in shader variables).

var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
cmd.Release();
CommandBufferPool.Release(cmd);
// Setup global lighting shader variables
SetupLightShaderVariables(cull.visibleLights, context);

// Setup lighting variables for shader to use
private static void SetupLightShaderVariables(VisibleLight[] lights, ScriptableRenderContext context)
private static void SetupLightShaderVariables(List<VisibleLight> lights, ScriptableRenderContext context)
{
// We only support up to 8 visible lights here. More complex approaches would
// be doing some sort of per-object light setups, but here we go for simplest possible

// to the viewer, so that "most important" lights in the scene are picked, and not the 8
// that happened to be first.
int lightCount = Mathf.Min(lights.Length, kMaxLights);
int lightCount = Mathf.Min(lights.Count, kMaxLights);
// Prepare light data
Vector4[] lightColors = new Vector4[kMaxLights];

GetShaderConstantsFromNormalizedSH(ref ambientSH, shConstants);
// setup global shader variables to contain all the data computed above
CommandBuffer cmd = new CommandBuffer();
CommandBuffer cmd = CommandBufferPool.Get();
cmd.SetGlobalVectorArray("globalLightColor", lightColors);
cmd.SetGlobalVectorArray("globalLightPos", lightPositions);
cmd.SetGlobalVectorArray("globalLightSpotDir", lightSpotDirections);

context.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
// Prepare L2 spherical harmonics values for efficient evaluation in a shader

3
Assets/ScriptableRenderPipeline/BasicRenderPipeline/BasicRenderPipelineShader.shader


SubShader
{
Tags { "RenderType" = "Opaque" "PerformanceChecks" = "False" }
LOD 300
// Include forward (base + additive) pass from regular Standard shader.
// They are not used by the scriptable render loop; only here so that
// if we turn off our example loop, then regular forward rendering kicks in

41
Assets/ScriptableRenderPipeline/Core/Shadow/Shadow.cs


override public void Update( FrameId frameId, ScriptableRenderContext renderContext, CullResults cullResults, VisibleLight[] lights )
{
var profilingSample = new HDPipeline.Utilities.ProfilingSample("Shadowmap" + m_TexSlot, renderContext);
var profilingSample = new HDPipeline.Utilities.ProfilingSample(string.Format("Shadowmap{0}",m_TexSlot), renderContext);
var cb = new CommandBuffer();
var cb = CommandBufferPool.Get();
cb.Dispose();
CommandBufferPool.Release(cb);
}
// loop for generating each individual shadowmap

if( !cullResults.GetShadowCasterBounds( m_EntryCache[i].key.visibleIdx, out bounds ) )
continue;
var cb = new CommandBuffer();
var cb = CommandBufferPool.Get();
cb.name = "Shadowmap.Update.Slice" + entrySlice;
cb.name = string.Format("Shadowmap.Update.Slice{0}", entrySlice);
if( curSlice != uint.MaxValue )
{

PreUpdate( frameId, cb, curSlice );
}
cb.name = "Shadowmap.Update - slice: " + curSlice + ", vp.x: " + m_EntryCache[i].current.viewport.x + ", vp.y: " + m_EntryCache[i].current.viewport.y + ", vp.w: " + m_EntryCache[i].current.viewport.width + ", vp.h: " + m_EntryCache[i].current.viewport.height;
cb.name = string.Format("Shadowmap.Update - slice: {0}, vp.x: {1}, vp.y: {2}, vp.w: {3}, vp.h: {4}", curSlice, m_EntryCache[i].current.viewport.x, m_EntryCache[i].current.viewport.y, m_EntryCache[i].current.viewport.width, m_EntryCache[i].current.viewport.height);
cb.Dispose();
CommandBufferPool.Release(cb);
dss.lightIndex = m_EntryCache[i].key.visibleIdx;
dss.splitData = m_EntryCache[i].current.splitData;

// post update
var cblast = new CommandBuffer();
var cblast = CommandBufferPool.Get();
PostUpdate( frameId, cblast, curSlice, lights );
if( !string.IsNullOrEmpty( m_ShaderKeyword ) )
{

renderContext.ExecuteCommandBuffer( cblast );
cblast.Dispose();
CommandBufferPool.Release(cblast);
m_ActiveEntriesCount = 0;

override public void DisplayShadowMap(ScriptableRenderContext renderContext, Vector4 scaleBias, uint slice, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
{
CommandBuffer debugCB = new CommandBuffer();
CommandBuffer debugCB = CommandBufferPool.Get();
debugCB.name = "";
Vector4 validRange = new Vector4(minValue, 1.0f / (maxValue - minValue));

debugCB.DrawProcedural(Matrix4x4.identity, m_DebugMaterial, m_DebugMaterial.FindPass("REGULARSHADOW"), MeshTopology.Triangles, 3, 1, propertyBlock);
renderContext.ExecuteCommandBuffer(debugCB);
debugCB.Dispose();
CommandBufferPool.Release(debugCB);
}
}

override public void DisplayShadowMap(ScriptableRenderContext renderContext, Vector4 scaleBias, uint slice, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue)
{
CommandBuffer debugCB = new CommandBuffer();
CommandBuffer debugCB = CommandBufferPool.Get();
debugCB.name = "";
Vector4 validRange = new Vector4(minValue, 1.0f / (maxValue - minValue));

debugCB.DrawProcedural(Matrix4x4.identity, m_DebugMaterial, m_DebugMaterial.FindPass("VARIANCESHADOW"), MeshTopology.Triangles, 3, 1, propertyBlock);
renderContext.ExecuteCommandBuffer(debugCB);
debugCB.Dispose();
CommandBufferPool.Release(debugCB);
}
}
// -------------------------------------------------------------------------------------------------------------------------------------------------

m_ShadowCtxt.SyncData();
}
public override void BindResources( ScriptableRenderContext renderContext )
public override void BindResources(ScriptableRenderContext renderContext)
foreach( var sm in m_Shadowmaps )
foreach (var sm in m_Shadowmaps)
sm.Fill( m_ShadowCtxt );
sm.Fill(m_ShadowCtxt);
CommandBuffer cb = new CommandBuffer(); // <- can we just keep this around or does this have to be newed every frame?
CommandBuffer cb = CommandBufferPool.Get(); // <- can we just keep this around or does this have to be newed every frame?
m_ShadowCtxt.BindResources( cb );
renderContext.ExecuteCommandBuffer( cb );
cb.Dispose();
m_ShadowCtxt.BindResources(cb);
renderContext.ExecuteCommandBuffer(cb);
CommandBufferPool.Release(cb);
}
// resets the shadow slot counters and returns the sum of all slots

11
Assets/ScriptableRenderPipeline/Core/TextureCache.cs


return sliceIndex;
}
private static List<int> s_TempIntList = new List<int>();
var tmpBuffer = new int[m_NumTextures];
s_TempIntList.Clear();
tmpBuffer[i] = m_SortedIdxArray[i]; // copy buffer
s_TempIntList.Add(m_SortedIdxArray[i]); // copy buffer
if (m_SliceArray[tmpBuffer[i]].countLRU == 0)
if (m_SliceArray[s_TempIntList[i]].countLRU == 0)
m_SortedIdxArray[zerosBase + numNonZeros] = tmpBuffer[i];
m_SortedIdxArray[zerosBase + numNonZeros] = s_TempIntList[i];
m_SortedIdxArray[nonZerosBase] = tmpBuffer[i];
m_SortedIdxArray[nonZerosBase] = s_TempIntList[i];
++nonZerosBase;
}
}

70
Assets/ScriptableRenderPipeline/Fptl/FptlLighting.cs


static void RenderGBuffer(CullResults cull, Camera camera, ScriptableRenderContext loop)
{
// setup GBuffer for rendering
var cmd = new CommandBuffer { name = "Create G-Buffer" };
var cmd = CommandBufferPool.Get ("Create G-Buffer");
cmd.Dispose();
CommandBufferPool.Release(cmd);
// render opaque objects using Deferred pass
var settings = new DrawRendererSettings(cull, camera, new ShaderPassName("Deferred"))
{

void RenderForward(CullResults cull, Camera camera, ScriptableRenderContext loop, bool opaquesOnly)
{
var cmd = new CommandBuffer { name = opaquesOnly ? "Prep Opaques Only Forward Pass" : "Prep Forward Pass" };
var cmd = CommandBufferPool.Get(opaquesOnly ? "Prep Opaques Only Forward Pass" : "Prep Forward Pass" );
bool useFptl = opaquesOnly && usingFptl; // requires depth pre-pass for forward opaques!

cmd.SetGlobalBuffer("g_vLightListGlobal", useFptl ? s_LightList : s_PerVoxelLightLists);
loop.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
// render opaque objects using Deferred pass
var settings = new DrawRendererSettings(cull, camera, new ShaderPassName("ForwardSinglePass"))

static void DepthOnlyForForwardOpaques(CullResults cull, Camera camera, ScriptableRenderContext loop)
{
var cmd = new CommandBuffer { name = "Forward Opaques - Depth Only" };
var cmd = CommandBufferPool.Get("Forward Opaques - Depth Only" );
cmd.Dispose();
CommandBufferPool.Release(cmd);
// render opaque objects using Deferred pass
var settings = new DrawRendererSettings(cull, camera, new ShaderPassName("DepthOnly"))

static void CopyDepthAfterGBuffer(ScriptableRenderContext loop)
{
var cmd = new CommandBuffer { name = "Copy depth" };
var cmd = CommandBufferPool.Get("Copy depth");
cmd.Dispose();
CommandBufferPool.Release(cmd);
var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
m_DeferredMaterial.EnableKeyword(bUseClusteredForDeferred ? "USE_CLUSTERED_LIGHTLIST" : "USE_FPTL_LIGHTLIST");
m_DeferredReflectionMaterial.EnableKeyword(bUseClusteredForDeferred ? "USE_CLUSTERED_LIGHTLIST" : "USE_FPTL_LIGHTLIST");

cmd.SetRenderTarget(new RenderTargetIdentifier(s_CameraTarget), new RenderTargetIdentifier(s_CameraDepthTexture));
loop.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
private static void SetMatrixCS(CommandBuffer cmd, ComputeShader shadercs, string name, Matrix4x4 mat)

dirLightCount++;
}
}
s_DirLightList.SetData(lights.ToArray());
s_DirLightList.SetData(lights);
return dirLightCount;
}

m_FrameId.frameCount++;
// get the indices for all lights that want to have shadows
m_ShadowRequests.Clear();
m_ShadowRequests.Capacity = inputs.visibleLights.Length;
int lcnt = inputs.visibleLights.Length;
m_ShadowRequests.Capacity = inputs.visibleLights.Count;
int lcnt = inputs.visibleLights.Count;
for (int i = 0; i < lcnt; ++i)
{
VisibleLight vl = inputs.visibleLights[i];

uint shadowRequestCount = (uint)m_ShadowRequests.Count;
int[] shadowRequests = m_ShadowRequests.ToArray();
int[] shadowDataIndices;
m_ShadowMgr.ProcessShadowRequests(m_FrameId, inputs, camera, inputs.visibleLights,
m_ShadowMgr.ProcessShadowRequests(m_FrameId, inputs, camera, inputs.visibleLights.ToArray(),
ref shadowRequestCount, shadowRequests, out shadowDataIndices);
// update the visibleLights with the shadow information

}
var numLights = inputs.visibleLights.Length;
var numProbes = probes.Length;
var numLights = inputs.visibleLights.Count;
var numProbes = probes.Count;
var numVolumes = numLights + numProbes;

return numLightsOut + numProbesOut;
}
CullResults m_CullResults;
public void Render(ScriptableRenderContext renderContext, IEnumerable<Camera> cameras)
{
foreach (var camera in cameras)

continue;
m_ShadowMgr.UpdateCullingParameters( ref cullingParams );
var cullResults = CullResults.Cull(ref cullingParams, renderContext);
ExecuteRenderLoop(camera, cullResults, renderContext);
CullResults.Cull(ref cullingParams, renderContext, ref m_CullResults);
ExecuteRenderLoop(camera, m_CullResults, renderContext);
}
renderContext.Submit();

{
var cmd = new CommandBuffer { name = "FinalPass" };
var cmd = CommandBufferPool.Get("FinalPass");
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
void ExecuteRenderLoop(Camera camera, CullResults cullResults, ScriptableRenderContext loop)

BuildPerTileLightLists(camera, loop, numLights, projscr, invProjscr);
m_ShadowMgr.RenderShadows( m_FrameId, loop, cullResults, cullResults.visibleLights );
m_ShadowMgr.RenderShadows( m_FrameId, loop, cullResults, cullResults.visibleLights.ToArray() );
m_ShadowMgr.SyncData();
m_ShadowMgr.BindResources( loop );

if (enableClustered) RenderForward(cullResults, camera, loop, false);
// debug views.
if (enableDrawLightBoundsDebug) DrawLightBoundsDebug(loop, cullResults.visibleLights.Length);
if (enableDrawLightBoundsDebug) DrawLightBoundsDebug(loop, cullResults.visibleLights.Count);
// present frame buffer.
FinalPass(loop);

{
var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
loop.Submit();
}

var cmd = new CommandBuffer { name = "DrawLightBoundsDebug" };
var cmd = CommandBufferPool.Get("DrawLightBoundsDebug");
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
void NewFrame()

var numBigTilesX = (w + 63) / 64;
var numBigTilesY = (h + 63) / 64;
var cmd = new CommandBuffer() { name = "Build light list" };
var cmd = CommandBufferPool.Get("Build light list" );
// generate screen-space AABBs (used for both fptl and clustered).
if (numLights != 0)

}
loop.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
var cmd = new CommandBuffer { name = "Push Global Parameters" };
var cmd = CommandBufferPool.Get("Push Global Parameters");
cmd.SetGlobalFloat("g_widthRT", (float)camera.pixelWidth);
cmd.SetGlobalFloat("g_heightRT", (float)camera.pixelHeight);

cmd.SetGlobalVector("g_vShadow3x3PCFTerms3", m_Shadow3X3PCFTerms[3]);
loop.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
private float PerceptualRoughnessToBlinnPhongPower(float perceptualRoughness)

4
Assets/ScriptableRenderPipeline/Fptl/SkyboxHelper.cs


return;
}
var cmd = new CommandBuffer { name = "Skybox" };
var cmd = CommandBufferPool.Get("Skybox");
var looksLikeSixSidedShader = true;
looksLikeSixSidedShader &= (mat.passCount == 6); // should have six passes

}
loop.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
public static Matrix4x4 GetProjectionMatrix(Camera camera)

39
Assets/ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs


using UnityEngine.SceneManagement;
using UnityEngine.Experimental.Rendering.HDPipeline;
using System.IO;
using UnityEngine.Experimental.Rendering;
// This script is a helper for the artists to re-synchronise all layered materials
[UnityEditor.MenuItem("HDRenderPipeline/Add \"Additional Light Data\" (if not present)")]
static void AddAdditionalLightData()
{
Light[] lights = GameObject.FindObjectsOfType(typeof(Light)) as Light[];
foreach (Light light in lights)
{
// Do not add a component if there already is one.
if (light.GetComponent<AdditionalLightData>() == null)
{
light.gameObject.AddComponent<AdditionalLightData>();
}
}
}
[UnityEditor.MenuItem("HDRenderPipeline/Add \"Additional Camera Data\" (if not present)")]
static void AddAdditionalCameraData()
{
Camera[] cameras = GameObject.FindObjectsOfType(typeof(Camera)) as Camera[];
foreach (Camera camera in cameras)
{
// Do not add a component if there already is one.
if (camera.GetComponent<HDAdditionalCameraData>() == null)
{
camera.gameObject.AddComponent<HDAdditionalCameraData>();
}
}
}
// This script is a helper for the artists to re-synchronize all layered materials
[MenuItem("HDRenderPipeline/Synchronize all Layered materials")]
static void SynchronizeAllLayeredMaterial()
{

// In case the shader code have change and the inspector have been update with new kind of keywords we need to regenerate the set of keywords use by the material.
// This script will remove all keyword of a material and trigger the inspector that will re-setup all the used keywords.
// It require that the inspector of the material have a static function call that update all keyword based on material properties.
[MenuItem("HDRenderPipeline/Reset all materials keywords")]
[MenuItem("HDRenderPipeline/Test/Reset all materials keywords")]
static void ResetAllMaterialKeywords()
{
try

}
}
// Funtion used only to check performance of data with and without tessellation
[MenuItem("HDRenderPipeline/Debug/Remove tessellation materials (not reversible)")]
// Function used only to check performance of data with and without tessellation
[MenuItem("HDRenderPipeline/Test/Remove tessellation materials (not reversible)")]
static void RemoveTessellationMaterials()
{
Object[] materials = Resources.FindObjectsOfTypeAll<Material>();

6
Assets/ScriptableRenderPipeline/HDRenderPipeline/Editor/UpgradeStandardShaderMaterials.cs


return upgraders;
}
[MenuItem("HDRenderPipeline/Upgrade Materials - Project")]
[MenuItem("RenderPipeline/HDRenderPipeline/Material Upgraders/Upgrade Standard Materials to Lit Materials - Project Folder", false, 1)]
[MenuItem("HDRenderPipeline/Upgrade Materials - Selection")]
[MenuItem("RenderPipeline/HDRenderPipeline/Material Upgraders/Upgrade Standard Materials to Lit Materials - Selection", false, 2)]
[MenuItem("HDRenderPipeline/Modify Light Intensity for Upgrade - Scene Only")]
[MenuItem("RenderPipeline/HDRenderPipeline/Material Upgraders/Modify Light Intensity for Upgrade - Scene Only", false, 3)]
static void UpgradeLights()
{
Light[] lights = Light.GetLights(LightType.Directional, 0);

298
Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs


}
}
public struct HDCamera
// This holds all the matrix data we need for rendering, including data from the previous frame
// (which is the main reason why we need to keep them around for a minimum of one frame).
// HDCameras are automatically created & updated from a source camera and will be destroyed if
// not used during a frame.
public class HDCamera
public Camera camera;
public Vector4 screenSize;
public Matrix4x4 viewProjectionMatrix;
public Matrix4x4 invViewProjectionMatrix;
public Matrix4x4 invProjectionMatrix;
public Vector4 invProjectionParam;
public readonly Camera camera;
public Vector4 screenSize { get; private set; }
public Matrix4x4 viewProjectionMatrix { get; private set; }
public Matrix4x4 prevViewProjectionMatrix { get; private set; }
public Matrix4x4 invViewProjectionMatrix { get; private set; }
public Matrix4x4 invProjectionMatrix { get; private set; }
public Vector4 invProjectionParam { get; private set; }
// The only way to reliably keep track of a frame change right now is to compare the frame
// count Unity gives us. We need this as a single camera could be rendered several times per
// frame and some matrices only have to be computed once. Realistically this shouldn't
// 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;
public HDCamera(Camera camera)
{
this.camera = camera;
Reset();
}
public void Update()
{
screenSize = new Vector4(camera.pixelWidth, camera.pixelHeight, 1.0f / camera.pixelWidth, 1.0f / camera.pixelHeight);
// The actual projection matrix used in shaders is actually massaged a bit to work across all platforms
// (different Z value ranges etc.)
var gpuProj = GL.GetGPUProjectionMatrix(camera.projectionMatrix, false);
var gpuVP = gpuProj * camera.worldToCameraMatrix;
// A camera could be rendered multiple time per frame, only updates the previous viewproj if needed
if (m_LastFrameActive != Time.frameCount)
{
prevViewProjectionMatrix = !m_FirstFrame
? viewProjectionMatrix
: gpuVP;
m_FirstFrame = false;
}
// Ref: An Efficient Depth Linearization Method for Oblique View Frustums, Eq. 6.
var invProjParam = new Vector4(
gpuProj.m20 / (gpuProj.m00 * gpuProj.m23),
gpuProj.m21 / (gpuProj.m11 * gpuProj.m23),
-1.0f / gpuProj.m23,
(-gpuProj.m22
+ gpuProj.m20 * gpuProj.m02 / gpuProj.m00
+ gpuProj.m21 * gpuProj.m12 / gpuProj.m11) / gpuProj.m23
);
viewProjectionMatrix = gpuVP;
invViewProjectionMatrix = gpuVP.inverse;
invProjectionMatrix = gpuProj.inverse;
invProjectionParam = invProjParam;
m_LastFrameActive = Time.frameCount;
}
public void SetupMaterial(Material material)
{
material.SetVector("_ScreenSize", screenSize);
material.SetMatrix("_ViewProjMatrix", viewProjectionMatrix);
material.SetMatrix("_PrevViewProjMatrix", prevViewProjectionMatrix);
material.SetMatrix("_InvViewProjMatrix", invViewProjectionMatrix);
material.SetMatrix("_InvProjMatrix", invProjectionMatrix);
material.SetVector("_InvProjParam", invProjectionParam);
}
public void Reset()
{
m_LastFrameActive = -1;
m_FirstFrame = true;
}
static Dictionary<Camera, HDCamera> m_Cameras = new Dictionary<Camera, HDCamera>();
static List<Camera> m_Cleanup = new List<Camera>(); // Recycled to reduce GC pressure
// Grab the HDCamera tied to a given Camera and update it.
public static HDCamera Get(Camera camera)
{
HDCamera hdcam;
if (!m_Cameras.TryGetValue(camera, out hdcam))
{
hdcam = new HDCamera(camera);
m_Cameras.Add(camera, hdcam);
}
hdcam.Update();
return hdcam;
}
// Look for any camera that hasn't been used in the last frame and remove them for the pool.
public static void CleanUnused()
{
int frameCheck = Time.frameCount - 1;
foreach (var kvp in m_Cameras)
{
if (kvp.Value.m_LastFrameActive != frameCheck)
m_Cleanup.Add(kvp.Key);
}
foreach (var cam in m_Cleanup)
m_Cameras.Remove(cam);
m_Cleanup.Clear();
}
}
public class GBufferManager

}
}
private RenderTargetIdentifier[] m_ColorMRTs;
var colorMRTs = new RenderTargetIdentifier[gbufferCount];
if (m_ColorMRTs == null || m_ColorMRTs.Length != gbufferCount)
m_ColorMRTs = new RenderTargetIdentifier[gbufferCount];
colorMRTs[index] = RTIDs[index];
m_ColorMRTs[index] = RTIDs[index];
return colorMRTs;
return m_ColorMRTs;
}
public int gbufferCount { get; set; }

// Old SSS Model >>>
Material m_FilterSubsurfaceScattering;
// <<< Old SSS Model
Material m_CameraMotionVectorsMaterial;
Material m_DebugViewMaterialGBuffer;
Material m_DebugDisplayLatlong;

// Detect when windows size is changing
int m_CurrentWidth;
int m_CurrentHeight;
// Use to detect frame changes
int m_FrameCount;
public int GetCurrentShadowCount() { return m_LightLoop.GetCurrentShadowCount(); }
public int GetShadowAtlasCount() { return m_LightLoop.GetShadowAtlasCount(); }

m_CameraFilteringBufferRT = new RenderTargetIdentifier(m_CameraFilteringBuffer);
CreateSssMaterials(sssSettings.useDisneySSS);
// <<< Old SSS Model
m_CameraMotionVectorsMaterial = Utilities.CreateEngineMaterial("Hidden/HDRenderPipeline/CameraMotionVectors");
InitializeDebugMaterials();

public void PushGlobalParams(HDCamera hdCamera, ScriptableRenderContext renderContext, SubsurfaceScatteringSettings sssParameters)
{
var cmd = new CommandBuffer {name = "Push Global Parameters"};
var cmd = CommandBufferPool.Get("Push Global Parameters");
cmd.SetGlobalVector("_ScreenSize", hdCamera.screenSize);
cmd.SetGlobalMatrix("_ViewProjMatrix", hdCamera.viewProjectionMatrix);
cmd.SetGlobalMatrix("_InvViewProjMatrix", hdCamera.invViewProjectionMatrix);
cmd.SetGlobalMatrix("_InvProjMatrix", hdCamera.invProjectionMatrix);
cmd.SetGlobalVector("_InvProjParam", hdCamera.invProjectionParam);
cmd.SetGlobalVector("_ScreenSize", hdCamera.screenSize);
cmd.SetGlobalMatrix("_ViewProjMatrix", hdCamera.viewProjectionMatrix);
cmd.SetGlobalMatrix("_PrevViewProjMatrix", hdCamera.prevViewProjectionMatrix);
cmd.SetGlobalMatrix("_InvViewProjMatrix", hdCamera.invViewProjectionMatrix);
cmd.SetGlobalMatrix("_InvProjMatrix", hdCamera.invProjectionMatrix);
cmd.SetGlobalVector("_InvProjParam", hdCamera.invProjectionParam);
// TODO: cmd.SetGlobalInt() does not exist, so we are forced to use Shader.SetGlobalInt() instead.

cmd.SetGlobalVectorArray("_TransmissionTints", sssParameters.transmissionTints);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
bool NeedDepthBufferCopy()

private void CopyDepthBufferIfNeeded(ScriptableRenderContext renderContext)
{
var cmd = new CommandBuffer() { name = NeedDepthBufferCopy() ? "Copy DepthBuffer" : "Set DepthBuffer"};
var cmd = CommandBufferPool.Get(NeedDepthBufferCopy() ? "Copy DepthBuffer" : "Set DepthBuffer");
if (NeedDepthBufferCopy())
{

cmd.SetGlobalTexture("_MainDepthTexture", GetDepthTexture());
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
public void UpdateCommonSettings()

m_ShadowSettings.directionalLightNearPlaneOffset = commonSettings.shadowNearPlaneOffset;
}
CullResults m_CullResults;
public override void Render(ScriptableRenderContext renderContext, Camera[] cameras)
{
base.Render(renderContext, cameras);

#endif
if (m_FrameCount != Time.frameCount)
{
HDCamera.CleanUnused();
m_FrameCount = Time.frameCount;
}
GraphicsSettings.lightsUseLinearIntensity = true;
GraphicsSettings.lightsUseColorTemperature = true;

// we only want to render one camera for now
// select the most main camera!
Camera camera = cameras.OrderByDescending(x => x.tag == "MainCamera").FirstOrDefault();
Camera camera = null;
foreach (var cam in cameras)
{
if (cam == Camera.main)
{
camera = cam;
break;
}
}
if (camera == null && cameras.Length > 0)
camera = cameras[0];
if (camera == null)
{
renderContext.Submit();

m_LightLoop.UpdateCullingParameters( ref cullingParams );
var cullResults = CullResults.Cull(ref cullingParams, renderContext);
CullResults.Cull(ref cullingParams, renderContext,ref m_CullResults);
HDCamera hdCamera = Utilities.GetHDCamera(camera);
var hdCamera = HDCamera.Get(camera);
var additionalCameraData = camera.GetComponent<HDAdditionalCameraData>();
if (additionalCameraData && additionalCameraData.renderingPath == RenderingPathHDRP.Unlit)
{
// TODO: Add another path dedicated to planar reflection / real time cubemap that implement simpler lighting
string passName = "Forward"; // It is up to the users to only send unlit object for this camera path
using (new Utilities.ProfilingSample(passName, renderContext))
{
Utilities.SetRenderTarget(renderContext, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.ClearColor | ClearFlag.ClearDepth);
RenderOpaqueRenderList(m_CullResults, camera, renderContext, passName);
RenderTransparentRenderList(m_CullResults, camera, renderContext, passName);
}
renderContext.Submit();
return;
}
RenderDepthPrepass(cullResults, camera, renderContext);
RenderDepthPrepass(m_CullResults, camera, renderContext);
RenderForwardOnlyOpaqueDepthPrepass(cullResults, camera, renderContext);
RenderGBuffer(cullResults, camera, renderContext);
RenderForwardOnlyOpaqueDepthPrepass(m_CullResults, camera, renderContext);
RenderGBuffer(m_CullResults, camera, renderContext);
// If full forward rendering, we did not do any rendering yet, so don't need to copy the buffer.
// If Deferred then the depth buffer is full (regular GBuffer + ForwardOnly depth prepass are done so we can copy it safely.

if (m_DebugDisplaySettings.IsDebugMaterialDisplayEnabled())
{
RenderDebugViewMaterial(cullResults, hdCamera, renderContext);
RenderDebugViewMaterial(m_CullResults, hdCamera, renderContext);
}
else
{

m_SsaoEffect.Render(ssaoSettingsToUse, this, hdCamera, renderContext, m_Asset.renderingSettings.useForwardRenderingOnly);
m_LightLoop.PrepareLightsForGPU(m_ShadowSettings, cullResults, camera);
m_LightLoop.RenderShadows(renderContext, cullResults);
m_LightLoop.PrepareLightsForGPU(m_ShadowSettings, m_CullResults, camera);
m_LightLoop.RenderShadows(renderContext, m_CullResults);
renderContext.SetupCameraProperties(camera); // Need to recall SetupCameraProperties after m_ShadowPass.Render
m_LightLoop.BuildGPULightLists(camera, renderContext, m_CameraDepthStencilBufferRT);
}

// For opaque forward we have split rendering in two categories
// Material that are always forward and material that can be deferred or forward depends on render pipeline options (like switch to rendering forward only mode)
// Material that are always forward are unlit and complex (Like Hair) and don't require sorting, so it is ok to split them.
RenderForward(cullResults, camera, renderContext, true); // Render deferred or forward opaque
RenderForwardOnlyOpaque(cullResults, camera, renderContext);
RenderForward(m_CullResults, camera, renderContext, true); // Render deferred or forward opaque
RenderForwardOnlyOpaque(m_CullResults, camera, renderContext);
RenderLightingDebug(hdCamera, renderContext, m_CameraColorBufferRT);

RenderSky(hdCamera, renderContext);
// Render all type of transparent forward (unlit, lit, complex (hair...)) to keep the sorting between transparent objects.
RenderForward(cullResults, camera, renderContext, false);
RenderForward(m_CullResults, camera, renderContext, false);
var cmd = new CommandBuffer { name = "Blit to final RT" };
var cmd = CommandBufferPool.Get("Blit to final RT" );
cmd.Dispose();
CommandBufferPool.Release(cmd);
RenderVelocity(cullResults, camera, renderContext); // Note we may have to render velocity earlier if we do temporalAO, temporal volumetric etc... Mean we will not take into account forward opaque in case of deferred rendering ?
RenderVelocity(m_CullResults, hdCamera, renderContext); // Note we may have to render velocity earlier if we do temporalAO, temporal volumetric etc... Mean we will not take into account forward opaque in case of deferred rendering ?
RenderDistortion(cullResults, camera, renderContext);
RenderDistortion(m_CullResults, camera, renderContext);
RenderPostProcesses(camera, renderContext);
}

// bind depth surface for editor grid/gizmo/selection rendering
if (camera.cameraType == CameraType.SceneView)
{
var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
renderContext.Submit();

// Render GBuffer opaque
if (!m_Asset.renderingSettings.ShouldUseForwardRenderingOnly())
{
Utilities.SetupMaterialHDCamera(hdCamera, m_DebugViewMaterialGBuffer);
hdCamera.SetupMaterial(m_DebugViewMaterialGBuffer);
var cmd = new CommandBuffer { name = "DebugViewMaterialGBuffer" };
var cmd = CommandBufferPool.Get("DebugViewMaterialGBuffer" );
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
// Render forward transparent

// Last blit
{
var cmd = new CommandBuffer { name = "Blit DebugView Material Debug" };
var cmd = CommandBufferPool.Get("Blit DebugView Material Debug");
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
}

if (!m_DebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission || m_Asset.renderingSettings.ShouldUseForwardRenderingOnly())
return;
var cmd = new CommandBuffer() { name = "Subsurface Scattering" };
var cmd = CommandBufferPool.Get("Subsurface Scattering");
// Temp >>>
Matrix4x4 viewMatrix = hdCamera.camera.worldToCameraMatrix;
viewMatrix.SetRow(2, -viewMatrix.GetRow(2)); // Make Z axis point forwards in the view space (left-handed CS)
Matrix4x4 projMatrix = GL.GetGPUProjectionMatrix(hdCamera.camera.projectionMatrix, false);
projMatrix.SetColumn(2, -projMatrix.GetColumn(2)); // Undo the view-space transformation
m_FilterAndCombineSubsurfaceScattering.SetMatrix("_ViewMatrix", viewMatrix);
m_FilterAndCombineSubsurfaceScattering.SetMatrix("_ProjMatrix", projMatrix);
// <<< Temp
m_FilterAndCombineSubsurfaceScattering.SetFloatArray("_WorldScales", sssParameters.worldScales);
m_FilterAndCombineSubsurfaceScattering.SetFloatArray("_FilterKernelsNearField", sssParameters.filterKernelsNearField);
m_FilterAndCombineSubsurfaceScattering.SetFloatArray("_FilterKernelsFarField", sssParameters.filterKernelsFarField);

}
context.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
void UpdateSkyEnvironment(HDCamera hdCamera, ScriptableRenderContext renderContext)

}
}
void RenderVelocity(CullResults cullResults, Camera camera, ScriptableRenderContext renderContext)
void RenderVelocity(CullResults cullResults, HDCamera hdcam, ScriptableRenderContext renderContext)
{
using (new Utilities.ProfilingSample("Velocity", renderContext))
{

int w = camera.pixelWidth;
int h = camera.pixelHeight;
// These flags are still required in SRP or the engine won't compute previous model matrices...
// If the flag hasn't been set yet on this camera, motion vectors will skip a frame.
hdcam.camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth;
var cmd = new CommandBuffer { name = "" };
int w = (int)hdcam.screenSize.x;
int h = (int)hdcam.screenSize.y;
var cmd = CommandBufferPool.Get("");
cmd.Blit(BuiltinRenderTextureType.None, m_VelocityBufferRT, m_CameraMotionVectorsMaterial, 0);
cmd.Dispose();
RenderOpaqueRenderList(cullResults, camera, renderContext, "MotionVectors");
RenderOpaqueRenderList(cullResults, hdcam.camera, renderContext, "MotionVectors", RendererConfiguration.PerObjectMotionVectors);
}
}

int w = camera.pixelWidth;
int h = camera.pixelHeight;
var cmd = new CommandBuffer { name = "" };
var cmd = CommandBufferPool.Get("");
cmd.Dispose();
CommandBufferPool.Release(cmd);
// Only transparent object can render distortion vectors
RenderTransparentRenderList(cullResults, camera, renderContext, "DistortionVectors");

using (new Utilities.ProfilingSample("Post-processing", renderContext))
{
var postProcessLayer = camera.GetComponent<PostProcessLayer>();
var cmd = new CommandBuffer { name = "" };
var cmd = CommandBufferPool.Get("");
cmd.SetGlobalTexture("_CameraMotionVectorsTexture", m_VelocityBufferRT);
var context = m_PostProcessContext;
context.Reset();

context.camera = camera;
context.sourceFormat = RenderTextureFormat.ARGBHalf; // ?
context.sourceFormat = RenderTextureFormat.ARGBHalf;
context.flip = true;
postProcessLayer.Render(context);

}
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
}

}
}
MaterialPropertyBlock m_SharedPropertyBlock = new MaterialPropertyBlock();
void RenderDebug(HDCamera camera, ScriptableRenderContext renderContext)
{
// We don't want any overlay for these kind of rendering

// We make sure the depth buffer is bound because we need it to write depth at near plane for overlays otherwise the editor grid end up visible in them.
Utilities.SetRenderTarget(renderContext, BuiltinRenderTextureType.CameraTarget, m_CameraDepthStencilBufferRT);
CommandBuffer debugCB = new CommandBuffer();
CommandBuffer debugCB = CommandBufferPool.Get();
debugCB.name = "Render Debug";
// First render full screen debug texture

float overlaySize = Math.Min(camera.camera.pixelHeight, camera.camera.pixelWidth) * overlayRatio;
float y = camera.camera.pixelHeight - overlaySize;
MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
propertyBlock.SetTexture("_InputCubemap", skyReflection);
propertyBlock.SetFloat("_Mipmap", lightingDebug.skyReflectionMipmap);
m_SharedPropertyBlock.SetTexture("_InputCubemap", skyReflection);
m_SharedPropertyBlock.SetFloat("_Mipmap", lightingDebug.skyReflectionMipmap);
debugCB.DrawProcedural(Matrix4x4.identity, m_DebugDisplayLatlong, 0, MeshTopology.Triangles, 3, 1, propertyBlock);
debugCB.DrawProcedural(Matrix4x4.identity, m_DebugDisplayLatlong, 0, MeshTopology.Triangles, 3, 1, m_SharedPropertyBlock);
CommandBufferPool.Release(debugCB);
m_LightLoop.RenderDebugOverlay(camera.camera, renderContext, m_DebugDisplaySettings, ref x, ref y, overlaySize, camera.camera.pixelWidth);
}

// Clear depth/stencil and init buffers
using (new Utilities.ProfilingSample("InitGBuffers and clear Depth/Stencil", renderContext))
{
var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
cmd.name = "";
// Init buffer

}
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
Utilities.SetRenderTarget(renderContext, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.ClearDepth);
}

17
Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.cs


#if UNITY_EDITOR
const string k_HDRenderPipelinePath = "Assets/ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipelineAsset.asset";
[MenuItem("RenderPipeline/HDRenderPipeline/Create Pipeline Asset")]
[MenuItem("RenderPipeline/HDRenderPipeline/Create Pipeline Asset", false, 16)]
static void CreateHDRenderPipeline()
{
var instance = CreateInstance<HDRenderPipelineAsset>();

instance.renderPipelineResources = AssetDatabase.LoadAssetAtPath<RenderPipelineResources>(RenderPipelineResources.renderPipelineResourcesPath);
}
[UnityEditor.MenuItem("HDRenderPipeline/Add \"Additional Light Data\" (if not present)")]
static void AddAdditionalLightData()
{
Light[] lights = FindObjectsOfType(typeof(Light)) as Light[];
foreach (Light light in lights)
{
// Do not add a component if there already is one.
if (light.GetComponent<AdditionalLightData>() == null)
{
light.gameObject.AddComponent<AdditionalLightData>();
}
}
}
#endif

4
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/AmbientOcclusion/ScreenSpaceAmbientOcclusion.cs


if (m_Command == null)
{
m_Command = new CommandBuffer { name = "Ambient Occlusion" };
m_Command = new CommandBuffer();
m_Command.name = "Ambient Occlusion";
}
else
{

public void Cleanup()
{
Utilities.Destroy(m_Material);
if (m_Command != null) m_Command.Dispose();
}
}
}

64
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs


{
m_lightList.Clear();
if (cullResults.visibleLights.Length != 0 || cullResults.visibleReflectionProbes.Length != 0)
if (cullResults.visibleLights.Count != 0 || cullResults.visibleReflectionProbes.Count != 0)
{
// 0. deal with shadows
{

m_ShadowRequests.Capacity = cullResults.visibleLights.Length;
int lcnt = cullResults.visibleLights.Length;
m_ShadowRequests.Capacity = cullResults.visibleLights.Count;
int lcnt = cullResults.visibleLights.Count;
for (int i = 0; i < lcnt; ++i)
{
VisibleLight vl = cullResults.visibleLights[i];

}
// pass this list to a routine that assigns shadows based on some heuristic
uint shadowRequestCount = (uint)m_ShadowRequests.Count;
//TODO: Do not call ToArray here to avoid GC, refactor API
m_ShadowMgr.ProcessShadowRequests(m_FrameId, cullResults, camera, cullResults.visibleLights,
m_ShadowMgr.ProcessShadowRequests(m_FrameId, cullResults, camera, cullResults.visibleLights.ToArray(),
ref shadowRequestCount, shadowRequests, out shadowDataIndices);
// update the visibleLights with the shadow information

int areaLightCount = 0;
int projectorLightCount = 0;
int lightCount = Math.Min(cullResults.visibleLights.Length, k_MaxLightsOnScreen);
int lightCount = Math.Min(cullResults.visibleLights.Count, k_MaxLightsOnScreen);
for (int lightIndex = 0, numLights = cullResults.visibleLights.Length; (lightIndex < numLights) && (sortCount < lightCount); ++lightIndex)
for (int lightIndex = 0, numLights = cullResults.visibleLights.Count; (lightIndex < numLights) && (sortCount < lightCount); ++lightIndex)
{
var light = cullResults.visibleLights[lightIndex];

sortKeys[sortCount++] = (uint)lightCategory << 27 | (uint)gpuLightType << 22 | (uint)lightVolumeType << 17 | shadow << 16 | (uint)lightIndex;
}
//TODO: Replace with custom sort, allocates mem and increases GC pressure.
Array.Sort(sortKeys, 0, sortCount);
// TODO: Refactor shadow management

// Redo everything but this time with envLights
int envLightCount = 0;
int probeCount = Math.Min(cullResults.visibleReflectionProbes.Length, k_MaxEnvLightsOnScreen);
int probeCount = Math.Min(cullResults.visibleReflectionProbes.Count, k_MaxEnvLightsOnScreen);
for (int probeIndex = 0, numProbes = cullResults.visibleReflectionProbes.Length; (probeIndex < numProbes) && (sortCount < probeCount); probeIndex++)
for (int probeIndex = 0, numProbes = cullResults.visibleReflectionProbes.Count; (probeIndex < numProbes) && (sortCount < probeCount); probeIndex++)
{
var probe = cullResults.visibleReflectionProbes[probeIndex];

var projscr = temp * proj;
var invProjscr = projscr.inverse;
var cmd = new CommandBuffer() { name = "" };
var cmd = CommandBufferPool.Get("");
cmd.SetRenderTarget(new RenderTargetIdentifier((Texture)null));
// generate screen-space AABBs (used for both fptl and clustered).

// enable coarse 2D pass on 64x64 tiles (used for both fptl and clustered).
if (m_TileSettings.enableBigTilePrepass)
{
cmd.SetComputeIntParams(buildPerBigTileLightListShader, "g_viDimensions", new int[2] { w, h });
cmd.SetComputeIntParams(buildPerBigTileLightListShader, "g_viDimensions", w, h);
cmd.SetComputeIntParam(buildPerBigTileLightListShader, "_EnvLightIndexShift", m_lightList.lights.Count);
cmd.SetComputeIntParam(buildPerBigTileLightListShader, "g_iNrVisibLights", m_lightCount);
Utilities.SetMatrixCS(cmd, buildPerBigTileLightListShader, "g_mScrProjection", projscr);

if (usingFptl) // optimized for opaques only
{
cmd.SetComputeIntParams(buildPerTileLightListShader, "g_viDimensions", new int[2] { w, h });
cmd.SetComputeIntParams(buildPerTileLightListShader, "g_viDimensions", w, h);
cmd.SetComputeIntParam(buildPerTileLightListShader, "_EnvLightIndexShift", m_lightList.lights.Count);
cmd.SetComputeIntParam(buildPerTileLightListShader, "g_iNrVisibLights", m_lightCount);

}
cmd.SetComputeIntParam(buildMaterialFlagsShader, "g_BaseFeatureFlags", (int)baseFeatureFlags);
cmd.SetComputeIntParams(buildMaterialFlagsShader, "g_viDimensions", new int[2] { w, h });
cmd.SetComputeIntParams(buildMaterialFlagsShader, "g_viDimensions", w, h);
cmd.SetComputeBufferParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, "g_TileFeatureFlags", s_TileFeatureFlags);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, "g_depth_tex", cameraDepthBufferRT);

cmd.SetComputeIntParam(buildDispatchIndirectShader, "g_NumTilesX", numTilesX);
cmd.DispatchCompute(buildDispatchIndirectShader, s_BuildDispatchIndirectKernel, (numTiles + 63) / 64, 1, 1);
}
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
// This is a workaround for global properties not being accessible from compute.

private void UpdateDataBuffers()
{
s_DirectionalLightDatas.SetData(m_lightList.directionalLights.ToArray());
s_LightDatas.SetData(m_lightList.lights.ToArray());
s_EnvLightDatas.SetData(m_lightList.envLights.ToArray());
s_shadowDatas.SetData(m_lightList.shadows.ToArray());
s_DirectionalLightDatas.SetData(m_lightList.directionalLights);
s_LightDatas.SetData(m_lightList.lights);
s_EnvLightDatas.SetData(m_lightList.envLights);
s_shadowDatas.SetData(m_lightList.shadows);
s_ConvexBoundsBuffer.SetData(m_lightList.bounds.ToArray());
s_LightVolumeDataBuffer.SetData(m_lightList.lightVolumes.ToArray());
s_ConvexBoundsBuffer.SetData(m_lightList.bounds);
s_LightVolumeDataBuffer.SetData(m_lightList.lightVolumes);
}
private void BindGlobalParams(CommandBuffer cmd, ComputeShader computeShader, int kernelIndex, Camera camera, ScriptableRenderContext loop)

private void PushGlobalParams(Camera camera, ScriptableRenderContext loop, ComputeShader computeShader, int kernelIndex)
{
var cmd = new CommandBuffer { name = "Push Global Parameters" };
var cmd = CommandBufferPool.Get("Push Global Parameters");
// Shadows
m_ShadowMgr.SyncData();

SetGlobalPropertyRedirect(null, 0, null);
loop.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
#if UNITY_EDITOR

public void RenderShadows(ScriptableRenderContext renderContext, CullResults cullResults)
{
// kick off the shadow jobs here
m_ShadowMgr.RenderShadows(m_FrameId, renderContext, cullResults, cullResults.visibleLights);
m_ShadowMgr.RenderShadows(m_FrameId, renderContext, cullResults, cullResults.visibleLights.ToArray());
}
private void SetupDebugDisplayMode(bool debugDisplayEnable)

if (m_TileSettings.tileDebugByCategory == TileSettings.TileDebug.None)
return;
var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
cmd.name = "Tiled Lighting Debug";
bool bUseClusteredForDeferred = !usingFptl;

if (GetFeatureVariantsEnabled())
{
// featureVariants
Utilities.SetupMaterialHDCamera(hdCamera, m_DebugViewTilesMaterial);
hdCamera.SetupMaterial(m_DebugViewTilesMaterial);
m_DebugViewTilesMaterial.SetInt("_NumTiles", numTiles);
m_DebugViewTilesMaterial.SetInt("_ViewTilesFlags", (int)m_TileSettings.tileDebugByCategory);
m_DebugViewTilesMaterial.SetVector("_MousePixelCoord", mousePixelCoord);

else if (m_TileSettings.tileDebugByCategory != TileSettings.TileDebug.None)
{
// lightCategories
Utilities.SetupMaterialHDCamera(hdCamera, m_DebugViewTilesMaterial);
hdCamera.SetupMaterial(m_DebugViewTilesMaterial);
m_DebugViewTilesMaterial.SetInt("_ViewTilesFlags", (int)m_TileSettings.tileDebugByCategory);
m_DebugViewTilesMaterial.SetVector("_MousePixelCoord", mousePixelCoord);
m_DebugViewTilesMaterial.EnableKeyword(bUseClusteredForDeferred ? "USE_CLUSTERED_LIGHTLIST" : "USE_FPTL_LIGHTLIST");

SetGlobalPropertyRedirect(null, 0, null);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
public void RenderDeferredLighting( HDCamera hdCamera, ScriptableRenderContext renderContext,

using (new Utilities.ProfilingSample((m_TileSettings.enableTileAndCluster ? "TilePass - Deferred Lighting Pass" : "SinglePass - Deferred Lighting Pass") + (outputSplitLighting ? " MRT" : ""), renderContext))
{
var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
cmd.name = bUseClusteredForDeferred ? "Clustered pass" : "Tiled pass";
var camera = hdCamera.camera;

SetGlobalPropertyRedirect(null, 0, null);
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
} // TilePass - Deferred Lighting Pass
}

bool useFptl = renderOpaque && usingFptl;
var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
if (!m_TileSettings.enableTileAndCluster)
{

}
renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
public void RenderDebugOverlay(Camera camera, ScriptableRenderContext renderContext, DebugDisplaySettings debugDisplaySettings, ref float x, ref float y, float overlaySize, float width)

10
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.hlsl


#include "TilePass.cs.hlsl"
// For FPTL
uint _NumTileFtplX;
uint _NumTileFtplY;
CBUFFER_START(UnityTilePass)
uint _NumTileFtplX;
uint _NumTileFtplY;
// these uniforms are only needed for when OPAQUES_ONLY is NOT defined
// but there's a problem with our front-end compilation of compute shaders with multiple kernels causing it to error

//#ifdef USE_CLUSTERED_LIGHTLIST
uint _NumTileClusteredX;
uint _NumTileClusteredY;
CBUFFER_END
StructuredBuffer<uint> g_vLayeredOffsetsBuffer; // don't support Buffer yet in unity
StructuredBuffer<float> g_logBaseBuffer; // don't support Buffer yet in unity
//#endif

20
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/lightlistbuild-clustered.compute


#define PERFORM_SPHERICAL_INTERSECTION_TESTS
#define CONV_HULL_TEST_ENABLED
uniform int g_iNrVisibLights;
uniform float4x4 g_mInvScrProjection;
uniform float4x4 g_mScrProjection;
uniform int _EnvLightIndexShift;
CBUFFER_START(UnityLightListClustered)
int g_iNrVisibLights;
float4x4 g_mInvScrProjection;
float4x4 g_mScrProjection;
int _EnvLightIndexShift;
uniform float g_fClustScale;
uniform float g_fClustBase;
uniform float g_fNearPlane;
uniform float g_fFarPlane;
uniform int g_iLog2NumClusters; // numClusters = (1<<g_iLog2NumClusters)
float g_fClustScale;
float g_fClustBase;
float g_fNearPlane;
float g_fFarPlane;
int g_iLog2NumClusters; // numClusters = (1<<g_iLog2NumClusters)
CBUFFER_END
#include "ClusteredUtils.hlsl"

6
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/materialflags.compute


#define USE_MATERIAL_FEATURE_FLAGS
#define NR_THREADS 64
uniform uint2 g_viDimensions;
CBUFFER_START(UnityMaterialFlags)
uint2 g_viDimensions;
uint g_BaseFeatureFlags;
CBUFFER_END
uniform uint g_BaseFeatureFlags;
DECLARE_GBUFFER_TEXTURE(_GBufferTexture);

5
Assets/ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/shadeopaque.compute


RWTexture2D<float4> combinedLightingUAV;
#endif
CBUFFER_START(UnityShadeOpaque)
uint g_TileListOffset;
CBUFFER_END
uint g_TileListOffset;
StructuredBuffer<uint> g_TileList;
// Indirect
[numthreads(16, 16, 1)]

3
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader


SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" }
LOD 300
Pass
{
Name "GBuffer" // Name is not used

3
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader


SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" }
LOD 300
Pass
{
Name "GBuffer" // Name is not used

5
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs


if (m_isInit)
return;
var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
cmd.Dispose();
CommandBufferPool.Release(cmd);
m_isInit = true;
}

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


#define SSS_WRAP_ANGLE (PI/12) // Used for wrap lighting
#define SSS_WRAP_LIGHT cos(PI/2 - SSS_WRAP_ANGLE)
CBUFFER_START(UnitySSSParameters)
uint _EnableSSSAndTransmission; // Globally toggles subsurface and transmission scattering on/off
uint _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter
uint _TransmissionFlags; // 2 bit/profile; 0 = inf. thick, 1 = thin, 2 = regular

CBUFFER_END
//-----------------------------------------------------------------------------
// Helper functions/variable specific to this material

3
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader


SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" }
LOD 300
Pass
{
Name "GBuffer" // Name is not used

149
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitProperties.hlsl


// ===========================================================================
// WARNING:
// On PS4, texture/sampler declarations need to be outside of CBuffers
// Otherwise those parameters are not bound correctly at runtime.
// ===========================================================================
#ifndef LAYERED_LIT_SHADER
TEXTURE2D(_DiffuseLightingMap);
SAMPLER2D(sampler_DiffuseLightingMap);
TEXTURE2D(_DistortionVectorMap);
SAMPLER2D(sampler_DistortionVectorMap);
TEXTURE2D(_EmissiveColorMap);
SAMPLER2D(sampler_EmissiveColorMap);
TEXTURE2D(_BaseColorMap);
SAMPLER2D(sampler_BaseColorMap);
TEXTURE2D(_MaskMap);
SAMPLER2D(sampler_MaskMap);
TEXTURE2D(_SpecularOcclusionMap);
SAMPLER2D(sampler_SpecularOcclusionMap);
TEXTURE2D(_NormalMap);
SAMPLER2D(sampler_NormalMap);
TEXTURE2D(_NormalMapOS);
SAMPLER2D(sampler_NormalMapOS);
TEXTURE2D(_DetailMask);
SAMPLER2D(sampler_DetailMask);
TEXTURE2D(_DetailMap);
SAMPLER2D(sampler_DetailMap);
TEXTURE2D(_HeightMap);
SAMPLER2D(sampler_HeightMap);
TEXTURE2D(_TangentMap);
SAMPLER2D(sampler_TangentMap);
TEXTURE2D(_TangentMapOS);
SAMPLER2D(sampler_TangentMapOS);
TEXTURE2D(_AnisotropyMap);
SAMPLER2D(sampler_AnisotropyMap);
TEXTURE2D(_SubsurfaceRadiusMap);
SAMPLER2D(sampler_SubsurfaceRadiusMap);
TEXTURE2D(_ThicknessMap);
SAMPLER2D(sampler_ThicknessMap);
TEXTURE2D(_SpecularColorMap);
SAMPLER2D(sampler_SpecularColorMap);
#else
// Set of users variables
#define PROP_DECL(type, name) type name##0, name##1, name##2, name##3
// sampler are share by texture type inside a layered material but we need to support that a particualr layer have no texture, so we take the first sampler of available texture as the share one
// mean we must declare all sampler
#define PROP_DECL_TEX2D(name)\
TEXTURE2D(MERGE_NAME(name, 0)); \
SAMPLER2D(MERGE_NAME(MERGE_NAME(sampler, name), 0)); \
TEXTURE2D(MERGE_NAME(name, 1)); \
SAMPLER2D(MERGE_NAME(MERGE_NAME(sampler, name), 1)); \
TEXTURE2D(MERGE_NAME(name, 2)); \
SAMPLER2D(MERGE_NAME(MERGE_NAME(sampler, name), 2)); \
TEXTURE2D(MERGE_NAME(name, 3)); \
SAMPLER2D(MERGE_NAME(MERGE_NAME(sampler, name), 3))
PROP_DECL_TEX2D(_BaseColorMap);
PROP_DECL_TEX2D(_MaskMap);
PROP_DECL_TEX2D(_SpecularOcclusionMap);
PROP_DECL_TEX2D(_NormalMap);
PROP_DECL_TEX2D(_NormalMapOS);
PROP_DECL_TEX2D(_HeightMap);
PROP_DECL_TEX2D(_DetailMask);
PROP_DECL_TEX2D(_DetailMap);
TEXTURE2D(_LayerMaskMap);
SAMPLER2D(sampler_LayerMaskMap);
#endif
CBUFFER_START(_PerMaterial)
// shared constant between lit and layered lit

float _PPDMinSamples;
float _PPDLodThreshold;
TEXTURE2D(_DiffuseLightingMap);
SAMPLER2D(sampler_DiffuseLightingMap);
TEXTURE2D(_DistortionVectorMap);
SAMPLER2D(sampler_DistortionVectorMap);
TEXTURE2D(_EmissiveColorMap);
SAMPLER2D(sampler_EmissiveColorMap);
float _EmissiveIntensity;
// Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor"

// Set of users variables
float4 _BaseColor;
TEXTURE2D(_BaseColorMap);
SAMPLER2D(sampler_BaseColorMap);
TEXTURE2D(_MaskMap);
SAMPLER2D(sampler_MaskMap);
TEXTURE2D(_SpecularOcclusionMap);
SAMPLER2D(sampler_SpecularOcclusionMap);
TEXTURE2D(_NormalMap);
SAMPLER2D(sampler_NormalMap);
TEXTURE2D(_NormalMapOS);
SAMPLER2D(sampler_NormalMapOS);
TEXTURE2D(_DetailMask);
SAMPLER2D(sampler_DetailMask);
TEXTURE2D(_DetailMap);
SAMPLER2D(sampler_DetailMap);
TEXTURE2D(_HeightMap);
SAMPLER2D(sampler_HeightMap);
TEXTURE2D(_TangentMap);
SAMPLER2D(sampler_TangentMap);
TEXTURE2D(_TangentMapOS);
SAMPLER2D(sampler_TangentMapOS);
TEXTURE2D(_AnisotropyMap);
SAMPLER2D(sampler_AnisotropyMap);
TEXTURE2D(_SubsurfaceRadiusMap);
SAMPLER2D(sampler_SubsurfaceRadiusMap);
TEXTURE2D(_ThicknessMap);
SAMPLER2D(sampler_ThicknessMap);
TEXTURE2D(_SpecularColorMap);
SAMPLER2D(sampler_SpecularColorMap);
float _TexWorldScale;
float4 _UVMappingMask;

// Set of users variables
#define PROP_DECL(type, name) type name##0, name##1, name##2, name##3
// sampler are share by texture type inside a layered material but we need to support that a particualr layer have no texture, so we take the first sampler of available texture as the share one
// mean we must declare all sampler
#define PROP_DECL_TEX2D(name)\
TEXTURE2D(MERGE_NAME(name, 0)); \
SAMPLER2D(MERGE_NAME(MERGE_NAME(sampler, name), 0)); \
TEXTURE2D(MERGE_NAME(name, 1)); \
SAMPLER2D(MERGE_NAME(MERGE_NAME(sampler, name), 1)); \
TEXTURE2D(MERGE_NAME(name, 2)); \
SAMPLER2D(MERGE_NAME(MERGE_NAME(sampler, name), 2)); \
TEXTURE2D(MERGE_NAME(name, 3)); \
SAMPLER2D(MERGE_NAME(MERGE_NAME(sampler, name), 3))
// Set of users variables
PROP_DECL_TEX2D(_BaseColorMap);
float4 _BaseColorMap0_ST;
float4 _BaseColorMap1_ST;
float4 _BaseColorMap2_ST;

PROP_DECL(float, _Smoothness);
PROP_DECL_TEX2D(_MaskMap);
PROP_DECL_TEX2D(_SpecularOcclusionMap);
PROP_DECL_TEX2D(_NormalMap);
PROP_DECL_TEX2D(_NormalMapOS);
PROP_DECL_TEX2D(_HeightMap);
PROP_DECL_TEX2D(_DetailMask);
PROP_DECL_TEX2D(_DetailMap);
float4 _DetailMap0_ST;
float4 _DetailMap1_ST;
float4 _DetailMap2_ST;

PROP_DECL(float, _HeightAmplitude);
PROP_DECL(float, _HeightCenter);
TEXTURE2D(_LayerMaskMap);
SAMPLER2D(sampler_LayerMaskMap);
float _BlendUsingHeight1;
float _BlendUsingHeight2;

3
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader


SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" }
LOD 300
Pass
{
Name "GBuffer" // Name is not used

151
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CombineSubsurfaceScattering.shader


#pragma multi_compile _ SSS_FILTER_HORIZONTAL_AND_COMBINE
// <<< Old SSS Model
// Tweak parameters for the Disney SSS below.
#define SSS_BILATERAL_FILTER 1
#define SSS_USE_TANGENT_PLANE 0
#define SSS_CLAMP_ARTIFACT 0
#define SSS_DEBUG_LOD 0
#define SSS_DEBUG_NORMAL_VS 0
// Do not modify these.
#define SSS_BILATERAL 1
#define SSS_DEBUG 0
#ifdef SSS_MODEL_BASIC
#define RBG_BILATERAL_WEIGHTS 0
#endif
//-------------------------------------------------------------------------------------
// Include

// Inputs & outputs
//-------------------------------------------------------------------------------------
float4x4 _ViewMatrix, _ProjMatrix; // TEMP: make these global
float _FilterKernelsNearField[SSS_N_PROFILES][SSS_N_SAMPLES_NEAR_FIELD][2]; // 0 = radius, 1 = reciprocal of the PDF
float _FilterKernelsFarField[SSS_N_PROFILES][SSS_N_SAMPLES_FAR_FIELD][2]; // 0 = radius, 1 = reciprocal of the PDF
#else

return /* 0.25 * */ S * (expOneThird + expOneThird * expOneThird * expOneThird);
}
// Computes F(x)/P(x), s.t. x = sqrt(r^2 + t^2).
float3 ComputeBilateralWeight(float3 S, float r, float t, float rcpPdf)
// Computes F(r)/P(r), s.t. r = sqrt(a^2 + b^2).
// Rescaling of the PDF is handled by 'totalWeight'.
float3 ComputeBilateralWeight(float a2, float b, float mmPerUnit, float3 S, float rcpPdf)
#if (SSS_BILATERAL == 0)
t = 0;
#if (SSS_BILATERAL_FILTER == 0)
b = 0;
#endif
#if SSS_USE_TANGENT_PLANE
// Both 'a2' and 'b2' require unit conversion.
float r = sqrt(a2 + b * b) * mmPerUnit;
#else
// Only 'b2' requires unit conversion.
float r = sqrt(a2 + (b * mmPerUnit) * (b * mmPerUnit));
float3 val = KernelValCircle(sqrt(r * r + t * t), S);
// Rescaling of the PDF is handled by 'totalWeight'.
return val * rcpPdf;
#if SSS_CLAMP_ARTIFACT
return saturate(KernelValCircle(r, S) * rcpPdf);
#else
return KernelValCircle(r, S) * rcpPdf;
#endif
#define SSS_ITER(i, n, kernel, profileID, shapeParam, centerPosUnSS, centerDepthVS, \
millimPerUnit, pixelsPerMm, totalIrradiance, totalWeight) \
#define SSS_ITER(i, n, kernel, profileID, shapeParam, centerPosUnSS, centerPosVS, \
useTangentPlane, tangentX, tangentY, mmPerUnit, pixelsPerMm, \
totalIrradiance, totalWeight) \
float phi = TWO_PI * Fibonacci2d(i, n).y; \
float phi = SampleDiskFibonacci(i, n).y; \
float2 position = centerPosUnSS + vec * pixelsPerMm; \
float3 irradiance = LOAD_TEXTURE2D(_IrradianceSource, position).rgb; \
/* Compute the screen-space position and the associated irradiance. */ \
float2 position; float3 irradiance; \
/* Compute the squared distance (in mm) in the screen-aligned plane. */ \
float dXY2; \
\
if (useTangentPlane) \
{ \
/* 'vec' is given relative to the tangent frame. */ \
float3 relPosVS = vec.x * tangentX + vec.y * tangentY; \
float3 positionVS = centerPosVS + relPosVS; \
float4 positionCS = mul(_ProjMatrix, float4(positionVS, 1)); \
float2 positionSS = positionCS.xy * (rcp(positionCS.w) * 0.5) + 0.5; \
\
position = positionSS * _ScreenSize.xy; \
irradiance = LOAD_TEXTURE2D(_IrradianceSource, position).rgb; \
dXY2 = dot(relPosVS.xy, relPosVS.xy); \
} \
else \
{ \
/* 'vec' is given directly in screen-space. */ \
position = centerPosUnSS + vec * pixelsPerMm; \
irradiance = LOAD_TEXTURE2D(_IrradianceSource, position).rgb; \
dXY2 = r * r; \
} \
\
/* TODO: see if making this a [branch] improves performance. */ \
[flatten] \

float z = LOAD_TEXTURE2D(_MainDepthTexture, position).r; \
float d = LinearEyeDepth(z, _ZBufferParams); \
float t = millimPerUnit * d - (millimPerUnit * centerDepthVS); \
float t = d - centerPosVS.z; \
float3 w = ComputeBilateralWeight(shapeParam, r, t, p); \
float3 w = ComputeBilateralWeight(dXY2, t, mmPerUnit, shapeParam, p); \
\
totalIrradiance += w * irradiance; \
totalWeight += w; \

} \
}
#define SSS_LOOP(n, kernel, profileID, shapeParam, centerPosUnSS, centerDepthVS, \
millimPerUnit, pixelsPerMm, totalIrradiance, totalWeight) \
#define SSS_LOOP(n, kernel, profileID, shapeParam, centerPosUnSS, centerPosVS, \
useTangentPlane, tangentX, tangentY, mmPerUnit, pixelsPerMm, \
totalIrradiance, totalWeight) \
float centerRadius = kernel[profileID][0][0]; \
float3 centerWeight = KernelValCircle(0, shapeParam) * centerRcpPdf; \
float3 centerWeight = KernelValCircle(centerRadius, shapeParam) * centerRcpPdf; \
/* Perform integration over the screen-aligned plane in the view space. */ \
/* TODO: it would be more accurate to use the tangent plane instead. */ \
/* Integrate over the screen-aligned or tangent plane in the view space. */ \
SSS_ITER(i, n, kernel, profileID, shapeParam, centerPosUnSS, centerDepthVS, \
millimPerUnit, pixelsPerMm, totalIrradiance, totalWeight) \
SSS_ITER(i, n, kernel, profileID, shapeParam, centerPosUnSS, centerPosVS, \
useTangentPlane, tangentX, tangentY, mmPerUnit, pixelsPerMm, \
totalIrradiance, totalWeight) \
} \
}

float maxDistance = _FilterKernelsBasic[profileID][SSS_BASIC_N_SAMPLES - 1].a;
#endif
// Take the first (central) sample.
// TODO: copy its neighborhood into LDS.
float2 centerPosition = posInput.unPositionSS;
float3 centerIrradiance = LOAD_TEXTURE2D(_IrradianceSource, centerPosition).rgb;
float centerDepth = LOAD_TEXTURE2D(_MainDepthTexture, posInput.unPositionSS).r;
float centerDepth = LOAD_TEXTURE2D(_MainDepthTexture, centerPosition).r;
// Compute the view-space dimensions of the pixel as a quad projected onto geometry.
float2 unitsPerPixel = 2 * abs(cornerPosVS.xy - centerPosVS.xy);
float metersPerUnit = _WorldScales[profileID] / distScale;
float millimPerUnit = MILLIMETERS_PER_METER * metersPerUnit;
float2 pixelsPerMm = rcp(millimPerUnit * unitsPerPixel);
float mmPerUnit = MILLIMETERS_PER_METER * (_WorldScales[profileID] / distScale);
float unitsPerMm = rcp(mmPerUnit);
// Take the first (central) sample.
// TODO: copy its neighborhood into LDS.
float2 centerPosition = posInput.unPositionSS;
float3 centerIrradiance = LOAD_TEXTURE2D(_IrradianceSource, centerPosition).rgb;
// Compute the view-space dimensions of the pixel as a quad projected onto geometry.
float2 unitsPerPixel = 2 * abs(cornerPosVS.xy - centerPosVS.xy);
float2 pixelsPerMm = rcp(unitsPerPixel) * unitsPerMm;
// N.b.: our LoD selection algorithm is the same regardless of
// whether we integrate over the tangent plane or not, since we
// don't want the orientation of the tangent plane to create
// divergence of execution across the warp.
#if SSS_DEBUG
#if SSS_DEBUG_LOD
const bool useTangentPlane = SSS_USE_TANGENT_PLANE != 0;
// Compute the tangent frame in view space.
float3 normalVS = mul((float3x3)_ViewMatrix, bsdfData.normalWS);
float3 tangentX = GetLocalFrame(normalVS)[0] * unitsPerMm;
float3 tangentY = GetLocalFrame(normalVS)[1] * unitsPerMm;
#if SSS_DEBUG_NORMAL_VS
// We expect the view-space normal to be front-facing.
if (normalVS.z >= 0) return float4(1, 0, 0, 1);
#endif
// Accumulate filtered irradiance and bilateral weights (for renormalization).
float3 totalIrradiance, totalWeight;

if (maxDistInPixels < SSS_LOD_THRESHOLD)
{
#if SSS_DEBUG
#if SSS_DEBUG_LOD
profileID, shapeParam, centerPosition, centerPosVS.z,
millimPerUnit, pixelsPerMm, totalIrradiance, totalWeight)
profileID, shapeParam, centerPosition, centerPosVS,
useTangentPlane, tangentX, tangentY, mmPerUnit, pixelsPerMm,
totalIrradiance, totalWeight)
#if SSS_DEBUG
#if SSS_DEBUG_LOD
profileID, shapeParam, centerPosition, centerPosVS.z,
millimPerUnit, pixelsPerMm, totalIrradiance, totalWeight)
profileID, shapeParam, centerPosition, centerPosVS,
useTangentPlane, tangentX, tangentY, mmPerUnit, pixelsPerMm,
totalIrradiance, totalWeight)
#endif
}
#else

// Compute the view-space dimensions of the pixel as a quad projected onto geometry.
float2 unitsPerPixel = 2 * abs(cornerPosVS.xy - centerPosVS.xy);
float2 pixelsPerCm = rcp(centimPerUnit * unitsPerPixel);
// Compute the filtering direction.

[flatten]
if (any(sampleIrradiance))
{
#if SSS_BILATERAL
// Apply bilateral weighting.
// Ref #1: Skin Rendering by Pseudo–Separable Cross Bilateral Filtering.
// Ref #2: Separable SSS, Supplementary Materials, Section E.

sampleWeight *= exp(-zDistance * zDistance * halfRcpVariance);
#endif
totalIrradiance += sampleWeight * sampleIrradiance;
totalWeight += sampleWeight;

14
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringProfile.cs


// Clamp to avoid artifacts.
m_ShapeParam = new Vector3();
m_ShapeParam.x = Mathf.Min(1000f, 1.0f / scatteringDistance.r);
m_ShapeParam.y = Mathf.Min(1000f, 1.0f / scatteringDistance.g);
m_ShapeParam.z = Mathf.Min(1000f, 1.0f / scatteringDistance.b);
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);
// We importance sample the color channel with the widest scattering distance.
float s = Mathf.Min(m_ShapeParam.x, m_ShapeParam.y, m_ShapeParam.z);

// ------------------------------------------------------------------------------------
// Importance sample the near field kernel.
for (int i = 0; i < SssConstants.SSS_N_SAMPLES_NEAR_FIELD; i++)
for (int i = 0, n = SssConstants.SSS_N_SAMPLES_NEAR_FIELD; i < n; i++)
float p = i * (1.0f / SssConstants.SSS_N_SAMPLES_NEAR_FIELD);
float p = (i + 0.5f) * (1.0f / n);
float r = KernelCdfInverse(p, s);
// N.b.: computation of normalized weights, and multiplication by the surface albedo

m_MaxRadius = m_FilterKernelNearField[SssConstants.SSS_N_SAMPLES_NEAR_FIELD - 1].x;
// Importance sample the far field kernel.
for (int i = 0; i < SssConstants.SSS_N_SAMPLES_FAR_FIELD; i++)
for (int i = 0, n = SssConstants.SSS_N_SAMPLES_FAR_FIELD; i < n; i++)
float p = i * (1.0f / SssConstants.SSS_N_SAMPLES_FAR_FIELD);
float p = (i + 0.5f) * (1.0f / n);
float r = KernelCdfInverse(p, s);
// N.b.: computation of normalized weights, and multiplication by the surface albedo

2
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/MaterialUtilities.hlsl


positionCS.xy = positionCS.xy / positionCS.w;
previousPositionCS.xy = previousPositionCS.xy / previousPositionCS.w;
return (positionCS.xy - previousPositionCS.xy) * _ForceNoMotion;
return (positionCS.xy - previousPositionCS.xy) * unity_MotionVectorsParams.y;
#else
return float2(0.0, 0.0);
#endif

3
Assets/ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.shader


SubShader
{
Tags { "RenderType"="Opaque" "PerformanceChecks"="False" }
LOD 300
// Extracts information for lightmapping, GI (emission, albedo, ...)
// This pass it not used during regular rendering.
Pass

1
Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/HDRenderPipelineResources.asset


buildMaterialFlagsShader: {fileID: 7200000, guid: fb3eda953cd6e634e877fb777be2cd08,
type: 3}
shadeOpaqueShader: {fileID: 7200000, guid: 0b64f79746d2daf4198eaf6eab9af259, type: 3}
cameraMotionVectors: {fileID: 4800000, guid: 035941b63024d1943af48811c1db20d9, type: 3}
blitCubemap: {fileID: 4800000, guid: d05913e251bed7a4992c921c62e1b647, type: 3}
buildProbabilityTables: {fileID: 7200000, guid: b9f26cf340afe9145a699753531b2a4c,
type: 3}

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


fileFormatVersion: 2
guid: 42086e81f4f0c724f96f7f09cc995354
timeCreated: 1497363538
timeCreated: 1497525010
licenseType: Pro
NativeFormatImporter:
mainObjectFileID: 11400000

6
Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/RenderPipelineResources.cs


// TODO skybox/cubemap
[UnityEditor.MenuItem("RenderPipeline/HDRenderPipeline/Create Resources Asset")]
[UnityEditor.MenuItem("RenderPipeline/HDRenderPipeline/Create Resources Asset", false, 15)]
static void CreateRenderPipelineResources()
{
var instance = CreateInstance<RenderPipelineResources>();

// 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>("Assets/ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/DrawSssProfile.shader");
// instance.drawTransmittanceGraphShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/DrawTransmittanceGraph.shader");
instance.cameraMotionVectors = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/CameraMotionVectors.shader");
// Sky
instance.blitCubemap = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>("Assets/ScriptableRenderPipeline/HDRenderPipeline/Sky/BlitCubemap.shader");

// These shaders don't need to be reference by RenderPipelineResource as they are not use at runtime (only to draw in editor)
// public Shader drawSssProfile;
// public Shader drawTransmittanceGraphShader;
public Shader cameraMotionVectors;
// Sky
public Shader blitCubemap;

8
Assets/ScriptableRenderPipeline/HDRenderPipeline/ShaderConfig.cs


[GenerateHLSL(PackingRules.Exact)]
public enum ShaderOptions
{
// TODO: Currently it is not yet possible to use this feature, we need to provide previousPositionCS to the vertex shader as part of Attribute for GBuffer pass
// TODO: How to enable this feature only on mesh that effectively require it like skinned and moving mesh (other can be done with depth reprojection. But TAA can be an issue)
// TODO: It is not possible to use VelocityInGBuffer feature yet. This feature allow to render motion vectors during Gbuffer pass. However Unity have limitation today that forbid to do that.
// 1) Currently previousPositionCS is provide to the vertex shader with a hard coded NORMAL semantic (in the vertex declaration - See MeshRenderingData.cpp "pSecondaryFormat = gMotionVectorRenderFormat.GetVertexFormat();") mean it will overwrite the normal
// 2) All current available semantic (see ShaderChannelMask) are used in our Lit shader. Mean just changing the semantic is not enough, Unity need to unlock other Texcoord semantic
// 3) When this is solve (i.e move previousPositionCS to a free attribute semantic), Unity only support one pSecondaryFormat. Mean if we ahve a vertex color instance stream and motion vector, motion vector will overwrite vertex color stream. See MeshRenderingData.cpp
// All this could be fix we a new Mesh API not ready yet. Note that this feature only affect animated mesh (vertex or skin) as others use depth reprojection.
// TODO: not working yet, waiting for UINT16 RT format support
PackGBufferInU16 = 0
};

4
Assets/ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassVelocity.hlsl


// It is not possible to correctly generate the motion vector for tesselated geometry as tessellation parameters can change
// from one frame to another (adaptative, lod) + in Unity we only receive information for one non tesselated vertex.
// So motion vetor will be based on interpolate previous position at vertex level instead.
varyingsType.vpass.positionCS = mul(_NonJitteredVP, mul(unity_ObjectToWorld, float4(inputMesh.positionOS, 1.0)));
varyingsType.vpass.previousPositionCS = mul(_PreviousVP, mul(_PreviousM, _HasLastPositionData ? float4(inputPass.previousPositionOS, 1.0) : float4(inputMesh.positionOS, 1.0)));
varyingsType.vpass.positionCS = mul(_ViewProjMatrix, mul(unity_ObjectToWorld, float4(inputMesh.positionOS, 1.0)));
varyingsType.vpass.previousPositionCS = mul(_PrevViewProjMatrix, mul(unity_MatrixPreviousM, unity_MotionVectorsParams.x ? float4(inputPass.previousPositionOS, 1.0) : float4(inputMesh.positionOS, 1.0)));
return PackVaryingsType(varyingsType);
}

14
Assets/ScriptableRenderPipeline/HDRenderPipeline/ShaderVariables.hlsl


SAMPLER3D(samplerunity_ProbeVolumeSH);
CBUFFER_START(UnityVelocityPass)
float4x4 _NonJitteredVP;
float4x4 _PreviousVP;
float4x4 _PreviousM;
bool _HasLastPositionData;
bool _ForceNoMotion;
float _MotionVectorDepthBias;
float4x4 unity_MatrixNonJitteredVP;
float4x4 unity_MatrixPreviousVP;
float4x4 unity_MatrixPreviousM;
float4 unity_MotionVectorsParams;
// TODO: move this to constant buffer by Pass
CBUFFER_START(UnityPerPass)
float4x4 _PrevViewProjMatrix;
CBUFFER_END
float4x4 GetWorldToViewMatrix()
{

4
Assets/ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/HDRISkyRenderer.cs


m_SkyHDRIMaterial.SetTexture("_Cubemap", m_HdriSkyParams.skyHDRI);
m_SkyHDRIMaterial.SetVector("_SkyParam", new Vector4(m_HdriSkyParams.exposure, m_HdriSkyParams.multiplier, m_HdriSkyParams.rotation, 0.0f));
var cmd = new CommandBuffer { name = "" };
var cmd = CommandBufferPool.Get("");
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
public override bool IsSkyValid()

6
Assets/ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/ProceduralSkyRenderer.cs


// Set shader constants.
SetUniforms(builtinParams, m_ProceduralSkySettings, renderForCubemap, ref properties);
var cmd = new CommandBuffer { name = "" };
var cmd = CommandBufferPool.Get("");
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
}
}

12
Assets/ScriptableRenderPipeline/HDRenderPipeline/Sky/RuntimeFilterIBL.cs


m_ComputeGgxIblSampleDataCS.SetTexture(m_ComputeGgxIblSampleDataKernel, "output", m_GgxIblSampleData);
var cmd = new CommandBuffer() { name = "Compute GGX IBL Sample Data" };
var cmd = CommandBufferPool.Get("Compute GGX IBL Sample Data");
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
}

{
Utilities.SetRenderTarget(context, target, ClearFlag.ClearNone, mip, (CubemapFace)face);
var cmd = new CommandBuffer { name = "" };
var cmd = CommandBufferPool.Get();
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
}
}

int numRows = conditionalCdf.height;
var cmd = new CommandBuffer() { name = "Build Probability Tables" };
var cmd = CommandBufferPool.Get("Build Probability Tables");
cmd.Dispose();
CommandBufferPool.Release(cmd);
m_GgxConvolveMaterial.EnableKeyword("USE_MIS");
m_GgxConvolveMaterial.SetTexture("_ConditionalDensities", conditionalCdf);

9
Assets/ScriptableRenderPipeline/HDRenderPipeline/Sky/SkyManager.cs


for (int i = 0; i < 6; ++i)
{
Utilities.SetRenderTarget(renderContext, dest, ClearFlag.ClearNone, 0, (CubemapFace)i);
var cmd = new CommandBuffer { name = "" };
var cmd = CommandBufferPool.Get();
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
}

}
// Copy the first mip
var cmd = new CommandBuffer { name = "" };
var cmd = CommandBufferPool.Get();
cmd.Dispose();
if (m_useMIS && m_iblFilterGgx.SupportMIS)
{

{
m_iblFilterGgx.FilterCubemap(renderContext, input, target, mipCount, m_CubemapFaceMesh);
}
CommandBufferPool.Release(cmd);
}
}

4
Assets/ScriptableRenderPipeline/HDRenderPipeline/Sky/SkySettingsSingleton.cs


#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class SkySettingsSingleton : Singleton<SkySettingsSingleton>

100
Assets/ScriptableRenderPipeline/HDRenderPipeline/Utilities.cs


public static void SetRenderTarget(ScriptableRenderContext renderContext, RenderTargetIdentifier buffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)
{
var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
public static void SetRenderTarget(ScriptableRenderContext renderContext, RenderTargetIdentifier buffer, ClearFlag clearFlag = ClearFlag.ClearNone, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)

public static void SetRenderTarget(ScriptableRenderContext renderContext, RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthBuffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)
{
var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
public static void SetRenderTarget(ScriptableRenderContext renderContext, RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthBuffer)

public static void SetRenderTarget(ScriptableRenderContext renderContext, RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthBuffer, ClearFlag clearFlag, Color clearColor)
{
var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
cmd.Dispose();
var cmd = new CommandBuffer();
var cmd = CommandBufferPool.Get();
cmd.name = "";
for(int i = 0 ; i < 6 ; ++i)

renderContext.ExecuteCommandBuffer(cmd);
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
// Miscellanous

return sb.ToString();
}
public class ProfilingSample
public struct ProfilingSample
bool disposed = false;
bool disposed;
ScriptableRenderContext renderContext;
string name;

disposed = false;
CommandBuffer cmd = new CommandBuffer();
CommandBuffer cmd = CommandBufferPool.Get();
cmd.Dispose();
}
~ProfilingSample()
{
Dispose(false);
CommandBufferPool.Release(cmd);
public void Dispose()
{
Dispose(true);

protected virtual void Dispose(bool disposing)
void Dispose(bool disposing)
{
if (disposed)
return;

CommandBuffer cmd = new CommandBuffer();
CommandBuffer cmd = CommandBufferPool.Get();
cmd.Dispose();
CommandBufferPool.Release(cmd);
}
disposed = true;

return gpuVP;
}
public static HDCamera GetHDCamera(Camera camera)
{
HDCamera hdCamera = new HDCamera();
hdCamera.camera = camera;
hdCamera.screenSize = new Vector4(camera.pixelWidth, camera.pixelHeight, 1.0f / camera.pixelWidth, 1.0f / camera.pixelHeight);
// The actual projection matrix used in shaders is actually massaged a bit to work across all platforms
// (different Z value ranges etc.)
var gpuProj = GL.GetGPUProjectionMatrix(camera.projectionMatrix, false);
var gpuVP = gpuProj * camera.worldToCameraMatrix;
// Ref: An Efficient Depth Linearization Method for Oblique View Frustums, Eq. 6.
Vector4 invProjectionParam = new Vector4(gpuProj.m20 / (gpuProj.m00 * gpuProj.m23),
gpuProj.m21 / (gpuProj.m11 * gpuProj.m23),
-1.0f / gpuProj.m23,
(-gpuProj.m22
+ gpuProj.m20 * gpuProj.m02 / gpuProj.m00
+ gpuProj.m21 * gpuProj.m12 / gpuProj.m11) / gpuProj.m23);
hdCamera.viewProjectionMatrix = gpuVP;
hdCamera.invViewProjectionMatrix = gpuVP.inverse;
hdCamera.invProjectionMatrix = gpuProj.inverse;
hdCamera.invProjectionParam = invProjectionParam;
return hdCamera;
}
public static void SetupMaterialHDCamera(HDCamera hdCamera, Material material)
{
material.SetVector("_ScreenSize", hdCamera.screenSize);
material.SetMatrix("_ViewProjMatrix", hdCamera.viewProjectionMatrix);
material.SetMatrix("_InvViewProjMatrix", hdCamera.invViewProjectionMatrix);
material.SetMatrix("_InvProjMatrix", hdCamera.invProjectionMatrix);
material.SetVector("_InvProjParam", hdCamera.invProjectionParam);
}
static List<float> m_FloatListdata = new List<float>();
var data = new float[16];
m_FloatListdata.Clear();
data[4 * c + r] = mat[r, c];
m_FloatListdata.Add(mat[r, c]);
cmd.SetComputeFloatParams(shadercs, name, data);
cmd.SetComputeFloatParams(shadercs, name, m_FloatListdata);
var data = new float[numMatrices * 16];
m_FloatListdata.Clear();
data[16 * n + 4 * c + r] = matArray[n][r, c];
m_FloatListdata.Add(matArray[n][r, c]);
cmd.SetComputeFloatParams(shadercs, name, data);
cmd.SetComputeFloatParams(shadercs, name, m_FloatListdata);
var data = new float[numVectors * 4];
m_FloatListdata.Clear();
data[4 * n + i] = vecArray[n][i];
m_FloatListdata.Add(vecArray[n][i]);
cmd.SetComputeFloatParams(shadercs, name, data);
cmd.SetComputeFloatParams(shadercs, name, m_FloatListdata);
}
public static void SetKeyword(Material m, string keyword, bool state)

RenderTargetIdentifier colorBuffer,
MaterialPropertyBlock properties = null, int shaderPassID = 0)
{
SetupMaterialHDCamera(camera, material);
camera.SetupMaterial(material);
commandBuffer.SetRenderTarget(colorBuffer);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassID, MeshTopology.Triangles, 3, 1, properties);
}

RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthStencilBuffer,
MaterialPropertyBlock properties = null, int shaderPassID = 0)
{
SetupMaterialHDCamera(camera, material);
camera.SetupMaterial(material);
commandBuffer.SetRenderTarget(colorBuffer, depthStencilBuffer);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassID, MeshTopology.Triangles, 3, 1, properties);
}

RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthStencilBuffer,
MaterialPropertyBlock properties = null, int shaderPassID = 0)
{
SetupMaterialHDCamera(camera, material);
camera.SetupMaterial(material);
commandBuffer.SetRenderTarget(colorBuffers, depthStencilBuffer);
commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassID, MeshTopology.Triangles, 3, 1, properties);
}

2
Assets/ScriptableRenderPipeline/LightweightPipeline.meta


fileFormatVersion: 2
guid: 7a2706b41ea31e54d9e4ca93be22278a
guid: 4923a4700d4d643a9a862a74e04870b3
folderAsset: yes
timeCreated: 1481548458
licenseType: Pro

5
Assets/ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightAssetInspector.cs


public static GUIContent shadowDistante = new GUIContent("Shadow Distance", "Max shadow drawing distance");
public static GUIContent shadowMinBias = new GUIContent("Shadow Min Normal Bias Offset", "Minimum value of normal bias offset applied");
public static GUIContent shadowBias = new GUIContent("Shadow Normal Bias", "Normal bias offset value.");
public static GUIContent shadowAtlasResolution = new GUIContent("Shadow Map Resolution",
"Resolution of shadow map texture. If cascades are enabled all cascades will be packed into this texture resolution.");

EditorGUILayout.PropertyField(m_ShadowTypeProp, Styles.shadowType);
EditorGUILayout.PropertyField(m_ShadowAtlasResolutionProp, Styles.shadowAtlasResolution);
EditorGUILayout.PropertyField(m_ShadowNearPlaneOffsetProp, Styles.shadowNearPlaneOffset);
EditorGUILayout.PropertyField(m_ShadowMinNormalBiasProperty, Styles.shadowMinBias);
EditorGUILayout.PropertyField(m_ShadowNormalBiasProperty, Styles.shadowBias);
EditorGUILayout.PropertyField(m_ShadowDistanceProp, Styles.shadowDistante);
EditorGUILayout.PropertyField(m_ShadowCascadesProp, Styles.shadowCascades);

189
Assets/ScriptableRenderPipeline/LightweightPipeline/LightweightPipeline.cs


{
public int pixelLightsCount;
public int vertexLightsCount;
public int shadowLightIndex;
public bool shadowsRendered;
}
public class LightweightPipeline : RenderPipeline

private static readonly int kMaxCascades = 4;
private int m_ShadowCasterCascadesCount = kMaxCascades;
private int m_ShadowMapProperty;
private int m_ShadowLightIndex = -1;
private int m_DepthBufferBits = 24;
private int m_DepthBufferBits = 16;
private Vector4[] m_DirectionalShadowSplitDistances = new Vector4[kMaxCascades];
private ShadowSettings m_ShadowSettings = ShadowSettings.Default;

}
}
CullResults m_CullResults;
public override void Render(ScriptableRenderContext context, Camera[] cameras)
{
base.Render(context, cameras);

if (!CullResults.GetCullingParameters(camera, out cullingParameters))
continue;
cullingParameters.shadowDistance = m_ShadowSettings.maxShadowDistance;
CullResults cullResults = CullResults.Cull(ref cullingParameters, context);
cullingParameters.shadowDistance = Mathf.Min(m_ShadowSettings.maxShadowDistance, camera.farClipPlane);
CullResults.Cull(ref cullingParameters, context,ref m_CullResults);
VisibleLight[] visibleLights = cullResults.visibleLights;
VisibleLight[] visibleLights = m_CullResults.visibleLights.ToArray();
bool shadowsRendered = false;
InitializeMainShadowLightIndex(visibleLights);
if (m_ShadowLightIndex > -1)
shadowsRendered = RenderShadows(ref cullResults, ref visibleLights[m_ShadowLightIndex], ref context);
if (lightData.shadowLightIndex > -1)
lightData.shadowsRendered = RenderShadows(ref m_CullResults, ref visibleLights[lightData.shadowLightIndex], lightData.shadowLightIndex, ref context);
// Setup camera matrices and RT
context.SetupCameraProperties(camera);

var cmd = new CommandBuffer() { name = "Clear" };
var cmd = CommandBufferPool.Get("Clear");
cmd.Dispose();
CommandBufferPool.Release(cmd);
SetupLightShaderVariables(visibleLights, ref cullResults, ref context, ref lightData);
if (shadowsRendered)
SetupShadowShaderVariables(ref context, m_ShadowCasterCascadesCount);
SetupShaderLightConstants(visibleLights, ref lightData, ref m_CullResults, ref context);
if (lightData.shadowsRendered)
SetupShadowShaderConstants(ref context, ref visibleLights[lightData.shadowLightIndex], lightData.shadowLightIndex, m_ShadowCasterCascadesCount);
SetShaderKeywords(ref lightData, ref context);
RendererConfiguration configuration = RendererConfiguration.PerObjectReflectionProbes;
if (m_Asset.EnableLightmap)

configuration |= RendererConfiguration.ProvideLightIndices;
// Render Opaques
var litSettings = new DrawRendererSettings(cullResults, camera, m_LitPassName);
var litSettings = new DrawRendererSettings(m_CullResults, camera, m_LitPassName);
var unlitSettings = new DrawRendererSettings(cullResults, camera, m_UnlitPassName);
var unlitSettings = new DrawRendererSettings(m_CullResults, camera, m_UnlitPassName);
unlitSettings.sorting.flags = SortFlags.CommonOpaque;
unlitSettings.inputFilter.SetQueuesOpaque();

var discardRT = new CommandBuffer();
var discardRT = CommandBufferPool.Get();
discardRT.Dispose();
CommandBufferPool.Release(cmd);
context.DrawRenderers(ref unlitSettings);

lightData.pixelLightsCount = Mathf.Min(lightsCount, m_Asset.MaxSupportedPixelLights);
lightData.vertexLightsCount = (m_Asset.SupportsVertexLight) ? Mathf.Min(lightsCount - lightData.pixelLightsCount, kMaxVertexLights) : 0;
lightData.isSingleDirectionalLight = lightData.pixelLightsCount == 1 && lightData.vertexLightsCount == 0 && lights[0].lightType == LightType.Directional;
// Directional light path can handle unlit.
if (lightsCount == 0)
lightData.isSingleDirectionalLight = true;
lightData.shadowsRendered = false;
InitializeMainShadowLightIndex(lights, out lightData.shadowLightIndex);
}
private void FillLightIndices(ref CullResults cullResults, int visibleLightsCount)

cullResults.FillLightIndices(m_LightIndexListBuffer);
}
private void SetupLightShaderVariables(VisibleLight[] lights, ref CullResults cullResults, ref ScriptableRenderContext context, ref LightData lightData)
private void SetupShaderLightConstants(VisibleLight[] lights, ref LightData lightData, ref CullResults cullResults, ref ScriptableRenderContext context)
{
if (lights.Length == 0)
return;
if (lightData.isSingleDirectionalLight)
SetupShaderSingleDirectionalLightConstants(ref lights [0], ref context);
else
SetupShaderLightListConstants(lights, lightData.pixelLightsCount, ref cullResults, ref context);
}
private void SetupShaderSingleDirectionalLightConstants(ref VisibleLight light, ref ScriptableRenderContext context)
int maxLights = 1;
if (!lightData.isSingleDirectionalLight)
{
FillLightIndices(ref cullResults, lights.Length);
maxLights = Math.Min(kMaxVisibleLights, lights.Length);
}
Vector4 lightDir = -light.localToWorld.GetColumn(2);
CommandBuffer cmd = new CommandBuffer() { name = "SetupLightConstants" };
cmd.SetGlobalVector("_LightPosition0", new Vector4(lightDir.x, lightDir.y, lightDir.z, 0.0f));
cmd.SetGlobalColor("_LightColor0", light.finalColor);
context.ExecuteCommandBuffer(cmd);
cmd.Dispose();
}
// TODO: Perform tests on light lights memory pattern access (SOA vs AOS vs Swizzling)
private void SetupShaderLightListConstants(VisibleLight[] lights, int pixelLightsCount, ref CullResults cullResults, ref ScriptableRenderContext context)
{
FillLightIndices(ref cullResults, lights.Length);
int maxLights = Math.Min(kMaxVisibleLights, lights.Length);
for (int i = 0; i < maxLights; ++i)
for (int i = 0; i < maxLights; ++i)
VisibleLight currLight = lights[i];
if (currLight.lightType == LightType.Directional)
VisibleLight currLight = lights [i];
if (currLight.lightType == LightType.Directional)
Vector4 dir = -currLight.localToWorld.GetColumn(2);
m_LightPositions[i] = new Vector4(dir.x, dir.y, dir.z, 0.0f);
}
else
Vector4 dir = -currLight.localToWorld.GetColumn (2);
m_LightPositions [i] = new Vector4 (dir.x, dir.y, dir.z, 0.0f);
}
else
Vector4 pos = currLight.localToWorld.GetColumn(3);
m_LightPositions[i] = new Vector4(pos.x, pos.y, pos.z, 1.0f);
Vector4 pos = currLight.localToWorld.GetColumn (3);
m_LightPositions [i] = new Vector4 (pos.x, pos.y, pos.z, 1.0f);
}
m_LightColors[i] = currLight.finalColor;

if (currLight.lightType == LightType.Spot)
if (currLight.lightType == LightType.Spot)
Vector4 dir = currLight.localToWorld.GetColumn(2);
m_LightSpotDirections[i] = new Vector4(-dir.x, -dir.y, -dir.z, 0.0f);
Vector4 dir = currLight.localToWorld.GetColumn (2);
m_LightSpotDirections [i] = new Vector4 (-dir.x, -dir.y, -dir.z, 0.0f);
float cosOuterAngle = Mathf.Cos(spotAngle * 0.5f);
float cosInneAngle = Mathf.Cos(spotAngle * 0.25f);
float cosOuterAngle = Mathf.Cos (spotAngle * 0.5f);
float cosInneAngle = Mathf.Cos (spotAngle * 0.25f);
m_LightAttenuations[i] = new Vector4(cosOuterAngle,
Mathf.Approximately(angleRange, 0.0f) ? 1.0f : angleRange, quadAtten, rangeSq);
}
m_LightAttenuations [i] = new Vector4 (cosOuterAngle,
Mathf.Approximately (angleRange, 0.0f) ? 1.0f : angleRange, quadAtten, rangeSq);
}
m_LightSpotDirections[i] = new Vector4(0.0f, 0.0f, 1.0f, 0.0f) ;
m_LightAttenuations[i] = new Vector4(-1.0f, 1.0f, quadAtten, rangeSq);
m_LightSpotDirections [i] = new Vector4 (0.0f, 0.0f, 1.0f, 0.0f);
m_LightAttenuations [i] = new Vector4 (-1.0f, 1.0f, quadAtten, rangeSq);
CommandBuffer cmd = new CommandBuffer() {name = "SetupShadowShaderConstants"};
cmd.SetGlobalVectorArray("globalLightPos", m_LightPositions);
cmd.SetGlobalVectorArray("globalLightColor", m_LightColors);
cmd.SetGlobalVectorArray("globalLightAtten", m_LightAttenuations);
cmd.SetGlobalVectorArray("globalLightSpotDir", m_LightSpotDirections);
if (!lightData.isSingleDirectionalLight)
cmd.SetGlobalBuffer("globalLightIndexList", m_LightIndexListBuffer);
cmd.SetGlobalVector("globalLightData", new Vector4(lightData.pixelLightsCount, m_ShadowLightIndex, m_Asset.ShadowMinNormalBias, m_Asset.ShadowNormalBias));
SetShaderKeywords(cmd, lightData.isSingleDirectionalLight, lightData.vertexLightsCount > 0);
CommandBuffer cmd = CommandBufferPool.Get("SetupShadowShaderConstants");
cmd.SetGlobalVector("globalLightCount", new Vector4 (pixelLightsCount, 0.0f, 0.0f, 0.0f));
cmd.SetGlobalVectorArray ("globalLightPos", m_LightPositions);
cmd.SetGlobalVectorArray ("globalLightColor", m_LightColors);
cmd.SetGlobalVectorArray ("globalLightAtten", m_LightAttenuations);
cmd.SetGlobalVectorArray ("globalLightSpotDir", m_LightSpotDirections);
cmd.SetGlobalBuffer("globalLightIndexList", m_LightIndexListBuffer);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
private void SetShaderKeywords(ref LightData lightData, ref ScriptableRenderContext context)
{
CommandBuffer cmd = new CommandBuffer() { name = "SetShaderKeywords" };
SetShaderKeywords(cmd, lightData.shadowsRendered, lightData.isSingleDirectionalLight, lightData.vertexLightsCount > 0);
private bool RenderShadows(ref CullResults cullResults, ref VisibleLight shadowLight, ref ScriptableRenderContext context)
private bool RenderShadows(ref CullResults cullResults, ref VisibleLight shadowLight, int shadowLightIndex, ref ScriptableRenderContext context)
{
m_ShadowCasterCascadesCount = m_ShadowSettings.directionalLightCascadeCount;

int shadowResolution = GetMaxTileResolutionInAtlas(m_ShadowSettings.shadowAtlasWidth, m_ShadowSettings.shadowAtlasHeight, m_ShadowCasterCascadesCount);
Bounds bounds;
if (!cullResults.GetShadowCasterBounds(m_ShadowLightIndex, out bounds))
if (!cullResults.GetShadowCasterBounds(shadowLightIndex, out bounds))
var setRenderTargetCommandBuffer = new CommandBuffer();
var setRenderTargetCommandBuffer = CommandBufferPool.Get();
setRenderTargetCommandBuffer.name = "Render packed shadows";
setRenderTargetCommandBuffer.GetTemporaryRT(m_ShadowMapProperty, m_ShadowSettings.shadowAtlasWidth,
m_ShadowSettings.shadowAtlasHeight, m_DepthBufferBits, FilterMode.Bilinear, RenderTextureFormat.Depth,

context.ExecuteCommandBuffer(setRenderTargetCommandBuffer);
setRenderTargetCommandBuffer.Dispose();
CommandBufferPool.Release(setRenderTargetCommandBuffer);
Vector3 lightDir = Vector3.Normalize(shadowLight.light.transform.forward);
var settings = new DrawShadowsSettings(cullResults, m_ShadowLightIndex);
var settings = new DrawShadowsSettings(cullResults, shadowLightIndex);
needRendering = cullResults.ComputeSpotShadowMatricesAndCullingPrimitives(m_ShadowLightIndex, out view, out proj,
needRendering = cullResults.ComputeSpotShadowMatricesAndCullingPrimitives(shadowLightIndex, out view, out proj,
out settings.splitData);
if (!needRendering)

RenderShadowSlice(ref context, lightDir, 0, proj, view, settings);
RenderShadowSlice(ref context, 0, proj, view, settings);
needRendering = cullResults.ComputeDirectionalShadowMatricesAndCullingPrimitives(m_ShadowLightIndex,
needRendering = cullResults.ComputeDirectionalShadowMatricesAndCullingPrimitives(shadowLightIndex,
cascadeIdx, m_ShadowCasterCascadesCount, splitRatio, shadowResolution, shadowNearPlane, out view, out proj,
out settings.splitData);

return false;
SetupShadowSliceTransform(cascadeIdx, shadowResolution, proj, view);
RenderShadowSlice(ref context, lightDir, cascadeIdx, proj, view, settings);
RenderShadowSlice(ref context, cascadeIdx, proj, view, settings);
}
}
else

m_ShadowSlices[cascadeIndex].shadowTransform = matTile * matScaleBias * proj * view;
}
private void RenderShadowSlice(ref ScriptableRenderContext context, Vector3 lightDir, int cascadeIndex,
private void RenderShadowSlice(ref ScriptableRenderContext context, int cascadeIndex,
var buffer = new CommandBuffer() {name = "Prepare Shadowmap Slice"};
var buffer = CommandBufferPool.Get("Prepare Shadowmap Slice");
buffer.Dispose();
CommandBufferPool.Release(buffer);
}
private int GetMaxTileResolutionInAtlas(int atlasWidth, int atlasHeight, int tileCount)

return resolution;
}
private void SetupShadowShaderVariables(ref ScriptableRenderContext context, int cascadeCount)
private void SetupShadowShaderConstants(ref ScriptableRenderContext context, ref VisibleLight shadowLight, int shadowLightIndex, int cascadeCount)
Vector3 shadowLightDir = Vector3.Normalize(shadowLight.localToWorld.GetColumn(2));
// TODO: multiplying by 0.1 to get similar results to Unity vanilla shadow bias
float bias = shadowLight.light.shadowBias * 0.1f;
float normalBias = shadowLight.light.shadowNormalBias;
float shadowResolution = m_ShadowSlices[0].shadowResolution;
const int maxShadowCascades = 4;

0.5f * invShadowResolution, -0.5f * invShadowResolution
};
var setupShadow = new CommandBuffer() {name = "SetupShadowShaderConstants"};
var setupShadow = CommandBufferPool.Get("SetupShadowShaderConstants");
setupShadow.SetGlobalVector("_ShadowLightDirection", new Vector4(-shadowLightDir.x, -shadowLightDir.y, -shadowLightDir.z, 0.0f));
setupShadow.SetGlobalVector("_ShadowData", new Vector4(shadowLightIndex, bias, normalBias, 0.0f));
setupShadow.Dispose();
CommandBufferPool.Release(setupShadow);
private void SetShaderKeywords(CommandBuffer cmd, bool singleDirecitonal, bool vertexLightSupport)
private void SetShaderKeywords(CommandBuffer cmd, bool renderShadows, bool singleDirecitonal, bool vertexLightSupport)
{
if (vertexLightSupport)
cmd.EnableShaderKeyword("_VERTEX_LIGHTS");

for (int i = 0; i < shadowKeywords.Length; ++i)
cmd.DisableShaderKeyword(shadowKeywords[i]);
if (m_ShadowLightIndex != -1 && m_Asset.CurrShadowType != ShadowType.NO_SHADOW)
if (renderShadows && m_Asset.CurrShadowType != ShadowType.NO_SHADOW)
{
int keywordIndex = (int)m_Asset.CurrShadowType - 1;
if (m_Asset.CascadeCount > 1)

cmd.DisableShaderKeyword("_LIGHT_PROBES_ON");
}
private void InitializeMainShadowLightIndex(VisibleLight[] lights)
private void InitializeMainShadowLightIndex(VisibleLight[] lights, out int shadowIndex)
m_ShadowLightIndex = -1;
shadowIndex = -1;
float maxIntensity = -1;
for (int i = 0; i < lights.Length; ++i)
{

m_ShadowLightIndex = i;
shadowIndex = i;
maxIntensity = light.intensity;
}
}

{
return (type == LightType.Directional || type == LightType.Spot);
}
}
}

2
Assets/ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset


m_ShadowAtlasResolution: 1024
m_ShadowNearPlaneOffset: 2
m_ShadowDistance: 50
m_MinShadowNormalBias: 0.0005
m_ShadowNormalBias: 0.05
m_ShadowCascades: 1
m_Cascade2Split: 0.25
m_Cascade4Split: {x: 0.067, y: 0.2, z: 0.467}

18
Assets/ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.cs


private static readonly string m_AssetName = "LightweightPipelineAsset.asset";
#if UNITY_EDITOR
[UnityEditor.MenuItem("RenderPipeline/LightweightPipeline/Create Pipeline Asset")]
[UnityEditor.MenuItem("RenderPipeline/LightweightPipeline/Create Pipeline Asset", false, 15)]
static void CreateLightweightPipeline()
{
var instance = ScriptableObject.CreateInstance<LightweightPipelineAsset>();

[SerializeField] private ShadowResolution m_ShadowAtlasResolution = ShadowResolution._1024;
[SerializeField] private float m_ShadowNearPlaneOffset = 2.0f;
[SerializeField] private float m_ShadowDistance = 50.0f;
[SerializeField] private float m_MinShadowNormalBias = 0.0005f;
[SerializeField] private float m_ShadowNormalBias = 0.05f;
[SerializeField] private ShadowCascades m_ShadowCascades = ShadowCascades.NO_CASCADES;
[SerializeField] private float m_Cascade2Split = 0.25f;
[SerializeField] private Vector3 m_Cascade4Split = new Vector3(0.067f, 0.2f, 0.467f);

private set { m_ShadowDistance = value; }
}
public float ShadowMinNormalBias
{
get { return m_MinShadowNormalBias; }
private set { m_MinShadowNormalBias = value; }
}
public float ShadowNormalBias
{
get { return m_ShadowNormalBias; }
private set { m_ShadowNormalBias = value; }
}
public float Cascade2Split
{
get { return m_Cascade2Split; }

37
Assets/ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPipeline.shader


#if defined(_VERTEX_LIGHTS) && !defined(_SINGLE_DIRECTIONAL_LIGHT)
half4 diffuseAndSpecular = half4(1.0, 1.0, 1.0, 1.0);
int vertexLightStart = unity_LightIndicesOffsetAndCount.x + globalLightData.x;
int vertexLightEnd = vertexLightStart + (unity_LightIndicesOffsetAndCount.y - globalLightData.x);
int vertexLightStart = unity_LightIndicesOffsetAndCount.x + globalLightCount.x;
int vertexLightEnd = vertexLightStart + (unity_LightIndicesOffsetAndCount.y - globalLightCount.x);
half NdotL;
o.fogCoord.yzw += EvaluateOneLight(lightInput, diffuseAndSpecular.rgb, diffuseAndSpecular, normal, o.posWS, o.viewDir.xyz, NdotL);
o.fogCoord.yzw += EvaluateOneLight(lightInput, diffuseAndSpecular.rgb, diffuseAndSpecular, normal, o.posWS, o.viewDir.xyz);
}
#endif

half3 viewDir = i.viewDir.xyz;
half3 color = half3(0, 0, 0);
LightInput lightData;
INITIALIZE_LIGHT(lightData, 0);
half NdotL;
color = EvaluateOneLight(lightData, diffuse, specularGloss, normal, i.posWS, viewDir, NdotL);
half3 color = EvaluateDirectionalLight(diffuse, specularGloss, normal, _LightPosition0, viewDir) * _LightColor0;
float bias = max(globalLightData.z, (1.0 - NdotL) * globalLightData.w);
color *= ComputeShadowAttenuation(i, bias);
color *= ComputeShadowAttenuation(i, _LightPosition0.xyz);
int pixelLightEnd = unity_LightIndicesOffsetAndCount.x + min(globalLightData.x, unity_LightIndicesOffsetAndCount.y);
half3 color = half3(0, 0, 0);
#ifdef _SHADOWS
half shadowAttenuation = ComputeShadowAttenuation(i, _ShadowLightDirection.xyz);
#endif
int pixelLightEnd = unity_LightIndicesOffsetAndCount.x + min(globalLightCount.x, unity_LightIndicesOffsetAndCount.y);
half NdotL;
color += EvaluateOneLight(lightData, diffuse, specularGloss, normal, i.posWS, viewDir, NdotL);
if (lightIndex == globalLightData.y)
{
float bias = max(globalLightData.z, (1.0 - NdotL) * globalLightData.w);
color *= ComputeShadowAttenuation(i, bias);
}
// multiplies shadowAttenuation to avoid branching.
// step will only evaluate to 1 when lightIndex == _ShadowData.x (shadowLightIndex)
half currLightAttenuation = shadowAttenuation * step(abs(lightIndex - _ShadowData.x), 0);
color += EvaluateOneLight(lightData, diffuse, specularGloss, normal, i.posWS, viewDir) * currLightAttenuation;
#else
color += EvaluateOneLight(lightData, diffuse, specularGloss, normal, i.posWS, viewDir);
#endif
}

float4 vert(float4 pos : POSITION) : SV_POSITION
{
float4 clipPos = UnityObjectToClipPos(pos);
float4 clipPos = UnityObjectToClipPos(pos);
#if defined(UNITY_REVERSED_Z)
clipPos.z = min(clipPos.z, UNITY_NEAR_CLIP_VALUE);
#else

38
Assets/ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPipelineCore.cginc


float4 hpos : SV_POSITION;
};
// Per object light list data
#ifndef _SINGLE_DIRECTIONAL_LIGHT
half4 unity_LightIndicesOffsetAndCount;
StructuredBuffer<uint> globalLightIndexList;
half4 globalLightCount;
float4 globalLightData; // x: pixelLightCount, y = shadowLightIndex, z = minShadowNormalBiasOffset, w = shadowNormalBiasOffset
// Per object light list data
#ifndef _SINGLE_DIRECTIONAL_LIGHT
half4 unity_LightIndicesOffsetAndCount;
StructuredBuffer<uint> globalLightIndexList;
#else
float4 _LightPosition0;
#endif
half _Shininess;

#endif
}
inline half3 EvaluateOneLight(LightInput lightInput, half3 diffuseColor, half4 specularGloss, half3 normal, float3 posWorld, half3 viewDir, out half NdotL)
inline half3 EvaluateDirectionalLight(half3 diffuseColor, half4 specularGloss, half3 normal, half3 lightDir, half3 viewDir)
{
half NdotL = saturate(dot(normal, lightDir));
half3 diffuse = diffuseColor * NdotL;
#if defined(_SPECGLOSSMAP_BASE_ALPHA) || defined(_SPECGLOSSMAP) || defined(_SPECULAR_COLOR)
half3 halfVec = normalize(lightDir + viewDir);
half NdotH = saturate(dot(normal, halfVec));
half3 specular = specularGloss.rgb * pow(NdotH, _Shininess * 128.0) * specularGloss.a;
return diffuse + specular;
#else
return diffuse;
#endif
}
inline half3 EvaluateOneLight(LightInput lightInput, half3 diffuseColor, half4 specularGloss, half3 normal, float3 posWorld, half3 viewDir)
{
float3 posToLight = lightInput.pos.xyz;
posToLight -= posWorld * lightInput.pos.w;

half cutoff = step(distanceSqr, lightInput.atten.w);
lightAtten *= cutoff;
NdotL = saturate(dot(normal, lightDir));
half3 halfVec = normalize(lightDir + viewDir);
half NdotH = saturate(dot(normal, halfVec));
half NdotL = saturate(dot(normal, lightDir));
half3 halfVec = normalize(lightDir + viewDir);
half NdotH = saturate(dot(normal, halfVec));
half3 specular = specularGloss.rgb * lightColor * pow(NdotH, _Shininess * 128.0) * specularGloss.a;
return diffuse + specular;
#else

27
Assets/ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPipelineShadows.cginc


float _PCFKernel[8];
float4x4 _WorldToShadow[MAX_SHADOW_CASCADES];
float4 _DirShadowSplitSpheres[MAX_SHADOW_CASCADES];
half4 _ShadowData;
// In case of single directional light, shadow light dir is the same of light dir
#ifndef _SINGLE_DIRECTIONAL_LIGHT
half4 _ShadowLightDirection;
#endif
inline half ShadowAttenuation(float3 shadowCoord)
{

float depth = tex2D(_ShadowMap, shadowCoord).r;
return step(depth, shadowCoord.z);
return step(depth - _ShadowData.y, shadowCoord.z);
return step(shadowCoord.z, depth);
return step(shadowCoord.z, depth + _ShadowData.y);
#endif
}

return attenuation * 0.25;
}
inline half ComputeShadowAttenuation(v2f i, float bias)
inline half ComputeShadowAttenuation(v2f i, half3 shadowDir)
float3 vertexNormal = float3(i.tangentToWorld0.z, i.tangentToWorld1.z, i.tangentToWorld2.z);
half3 vertexNormal = half3(i.tangentToWorld0.z, i.tangentToWorld1.z, i.tangentToWorld2.z);
float3 vertexNormal = i.normal;
half3 vertexNormal = i.normal;
float3 offset = vertexNormal * bias;
half NdotL = dot(vertexNormal, shadowDir);
half bias = saturate(1.0 - NdotL) * _ShadowData.z;
float3 posWorldOffsetNormal = i.posWS + vertexNormal * bias;
float3 posWorldOffsetNormal = i.posWS + offset;
cascadeIndex = ComputeCascadeIndex(i.posWS);
cascadeIndex = ComputeCascadeIndex(posWorldOffsetNormal);
if (cascadeIndex >= MAX_SHADOW_CASCADES)
return 1.0;
#endif

3
Assets/ScriptableRenderPipeline/ShaderLibrary/Common.hlsl


// uniform have _ as prefix + uppercase _LowercaseThenCamelCase
// All uniforms should be in contant buffer (nothing in the global namespace).
// The reason is that for compute shader we need to guarantee that the layout of CBs is consistent across kernels. Something that we can't control with the global namespace (uniforms get optimized out if not used, modifying the global CBuffer layout per kernel)
// Structure definition that are share between C# and hlsl.
// These structures need to be align on float4 to respectect various packing rules from sahder language.
// This mean that these structure need to be padded.

427
Assets/ScriptableRenderPipeline/ShaderLibrary/Fibonacci.hlsl


// Computes a point using the Fibonacci sequence of length N.
// Input: Fib[N - 1], Fib[N - 2], and the index 'i' of the point.
// Ref: Integration of nonperiodic functions of two variables by Fibonacci lattice rules
// Ref: Efficient Quadrature Rules for Illumination Integrals
return float2(i / fibN1, frac(i * (fibN2 / fibN1)));
// N.b.: According to Swinbank and Pusser [SP06], the uniformity of the distribution
// can be slightly improved by introducing an offset of 1/N to the Z (or R) coordinates.
return float2(i / fibN1 + (0.5f / fibN1), frac(i * (fibN2 / fibN1)));
}
static const int k_FibonacciSeq[] = {

static const float2 k_Fibonacci2dSeq21[] = {
float2(0.00000000, 0.00000000),
float2(0.04761905, 0.61904764),
float2(0.09523810, 0.23809528),
float2(0.14285715, 0.85714293),
float2(0.19047619, 0.47619057),
float2(0.23809524, 0.09523821),
float2(0.28571430, 0.71428585),
float2(0.33333334, 0.33333349),
float2(0.38095239, 0.95238113),
float2(0.42857143, 0.57142878),
float2(0.47619048, 0.19047642),
float2(0.52380955, 0.80952406),
float2(0.57142860, 0.42857170),
float2(0.61904764, 0.04761887),
float2(0.66666669, 0.66666698),
float2(0.71428573, 0.28571510),
float2(0.76190478, 0.90476227),
float2(0.80952382, 0.52380943),
float2(0.85714287, 0.14285755),
float2(0.90476191, 0.76190567),
float2(0.95238096, 0.38095284)
float2(0.02380952, 0.00000000),
float2(0.07142857, 0.61904764),
float2(0.11904762, 0.23809528),
float2(0.16666667, 0.85714293),
float2(0.21428572, 0.47619057),
float2(0.26190478, 0.09523821),
float2(0.30952382, 0.71428585),
float2(0.35714287, 0.33333349),
float2(0.40476191, 0.95238113),
float2(0.45238096, 0.57142878),
float2(0.50000000, 0.19047642),
float2(0.54761904, 0.80952406),
float2(0.59523809, 0.42857170),
float2(0.64285713, 0.04761887),
float2(0.69047618, 0.66666698),
float2(0.73809522, 0.28571510),
float2(0.78571427, 0.90476227),
float2(0.83333331, 0.52380943),
float2(0.88095236, 0.14285755),
float2(0.92857140, 0.76190567),
float2(0.97619045, 0.38095284)
float2(0.00000000, 0.00000000),
float2(0.02941176, 0.61764705),
float2(0.05882353, 0.23529410),
float2(0.08823530, 0.85294116),
float2(0.11764706, 0.47058821),
float2(0.14705883, 0.08823538),
float2(0.17647059, 0.70588231),
float2(0.20588236, 0.32352924),
float2(0.23529412, 0.94117641),
float2(0.26470590, 0.55882359),
float2(0.29411766, 0.17647076),
float2(0.32352942, 0.79411745),
float2(0.35294119, 0.41176462),
float2(0.38235295, 0.02941132),
float2(0.41176471, 0.64705849),
float2(0.44117647, 0.26470566),
float2(0.47058824, 0.88235283),
float2(0.50000000, 0.50000000),
float2(0.52941179, 0.11764717),
float2(0.55882353, 0.73529434),
float2(0.58823532, 0.35294151),
float2(0.61764705, 0.97058773),
float2(0.64705884, 0.58823490),
float2(0.67647058, 0.20588207),
float2(0.70588237, 0.82352924),
float2(0.73529410, 0.44117641),
float2(0.76470590, 0.05882263),
float2(0.79411763, 0.67646980),
float2(0.82352942, 0.29411697),
float2(0.85294116, 0.91176414),
float2(0.88235295, 0.52941132),
float2(0.91176468, 0.14705849),
float2(0.94117647, 0.76470566),
float2(0.97058821, 0.38235283)
float2(0.01470588, 0.00000000),
float2(0.04411765, 0.61764705),
float2(0.07352941, 0.23529410),
float2(0.10294118, 0.85294116),
float2(0.13235295, 0.47058821),
float2(0.16176471, 0.08823538),
float2(0.19117647, 0.70588231),
float2(0.22058824, 0.32352924),
float2(0.25000000, 0.94117641),
float2(0.27941176, 0.55882359),
float2(0.30882353, 0.17647076),
float2(0.33823529, 0.79411745),
float2(0.36764705, 0.41176462),
float2(0.39705881, 0.02941132),
float2(0.42647058, 0.64705849),
float2(0.45588234, 0.26470566),
float2(0.48529410, 0.88235283),
float2(0.51470590, 0.50000000),
float2(0.54411763, 0.11764717),
float2(0.57352942, 0.73529434),
float2(0.60294116, 0.35294151),
float2(0.63235295, 0.97058773),
float2(0.66176468, 0.58823490),
float2(0.69117647, 0.20588207),
float2(0.72058821, 0.82352924),
float2(0.75000000, 0.44117641),
float2(0.77941179, 0.05882263),
float2(0.80882353, 0.67646980),
float2(0.83823532, 0.29411697),
float2(0.86764705, 0.91176414),
float2(0.89705884, 0.52941132),
float2(0.92647058, 0.14705849),
float2(0.95588237, 0.76470566),
float2(0.98529410, 0.38235283)
float2(0.00000000, 0.00000000),
float2(0.01818182, 0.61818182),
float2(0.03636364, 0.23636365),
float2(0.05454545, 0.85454547),
float2(0.07272727, 0.47272730),
float2(0.09090909, 0.09090900),
float2(0.10909091, 0.70909095),
float2(0.12727273, 0.32727289),
float2(0.14545454, 0.94545460),
float2(0.16363636, 0.56363630),
float2(0.18181819, 0.18181801),
float2(0.20000000, 0.80000019),
float2(0.21818182, 0.41818190),
float2(0.23636363, 0.03636360),
float2(0.25454545, 0.65454578),
float2(0.27272728, 0.27272701),
float2(0.29090908, 0.89090919),
float2(0.30909091, 0.50909138),
float2(0.32727271, 0.12727261),
float2(0.34545454, 0.74545479),
float2(0.36363637, 0.36363602),
float2(0.38181818, 0.98181820),
float2(0.40000001, 0.60000038),
float2(0.41818181, 0.21818161),
float2(0.43636364, 0.83636379),
float2(0.45454547, 0.45454597),
float2(0.47272727, 0.07272720),
float2(0.49090910, 0.69090843),
float2(0.50909090, 0.30909157),
float2(0.52727270, 0.92727280),
float2(0.54545456, 0.54545403),
float2(0.56363636, 0.16363716),
float2(0.58181816, 0.78181839),
float2(0.60000002, 0.39999962),
float2(0.61818182, 0.01818275),
float2(0.63636363, 0.63636398),
float2(0.65454543, 0.25454521),
float2(0.67272729, 0.87272835),
float2(0.69090909, 0.49090958),
float2(0.70909089, 0.10909081),
float2(0.72727275, 0.72727203),
float2(0.74545455, 0.34545517),
float2(0.76363635, 0.96363640),
float2(0.78181821, 0.58181763),
float2(0.80000001, 0.20000076),
float2(0.81818181, 0.81818199),
float2(0.83636361, 0.43636322),
float2(0.85454547, 0.05454636),
float2(0.87272727, 0.67272758),
float2(0.89090908, 0.29090881),
float2(0.90909094, 0.90909195),
float2(0.92727274, 0.52727318),
float2(0.94545454, 0.14545441),
float2(0.96363634, 0.76363754),
float2(0.98181820, 0.38181686)
float2(0.00909091, 0.00000000),
float2(0.02727273, 0.61818182),
float2(0.04545455, 0.23636365),
float2(0.06363636, 0.85454547),
float2(0.08181818, 0.47272730),
float2(0.10000000, 0.09090900),
float2(0.11818182, 0.70909095),
float2(0.13636364, 0.32727289),
float2(0.15454546, 0.94545460),
float2(0.17272727, 0.56363630),
float2(0.19090909, 0.18181801),
float2(0.20909090, 0.80000019),
float2(0.22727273, 0.41818190),
float2(0.24545455, 0.03636360),
float2(0.26363635, 0.65454578),
float2(0.28181818, 0.27272701),
float2(0.30000001, 0.89090919),
float2(0.31818181, 0.50909138),
float2(0.33636364, 0.12727261),
float2(0.35454544, 0.74545479),
float2(0.37272727, 0.36363602),
float2(0.39090911, 0.98181820),
float2(0.40909091, 0.60000038),
float2(0.42727274, 0.21818161),
float2(0.44545454, 0.83636379),
float2(0.46363637, 0.45454597),
float2(0.48181817, 0.07272720),
float2(0.50000000, 0.69090843),
float2(0.51818180, 0.30909157),
float2(0.53636366, 0.92727280),
float2(0.55454546, 0.54545403),
float2(0.57272726, 0.16363716),
float2(0.59090906, 0.78181839),
float2(0.60909092, 0.39999962),
float2(0.62727273, 0.01818275),
float2(0.64545453, 0.63636398),
float2(0.66363639, 0.25454521),
float2(0.68181819, 0.87272835),
float2(0.69999999, 0.49090958),
float2(0.71818179, 0.10909081),
float2(0.73636365, 0.72727203),
float2(0.75454545, 0.34545517),
float2(0.77272725, 0.96363640),
float2(0.79090911, 0.58181763),
float2(0.80909091, 0.20000076),
float2(0.82727271, 0.81818199),
float2(0.84545457, 0.43636322),
float2(0.86363637, 0.05454636),
float2(0.88181818, 0.67272758),
float2(0.89999998, 0.29090881),
float2(0.91818184, 0.90909195),
float2(0.93636364, 0.52727318),
float2(0.95454544, 0.14545441),
float2(0.97272730, 0.76363754),
float2(0.99090910, 0.38181686)
float2(0.00000000, 0.00000000),
float2(0.01123596, 0.61797750),
float2(0.02247191, 0.23595500),
float2(0.03370786, 0.85393250),
float2(0.04494382, 0.47191000),
float2(0.05617978, 0.08988762),
float2(0.06741573, 0.70786500),
float2(0.07865169, 0.32584238),
float2(0.08988764, 0.94382000),
float2(0.10112359, 0.56179762),
float2(0.11235955, 0.17977524),
float2(0.12359551, 0.79775238),
float2(0.13483146, 0.41573000),
float2(0.14606741, 0.03370762),
float2(0.15730338, 0.65168476),
float2(0.16853933, 0.26966286),
float2(0.17977528, 0.88764000),
float2(0.19101124, 0.50561714),
float2(0.20224719, 0.12359524),
float2(0.21348314, 0.74157238),
float2(0.22471911, 0.35955048),
float2(0.23595506, 0.97752762),
float2(0.24719101, 0.59550476),
float2(0.25842696, 0.21348286),
float2(0.26966292, 0.83146000),
float2(0.28089887, 0.44943714),
float2(0.29213482, 0.06741524),
float2(0.30337077, 0.68539238),
float2(0.31460676, 0.30336952),
float2(0.32584271, 0.92134666),
float2(0.33707866, 0.53932571),
float2(0.34831461, 0.15730286),
float2(0.35955057, 0.77528000),
float2(0.37078652, 0.39325714),
float2(0.38202247, 0.01123428),
float2(0.39325842, 0.62921333),
float2(0.40449437, 0.24719048),
float2(0.41573033, 0.86516762),
float2(0.42696628, 0.48314476),
float2(0.43820226, 0.10112190),
float2(0.44943821, 0.71910095),
float2(0.46067417, 0.33707809),
float2(0.47191012, 0.95505524),
float2(0.48314607, 0.57303238),
float2(0.49438202, 0.19100952),
float2(0.50561798, 0.80898666),
float2(0.51685393, 0.42696571),
float2(0.52808988, 0.04494286),
float2(0.53932583, 0.66292000),
float2(0.55056179, 0.28089714),
float2(0.56179774, 0.89887428),
float2(0.57303369, 0.51685333),
float2(0.58426964, 0.13483047),
float2(0.59550560, 0.75280762),
float2(0.60674155, 0.37078476),
float2(0.61797750, 0.98876190),
float2(0.62921351, 0.60673904),
float2(0.64044946, 0.22471619),
float2(0.65168542, 0.84269333),
float2(0.66292137, 0.46067429),
float2(0.67415732, 0.07865143),
float2(0.68539327, 0.69662857),
float2(0.69662923, 0.31460571),
float2(0.70786518, 0.93258286),
float2(0.71910113, 0.55056000),
float2(0.73033708, 0.16853714),
float2(0.74157304, 0.78651428),
float2(0.75280899, 0.40449142),
float2(0.76404494, 0.02246857),
float2(0.77528089, 0.64044571),
float2(0.78651685, 0.25842667),
float2(0.79775280, 0.87640381),
float2(0.80898875, 0.49438095),
float2(0.82022470, 0.11235809),
float2(0.83146065, 0.73033524),
float2(0.84269661, 0.34831238),
float2(0.85393256, 0.96628952),
float2(0.86516851, 0.58426666),
float2(0.87640452, 0.20224380),
float2(0.88764048, 0.82022095),
float2(0.89887643, 0.43820190),
float2(0.91011238, 0.05617905),
float2(0.92134833, 0.67415619),
float2(0.93258429, 0.29213333),
float2(0.94382024, 0.91011047),
float2(0.95505619, 0.52808762),
float2(0.96629214, 0.14606476),
float2(0.97752810, 0.76404190),
float2(0.98876405, 0.38201904)
float2(0.00561798, 0.00000000),
float2(0.01685393, 0.61797750),
float2(0.02808989, 0.23595500),
float2(0.03932584, 0.85393250),
float2(0.05056180, 0.47191000),
float2(0.06179775, 0.08988762),
float2(0.07303371, 0.70786500),
float2(0.08426967, 0.32584238),
float2(0.09550562, 0.94382000),
float2(0.10674157, 0.56179762),
float2(0.11797753, 0.17977524),
float2(0.12921348, 0.79775238),
float2(0.14044943, 0.41573000),
float2(0.15168539, 0.03370762),
float2(0.16292135, 0.65168476),
float2(0.17415731, 0.26966286),
float2(0.18539326, 0.88764000),
float2(0.19662921, 0.50561714),
float2(0.20786516, 0.12359524),
float2(0.21910113, 0.74157238),
float2(0.23033708, 0.35955048),
float2(0.24157304, 0.97752762),
float2(0.25280899, 0.59550476),
float2(0.26404494, 0.21348286),
float2(0.27528089, 0.83146000),
float2(0.28651685, 0.44943714),
float2(0.29775280, 0.06741524),
float2(0.30898875, 0.68539238),
float2(0.32022473, 0.30336952),
float2(0.33146068, 0.92134666),
float2(0.34269664, 0.53932571),
float2(0.35393259, 0.15730286),
float2(0.36516854, 0.77528000),
float2(0.37640449, 0.39325714),
float2(0.38764045, 0.01123428),
float2(0.39887640, 0.62921333),
float2(0.41011235, 0.24719048),
float2(0.42134830, 0.86516762),
float2(0.43258426, 0.48314476),
float2(0.44382024, 0.10112190),
float2(0.45505619, 0.71910095),
float2(0.46629214, 0.33707809),
float2(0.47752810, 0.95505524),
float2(0.48876405, 0.57303238),
float2(0.50000000, 0.19100952),
float2(0.51123595, 0.80898666),
float2(0.52247190, 0.42696571),
float2(0.53370786, 0.04494286),
float2(0.54494381, 0.66292000),
float2(0.55617976, 0.28089714),
float2(0.56741571, 0.89887428),
float2(0.57865167, 0.51685333),
float2(0.58988762, 0.13483047),
float2(0.60112357, 0.75280762),
float2(0.61235952, 0.37078476),
float2(0.62359548, 0.98876190),
float2(0.63483149, 0.60673904),
float2(0.64606744, 0.22471619),
float2(0.65730339, 0.84269333),
float2(0.66853935, 0.46067429),
float2(0.67977530, 0.07865143),
float2(0.69101125, 0.69662857),
float2(0.70224720, 0.31460571),
float2(0.71348315, 0.93258286),
float2(0.72471911, 0.55056000),
float2(0.73595506, 0.16853714),
float2(0.74719101, 0.78651428),
float2(0.75842696, 0.40449142),
float2(0.76966292, 0.02246857),
float2(0.78089887, 0.64044571),
float2(0.79213482, 0.25842667),
float2(0.80337077, 0.87640381),
float2(0.81460673, 0.49438095),
float2(0.82584268, 0.11235809),
float2(0.83707863, 0.73033524),
float2(0.84831458, 0.34831238),
float2(0.85955054, 0.96628952),
float2(0.87078649, 0.58426666),
float2(0.88202250, 0.20224380),
float2(0.89325845, 0.82022095),
float2(0.90449440, 0.43820190),
float2(0.91573036, 0.05617905),
float2(0.92696631, 0.67415619),
float2(0.93820226, 0.29213333),
float2(0.94943821, 0.91011047),
float2(0.96067417, 0.52808762),
float2(0.97191012, 0.14606476),
float2(0.98314607, 0.76404190),
float2(0.99438202, 0.38201904)
// Loads elements from one of the precomputed tables for sample counts of 21, 34, 55.
// Loads elements from one of the precomputed tables for sample counts of 21, 34, 55, and 89.
// Computes sample positions at runtime otherwise.
// Sample count must be a Fibonacci number (see 'k_FibonacciSeq').
float2 Fibonacci2d(uint i, uint sampleCount)

return Fibonacci2dSeq(fibN1, fibN2, i);
}
}
}
// Returns the radius as the X coordinate, and the angle as the Y coordinate.
float2 SampleDiskFibonacci(uint i, uint sampleCount)
{
float2 f = Fibonacci2d(i, sampleCount);
return float2(f.x, TWO_PI * f.y);
}
// Returns the zenith as the X coordinate, and the azimuthal angle as the Y coordinate.
float2 SampleHemisphereFibonacci(uint i, uint sampleCount)
{
float2 f = Fibonacci2d(i, sampleCount);
return float2(1 - f.x, TWO_PI * f.y);
}
// Returns the zenith as the X coordinate, and the azimuthal angle as the Y coordinate.
float2 SampleSphereFibonacci(uint i, uint sampleCount)
{
float2 f = Fibonacci2d(i, sampleCount);
return float2(1 - 2 * f.x, TWO_PI * f.y);
}
#endif // UNITY_FIBONACCI_INCLUDED

999
ImageTemplates/LightweightPipeline/Scenes/MultiplePointLights.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/LightweightPipeline/Scenes/Shaders/LDPipe_LitShaderMaps.unity.png
文件差异内容过多而无法显示
查看文件

2
ProjectSettings/ProjectVersion.txt


m_EditorVersion: 2017.2.0a4
m_EditorVersion: 2017.2.0b1

10
Assets/ScriptableRenderPipeline/HDRenderPipeline/AdditionalData.meta


fileFormatVersion: 2
guid: 969f45cd0fa680646a77e82d620ba21d
folderAsset: yes
timeCreated: 1498051186
licenseType: Pro
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

54
Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/CameraMotionVectors.shader


Shader "Hidden/HDRenderPipeline/CameraMotionVectors"
{
HLSLINCLUDE
#pragma target 4.5
#include "../../ShaderLibrary/Common.hlsl"
#include "../ShaderVariables.hlsl"
#include "../ShaderPass/FragInputs.hlsl"
#include "../ShaderPass/VaryingMesh.hlsl"
#include "../ShaderPass/VertMesh.hlsl"
PackedVaryingsType Vert(AttributesMesh inputMesh)
{
VaryingsType varyingsType;
varyingsType.vmesh = VertMesh(inputMesh);
return PackVaryingsType(varyingsType);
}
float4 Frag(PackedVaryingsToPS packedInput) : SV_Target
{
PositionInputs posInput = GetPositionInput(packedInput.vmesh.positionCS.xy, _ScreenSize.zw);
float depth = LOAD_TEXTURE2D(_MainDepthTexture, posInput.unPositionSS).x;
float3 vPos = ComputeViewSpacePosition(posInput.positionSS, depth, _InvProjMatrix);
float4 worldPos = mul(unity_CameraToWorld, float4(vPos, 1.0));
float4 prevClipPos = mul(_PrevViewProjMatrix, worldPos);
float4 curClipPos = mul(_ViewProjMatrix, worldPos);
float2 prevHPos = prevClipPos.xy / prevClipPos.w;
float2 curHPos = curClipPos.xy / curClipPos.w;
float2 previousPositionCS = (prevHPos + 1.0) / 2.0;
float2 positionCS = (curHPos + 1.0) / 2.0;
return float4(positionCS - previousPositionCS, 0.0, 1.0);
}
ENDHLSL
SubShader
{
Cull Off ZWrite Off ZTest Always
Pass
{
HLSLPROGRAM
#pragma vertex Vert
#pragma fragment Frag
ENDHLSL
}
}
}

9
Assets/ScriptableRenderPipeline/HDRenderPipeline/RenderPipelineResources/CameraMotionVectors.shader.meta


fileFormatVersion: 2
guid: 035941b63024d1943af48811c1db20d9
timeCreated: 1497432609
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

10
Assets/TestScenes/HDTest/HDRenderLoopTest.meta


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

12
Assets/ScriptableRenderPipeline/HDRenderPipeline/AdditionalData/HDAdditionalCameraData.cs


namespace UnityEngine.Experimental.Rendering
{
// This struct allow to add specialized path in HDRenderPipeline (can be use to render mini map or planar reflection etc...)
public enum RenderingPathHDRP { Default, Unlit };
[DisallowMultipleComponent, ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class HDAdditionalCameraData : MonoBehaviour
{
public RenderingPathHDRP renderingPath;
}
}

13
Assets/ScriptableRenderPipeline/HDRenderPipeline/AdditionalData/HDAdditionalCameraData.cs.meta


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

12
Assets/ScriptableRenderPipeline/core/CommandBufferPool.cs.meta


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

72
Assets/ScriptableRenderPipeline/core/CommandBufferPool.cs


using System.Collections.Generic;
using UnityEngine.Events;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering
{
internal 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;
public int countAll { get; private set; }
public int countActive { get { return countAll - countInactive; } }
public int countInactive { get { return m_Stack.Count; } }
public ObjectPool(UnityAction<T> actionOnGet, UnityAction<T> actionOnRelease)
{
m_ActionOnGet = actionOnGet;
m_ActionOnRelease = actionOnRelease;
}
public T Get()
{
T element;
if (m_Stack.Count == 0)
{
element = new T();
countAll++;
}
else
{
element = m_Stack.Pop();
}
if (m_ActionOnGet != null)
m_ActionOnGet(element);
return element;
}
public void Release(T element)
{
if (m_Stack.Count > 0 && ReferenceEquals(m_Stack.Peek(), element))
Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
if (m_ActionOnRelease != null)
m_ActionOnRelease(element);
m_Stack.Push(element);
}
}
public static class CommandBufferPool
{
private static ObjectPool<CommandBuffer> m_BufferPool = new ObjectPool<CommandBuffer>(null, x => x.Clear());
public static CommandBuffer Get()
{
var cmd = m_BufferPool.Get();
cmd.name = "Unnamed Command Buffer";
return cmd;
}
public static CommandBuffer Get(string name)
{
var cmd = m_BufferPool.Get();
cmd.name = name;
return cmd;
}
public static void Release(CommandBuffer buffer)
{
m_BufferPool.Release(buffer);
}
}
}

9
Assets/LegacyLayered.meta


fileFormatVersion: 2
guid: 78d15b13b40de7a4891eb491afc04d28
folderAsset: yes
timeCreated: 1497255974
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存