From dc5f783fa332634ad1cb43b5cc6b954617fbc89f Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 26 Nov 2019 14:40:45 +0100 Subject: [PATCH 01/92] Fixed execution error without raytracing --- .../Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index 7f338182d07..71ccadc1129 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -224,14 +224,16 @@ bool RenderDepthPrepass(RenderGraph renderGraph, CullingResults cull, HDCamera h if (data.msaaEnabled) mrt[1] = context.resources.GetTexture(data.depthAsColorBuffer); + bool useRayTracing = passData.frameSettings.IsEnabled(FrameSettingsField.RayTracing); + RenderDepthPrepass(context.renderContext, context.cmd, data.frameSettings , mrt , context.resources.GetTexture(data.depthBuffer) , data.hasDepthOnlyPrepass ? context.resources.GetRendererList(data.rendererListDepthOnly) : RendererList.nullRendererList , context.resources.GetRendererList(data.rendererListMRT) , data.hasDepthOnlyPrepass - , context.resources.GetRendererList(data.renderListRayTracingOpaque) - , context.resources.GetRendererList(data.renderListRayTracingTransparent) + , useRayTracing ? context.resources.GetRendererList(data.renderListRayTracingOpaque) : new RendererList() + , useRayTracing ? context.resources.GetRendererList(data.renderListRayTracingTransparent) : new RendererList() ); }); } @@ -559,7 +561,7 @@ void RenderDecals(RenderGraph renderGraph, HDCamera hdCamera, ref PrepassOutput { passData.meshDecalsRendererList = builder.UseRendererList(renderGraph.CreateRendererList(PrepareMeshDecalsRendererList(cullingResults, hdCamera, use4RTs))); SetupDBufferTargets(renderGraph, passData, use4RTs, ref output, builder); - + builder.SetRenderFunc( (RenderDBufferPassData data, RenderGraphContext context) => { From 3d86f9e1f9ec4fa1a54a46d8dd0f466b663e7639 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 26 Nov 2019 17:52:37 +0100 Subject: [PATCH 02/92] Prepare Prepass refacto --- .../HDRenderPipeline.Prepass.cs | 36 ++++++++++++++++--- .../HDRenderPipeline.RenderGraphUtils.cs | 2 +- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index 71ccadc1129..1b33f307f2f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -70,7 +70,6 @@ struct PrepassOutput public RenderGraphMutableResource resolvedDepthBuffer; public RenderGraphMutableResource resolvedNormalBuffer; public RenderGraphMutableResource resolvedMotionVectorsBuffer; - public RenderGraphMutableResource resolvedStencilBuffer; // Copy of the resolved depth buffer with mip chain public RenderGraphMutableResource depthPyramidTexture; @@ -119,6 +118,17 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, RenderGraphMutableResource RenderOcclusionMeshes(renderGraph, hdCamera, result.depthBuffer); StartSinglePass(renderGraph, hdCamera); + // TODO RENDERGRAPH + //// Bind the custom color/depth before the first custom pass + //if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.CustomPass)) + //{ + // if (m_CustomPassColorBuffer.IsValueCreated) + // cmd.SetGlobalTexture(HDShaderIDs._CustomColorTexture, m_CustomPassColorBuffer.Value); + // if (m_CustomPassDepthBuffer.IsValueCreated) + // cmd.SetGlobalTexture(HDShaderIDs._CustomDepthTexture, m_CustomPassDepthBuffer.Value); + //} + //RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforeRendering); + bool renderMotionVectorAfterGBuffer = RenderDepthPrepass(renderGraph, cullingResults, hdCamera, ref result); if (!renderMotionVectorAfterGBuffer) @@ -128,7 +138,8 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, RenderGraphMutableResource RenderObjectsMotionVectors(renderGraph, cullingResults, hdCamera, result); } - ResolveStencilBufferIfNeeded(renderGraph, hdCamera, ref result); + // TODO RENDERGRAPH + //PreRenderSky(hdCamera, cmd); // At this point in forward all objects have been rendered to the prepass (depth/normal/motion vectors) so we can resolve them ResolvePrepassBuffers(renderGraph, hdCamera, ref result); @@ -137,9 +148,17 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, RenderGraphMutableResource RenderGBuffer(renderGraph, sssBuffer, ref result, cullingResults, hdCamera); + // TODO RENDERGRAPH + //// After Depth and Normals/roughness including decals + //RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterOpaqueDepthAndNormal); + // In both forward and deferred, everything opaque should have been rendered at this point so we can safely copy the depth buffer for later processing. GenerateDepthPyramid(renderGraph, hdCamera, ref result); + // TODO RENDERGRAPH + //// Send all the geometry graphics buffer to client systems if required (must be done after the pyramid and before the transparent depth pre-pass) + //SendGeometryGraphicsBuffers(cmd, hdCamera); + if (renderMotionVectorAfterGBuffer) { // See the call RenderObjectsMotionVectors() above and comment @@ -148,7 +167,10 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, RenderGraphMutableResource RenderCameraMotionVectors(renderGraph, hdCamera, result.depthPyramidTexture, result.resolvedMotionVectorsBuffer); - result.stencilBuffer = msaa ? result.resolvedStencilBuffer : result.depthBuffer; + // TODO RENDERGRAPH + //RenderTransparencyOverdraw(cullingResults, hdCamera, renderContext, cmd); + + ResolveStencilBufferIfNeeded(renderGraph, hdCamera, ref result); StopSinglePass(renderGraph, hdCamera); @@ -485,11 +507,15 @@ void ResolveStencilBufferIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, re context.cmd); } ); - - output.resolvedStencilBuffer = passData.outputStencil; + output.stencilBuffer = passData.outputStencil; } } + else + { + output.stencilBuffer = output.depthBuffer; + } } + class RenderDBufferPassData { public RenderGraphMutableResource[] mrt = new RenderGraphMutableResource[Decal.GetMaterialDBufferCount()]; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs index 4f5ade35afe..9d65e4b8e8d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs @@ -135,7 +135,7 @@ class RenderOcclusionMeshesPassData void RenderOcclusionMeshes(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource depthBuffer) { - if (hdCamera.xr.enabled && hdCamera.xr.xrSdkEnabled && m_Asset.currentPlatformRenderPipelineSettings.xrSettings.occlusionMesh) + if (hdCamera.xr.enabled && m_Asset.currentPlatformRenderPipelineSettings.xrSettings.occlusionMesh) { using (var builder = renderGraph.AddRenderPass("XR Occlusion Meshes", out var passData)) { From e91a1f0fa888a17a073fca682ff98d5564b66635 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 27 Nov 2019 12:04:25 +0100 Subject: [PATCH 03/92] Another round of preparation --- .../VolumetricLighting/VolumetricLighting.cs | 27 ++--- .../HDRenderPipeline.LightLoop.cs | 19 +++- .../HDRenderPipeline.Prepass.cs | 92 ++++++++--------- .../HDRenderPipeline.RenderGraph.cs | 98 +++++++++++++++---- .../HDRenderPipeline.RenderGraphUtils.cs | 46 ++++++++- .../RenderPipeline/HDRenderPipeline.cs | 18 ++-- 6 files changed, 207 insertions(+), 93 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 8cdf713dc8a..5c5d67094ea 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -796,14 +796,18 @@ static void VolumetricLightingPass( in VolumetricLightingParameters parameters, static void FilterVolumetricLighting(in VolumetricLightingParameters parameters, RTHandle outputBuffer, RTHandle inputBuffer, CommandBuffer cmd) { - // The shader defines GROUP_SIZE_1D = 8. - cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelX, HDShaderIDs._VBufferLightingFeedback, inputBuffer); // Read - cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelX, HDShaderIDs._VBufferLightingIntegral, outputBuffer); // Write - cmd.DispatchCompute(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelX, ((int)parameters.resolution.x + 7) / 8, ((int)parameters.resolution.y + 7) / 8, parameters.viewCount); + using (new ProfilingSample(cmd, "Volumetric Lighting Filtering")) + { + + // The shader defines GROUP_SIZE_1D = 8. + cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelX, HDShaderIDs._VBufferLightingFeedback, inputBuffer); // Read + cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelX, HDShaderIDs._VBufferLightingIntegral, outputBuffer); // Write + cmd.DispatchCompute(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelX, ((int)parameters.resolution.x + 7) / 8, ((int)parameters.resolution.y + 7) / 8, parameters.viewCount); - cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelY, HDShaderIDs._VBufferLightingFeedback, outputBuffer); // Read - cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelY, HDShaderIDs._VBufferLightingIntegral, inputBuffer); // Write - cmd.DispatchCompute(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelY, ((int)parameters.resolution.x + 7) / 8, ((int)parameters.resolution.y + 7) / 8, parameters.viewCount); + cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelY, HDShaderIDs._VBufferLightingFeedback, outputBuffer); // Read + cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelY, HDShaderIDs._VBufferLightingIntegral, inputBuffer); // Write + cmd.DispatchCompute(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelY, ((int)parameters.resolution.x + 7) / 8, ((int)parameters.resolution.y + 7) / 8, parameters.viewCount); + } } void VolumetricLightingPass(HDCamera hdCamera, CommandBuffer cmd, int frameIndex) @@ -827,12 +831,9 @@ void VolumetricLightingPass(HDCamera hdCamera, CommandBuffer cmd, int frameIndex hdCamera.volumetricHistoryIsValid = true; // For the next frame... } - using (new ProfilingSample(cmd, "Volumetric Lighting Filtering")) - { - // Let's filter out volumetric buffer - if (parameters.filterVolume) - FilterVolumetricLighting(parameters, m_DensityBufferHandle, m_LightingBufferHandle, cmd); - } + // Let's filter out volumetric buffer + if (parameters.filterVolume) + FilterVolumetricLighting(parameters, m_DensityBufferHandle, m_LightingBufferHandle, cmd); } } // class VolumetricLightingModule } // namespace UnityEngine.Rendering.HighDefinition diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 67f2650428e..f5b4ab66686 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -285,6 +285,16 @@ RenderGraphResource RenderSSR( RenderGraph renderGraph, return ssrBlackTexture; RenderGraphResource result; + + // TODO RENDERGRAPH + //var settings = VolumeManager.instance.stack.GetComponent(); + //if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value) + //{ + // hdCamera.xr.StartSinglePass(cmd, hdCamera.camera, renderContext); + // RenderRayTracedReflections(hdCamera, cmd, m_SsrLightingTexture, renderContext, m_FrameCount); + // hdCamera.xr.StopSinglePass(cmd, hdCamera.camera, renderContext); + //} + //else { using (var builder = renderGraph.AddRenderPass("Render SSR", out var passData)) { @@ -480,13 +490,18 @@ RenderGraphResource VolumetricLightingPass(RenderGraph renderGraph, HDCamera hdC builder.SetRenderFunc( (VolumetricLightingPassData data, RenderGraphContext ctx) => { + RTHandle densityBufferRT = ctx.resources.GetTexture(data.densityBuffer); + RTHandle lightinBufferRT = ctx.resources.GetTexture(data.lightingBuffer); VolumetricLightingPass( data.parameters, - ctx.resources.GetTexture(data.densityBuffer), - ctx.resources.GetTexture(data.lightingBuffer), + densityBufferRT, + lightinBufferRT, data.parameters.enableReprojection ? ctx.resources.GetTexture(data.historyBuffer) : null, data.parameters.enableReprojection ? ctx.resources.GetTexture(data.feedbackBuffer) : null, data.bigTileLightListBuffer, ctx.cmd); + + if (data.parameters.filterVolume) + FilterVolumetricLighting(data.parameters, densityBufferRT, lightinBufferRT, ctx.cmd); }); if (parameters.enableReprojection) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index 1b33f307f2f..275060421b0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -115,64 +115,64 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, RenderGraphMutableResource result.motionVectorsBuffer = CreateMotionVectorBuffer(renderGraph, msaa, clearMotionVectors); result.depthBuffer = CreateDepthBuffer(renderGraph, msaa); - RenderOcclusionMeshes(renderGraph, hdCamera, result.depthBuffer); - StartSinglePass(renderGraph, hdCamera); - - // TODO RENDERGRAPH - //// Bind the custom color/depth before the first custom pass - //if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.CustomPass)) - //{ - // if (m_CustomPassColorBuffer.IsValueCreated) - // cmd.SetGlobalTexture(HDShaderIDs._CustomColorTexture, m_CustomPassColorBuffer.Value); - // if (m_CustomPassDepthBuffer.IsValueCreated) - // cmd.SetGlobalTexture(HDShaderIDs._CustomDepthTexture, m_CustomPassDepthBuffer.Value); - //} - //RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforeRendering); - - bool renderMotionVectorAfterGBuffer = RenderDepthPrepass(renderGraph, cullingResults, hdCamera, ref result); - - if (!renderMotionVectorAfterGBuffer) - { - // If objects motion vectors are enabled, this will render the objects with motion vector into the target buffers (in addition to the depth) - // Note: An object with motion vector must not be render in the prepass otherwise we can have motion vector write that should have been rejected - RenderObjectsMotionVectors(renderGraph, cullingResults, hdCamera, result); - } + RenderXROcclusionMeshes(renderGraph, hdCamera, result.depthBuffer); - // TODO RENDERGRAPH - //PreRenderSky(hdCamera, cmd); + using (new XRPassScope(renderGraph, hdCamera)) + { + // TODO RENDERGRAPH + //// Bind the custom color/depth before the first custom pass + //if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.CustomPass)) + //{ + // if (m_CustomPassColorBuffer.IsValueCreated) + // cmd.SetGlobalTexture(HDShaderIDs._CustomColorTexture, m_CustomPassColorBuffer.Value); + // if (m_CustomPassDepthBuffer.IsValueCreated) + // cmd.SetGlobalTexture(HDShaderIDs._CustomDepthTexture, m_CustomPassDepthBuffer.Value); + //} + //RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforeRendering); + + bool renderMotionVectorAfterGBuffer = RenderDepthPrepass(renderGraph, cullingResults, hdCamera, ref result); + + if (!renderMotionVectorAfterGBuffer) + { + // If objects motion vectors are enabled, this will render the objects with motion vector into the target buffers (in addition to the depth) + // Note: An object with motion vector must not be render in the prepass otherwise we can have motion vector write that should have been rejected + RenderObjectsMotionVectors(renderGraph, cullingResults, hdCamera, result); + } - // At this point in forward all objects have been rendered to the prepass (depth/normal/motion vectors) so we can resolve them - ResolvePrepassBuffers(renderGraph, hdCamera, ref result); + // TODO RENDERGRAPH + //PreRenderSky(hdCamera, cmd); - RenderDecals(renderGraph, hdCamera, ref result, cullingResults); + // At this point in forward all objects have been rendered to the prepass (depth/normal/motion vectors) so we can resolve them + ResolvePrepassBuffers(renderGraph, hdCamera, ref result); - RenderGBuffer(renderGraph, sssBuffer, ref result, cullingResults, hdCamera); + RenderDecals(renderGraph, hdCamera, ref result, cullingResults); - // TODO RENDERGRAPH - //// After Depth and Normals/roughness including decals - //RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterOpaqueDepthAndNormal); + RenderGBuffer(renderGraph, sssBuffer, ref result, cullingResults, hdCamera); - // In both forward and deferred, everything opaque should have been rendered at this point so we can safely copy the depth buffer for later processing. - GenerateDepthPyramid(renderGraph, hdCamera, ref result); + // TODO RENDERGRAPH + //// After Depth and Normals/roughness including decals + //RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterOpaqueDepthAndNormal); - // TODO RENDERGRAPH - //// Send all the geometry graphics buffer to client systems if required (must be done after the pyramid and before the transparent depth pre-pass) - //SendGeometryGraphicsBuffers(cmd, hdCamera); + // In both forward and deferred, everything opaque should have been rendered at this point so we can safely copy the depth buffer for later processing. + GenerateDepthPyramid(renderGraph, hdCamera, ref result); - if (renderMotionVectorAfterGBuffer) - { - // See the call RenderObjectsMotionVectors() above and comment - RenderObjectsMotionVectors(renderGraph, cullingResults, hdCamera, result); - } + // TODO RENDERGRAPH + //// Send all the geometry graphics buffer to client systems if required (must be done after the pyramid and before the transparent depth pre-pass) + //SendGeometryGraphicsBuffers(cmd, hdCamera); - RenderCameraMotionVectors(renderGraph, hdCamera, result.depthPyramidTexture, result.resolvedMotionVectorsBuffer); + if (renderMotionVectorAfterGBuffer) + { + // See the call RenderObjectsMotionVectors() above and comment + RenderObjectsMotionVectors(renderGraph, cullingResults, hdCamera, result); + } - // TODO RENDERGRAPH - //RenderTransparencyOverdraw(cullingResults, hdCamera, renderContext, cmd); + RenderCameraMotionVectors(renderGraph, hdCamera, result.depthPyramidTexture, result.resolvedMotionVectorsBuffer); - ResolveStencilBufferIfNeeded(renderGraph, hdCamera, ref result); + // TODO RENDERGRAPH + //RenderTransparencyOverdraw(cullingResults, hdCamera, renderContext, cmd); - StopSinglePass(renderGraph, hdCamera); + ResolveStencilBufferIfNeeded(renderGraph, hdCamera, ref result); + } return result; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index 85d2c240144..e61d6acf96e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -10,7 +10,7 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, AOVRequestData aovRequest, List aovBuffers, ScriptableRenderContext renderContext, - CommandBuffer cmd) + CommandBuffer commandBuffer) { var hdCamera = renderRequest.hdCamera; var camera = hdCamera.camera; @@ -38,25 +38,30 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, if (m_CurrentDebugDisplaySettings.IsDebugMaterialDisplayEnabled() || m_CurrentDebugDisplaySettings.IsMaterialValidationEnabled() || CoreUtils.IsSceneLightingDisabled(hdCamera.camera)) { - StartSinglePass(m_RenderGraph, hdCamera); - RenderDebugViewMaterial(m_RenderGraph, cullingResults, hdCamera, colorBuffer); - colorBuffer = ResolveMSAAColor(m_RenderGraph, hdCamera, colorBuffer); - StopSinglePass(m_RenderGraph, hdCamera); + using (new XRPassScope(m_RenderGraph, hdCamera)) + { + RenderDebugViewMaterial(m_RenderGraph, cullingResults, hdCamera, colorBuffer); + colorBuffer = ResolveMSAAColor(m_RenderGraph, hdCamera, colorBuffer); + } + } + else if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && + VolumeManager.instance.stack.GetComponent().enable.value) + { + // TODO RENDERGRAPH + //// Update the light clusters that we need to update + //BuildRayTracingLightCluster(cmd, hdCamera); + + //// We only request the light cluster if we are gonna use it for debug mode + //if (FullScreenDebugMode.LightCluster == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode && GetRayTracingClusterState()) + //{ + // HDRaytracingLightCluster lightCluster = RequestLightCluster(); + // lightCluster.EvaluateClusterDebugView(cmd, hdCamera); + //} + + //RenderPathTracing(hdCamera, cmd, m_CameraColorBuffer, renderContext, m_FrameCount); } else { - if (m_RayTracingSupported) - { - // Update the light clusters that we need to update - BuildRayTracingLightCluster(cmd, hdCamera); - - if (FullScreenDebugMode.LightCluster == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode) - { - HDRaytracingLightCluster lightCluster = RequestLightCluster(); - lightCluster.EvaluateClusterDebugView(cmd, hdCamera); - } - } - BuildGPULightList(m_RenderGraph, hdCamera, prepassOutput.depthBuffer, prepassOutput.stencilBuffer, prepassOutput.gbuffer); lightingBuffers.ambientOcclusionBuffer = m_AmbientOcclusionSystem.Render(m_RenderGraph, hdCamera, prepassOutput.depthPyramidTexture, prepassOutput.motionVectorsBuffer, m_FrameCount); @@ -79,6 +84,34 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, shadowResult = RenderShadows(m_RenderGraph, hdCamera, cullingResults); + // TODO RENDERGRAPH + //if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) + //{ + // // Update the light clusters that we need to update + // BuildRayTracingLightCluster(cmd, hdCamera); + + // // We only request the light cluster if we are gonna use it for debug mode + // if (FullScreenDebugMode.LightCluster == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode && GetRayTracingClusterState()) + // { + // HDRaytracingLightCluster lightCluster = RequestLightCluster(); + // lightCluster.EvaluateClusterDebugView(cmd, hdCamera); + // } + + // bool validIndirectDiffuse = ValidIndirectDiffuseState(hdCamera); + // if (validIndirectDiffuse) + // { + // RenderIndirectDiffuse(hdCamera, cmd, renderContext, m_FrameCount); + // } + //} + + // TODO RENDERGRAPH + //using (new ProfilingSample(cmd, "Render screen space shadows", CustomSamplerId.ScreenSpaceShadows.GetSampler())) + //{ + // hdCamera.xr.StartSinglePass(cmd, camera, renderContext); + // RenderScreenSpaceShadows(hdCamera, cmd); + // hdCamera.xr.StopSinglePass(cmd, camera, renderContext); + //} + var volumetricLighting = VolumetricLightingPass(m_RenderGraph, hdCamera, volumetricDensityBuffer, m_TileAndClusterData.bigTileLightList, shadowResult, m_FrameCount); StartSinglePass(m_RenderGraph, hdCamera); @@ -87,6 +120,7 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, RenderForwardOpaque(m_RenderGraph, hdCamera, colorBuffer, lightingBuffers, prepassOutput.depthBuffer, shadowResult, prepassOutput.dbuffer, cullingResults); + // TODO RENDERGRAPH : Move this to the end after we do move semantic and graph pruning to avoid doing the rest of the frame for nothing aovRequest.PushCameraTexture(m_RenderGraph, AOVBuffers.Normals, hdCamera, prepassOutput.resolvedNormalBuffer, aovBuffers); lightingBuffers.diffuseLightingBuffer = ResolveMSAAColor(m_RenderGraph, hdCamera, lightingBuffers.diffuseLightingBuffer); @@ -98,8 +132,12 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, RenderSky(m_RenderGraph, hdCamera, colorBuffer, volumetricLighting, prepassOutput.depthBuffer, prepassOutput.depthPyramidTexture); + // TODO RENDERGRAPH + //m_PostProcessSystem.DoUserAfterOpaqueAndSky(cmd, hdCamera, m_CameraColorBuffer); + colorBuffer = RenderTransparency(m_RenderGraph, hdCamera, colorBuffer, prepassOutput.depthBuffer, prepassOutput.motionVectorsBuffer, currentColorPyramid, prepassOutput.depthPyramidTexture, shadowResult, cullingResults); + // TODO RENDERGRAPH : Move this to the end after we do move semantic and graph pruning to avoid doing the rest of the frame for nothing // Transparent objects may write to the depth and motion vectors buffers. aovRequest.PushCameraTexture(m_RenderGraph, AOVBuffers.DepthStencil, hdCamera, prepassOutput.resolvedDepthBuffer, aovBuffers); if (m_Asset.currentPlatformRenderPipelineSettings.supportMotionVectors) @@ -122,6 +160,9 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, // At this point, the color buffer has been filled by either debug views are regular rendering so we can push it here. var colorPickerTexture = PushColorPickerDebugTexture(m_RenderGraph, colorBuffer); + // TODO RENDERGRAPH + //RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforePostProcess); + aovRequest.PushCameraTexture(m_RenderGraph, AOVBuffers.Color, hdCamera, colorBuffer, aovBuffers); //RenderPostProcess(cullingResults, hdCamera, target.id, renderContext, cmd); @@ -157,9 +198,9 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, RenderGizmos(m_RenderGraph, hdCamera, colorBuffer, GizmoSubset.PostImageEffects); - ExecuteRenderGraph(m_RenderGraph, hdCamera, m_MSAASamples, renderContext, cmd); + ExecuteRenderGraph(m_RenderGraph, hdCamera, m_MSAASamples, renderContext, commandBuffer ); - aovRequest.Execute(cmd, aovBuffers, RenderOutputProperties.From(hdCamera)); + aovRequest.Execute(commandBuffer, aovBuffers, RenderOutputProperties.From(hdCamera)); } static void ExecuteRenderGraph(RenderGraph renderGraph, HDCamera hdCamera, MSAASamples msaaSample, ScriptableRenderContext renderContext, CommandBuffer cmd) @@ -585,6 +626,17 @@ RenderGraphMutableResource RenderTransparency( RenderGraph rend RenderTransparentDepthPrepass(renderGraph, hdCamera, depthStencilBuffer, cullingResults); + // TODO RENDERGRAPH + //if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) + //{ + // RaytracingRecursiveRender(hdCamera, cmd, renderContext, cullingResults); + //} + + // TODO RENDERGRAPH + // To allow users to fetch the current color buffer, we temporarily bind the camera color buffer + //cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, m_CameraColorBuffer); + //RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforePreRefraction); + // Render pre-refraction objects RenderForwardTransparent(renderGraph, hdCamera, colorBuffer, motionVectorsBuffer, depthStencilBuffer, null, shadowResult, cullingResults, true); @@ -594,6 +646,10 @@ RenderGraphMutableResource RenderTransparency( RenderGraph rend GenerateColorPyramid(renderGraph, hdCamera, resolvedColorBuffer, currentColorPyramid, true); } + // TODO RENDERGRAPH + // We don't have access to the color pyramid with transparent if rough refraction is disabled + //RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforeTransparent); + // Render all type of transparent forward (unlit, lit, complex (hair...)) to keep the sorting between transparent objects. RenderForwardTransparent(renderGraph, hdCamera, colorBuffer, motionVectorsBuffer, depthStencilBuffer, currentColorPyramid, shadowResult, cullingResults, false); @@ -684,6 +740,7 @@ class RenderSkyPassData public RenderGraphMutableResource intermediateBuffer; public DebugDisplaySettings debugDisplaySettings; public SkyManager skyManager; + public int frameCount; } void RenderSky(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource colorBuffer, RenderGraphResource volumetricLighting, RenderGraphMutableResource depthStencilBuffer, RenderGraphResource depthTexture) @@ -704,6 +761,7 @@ void RenderSky(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableRes passData.intermediateBuffer = builder.WriteTexture(renderGraph.CreateTexture(colorBuffer)); passData.debugDisplaySettings = m_CurrentDebugDisplaySettings; passData.skyManager = m_SkyManager; + passData.frameCount = m_FrameCount; builder.ReadTexture(depthTexture); @@ -718,7 +776,7 @@ void RenderSky(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableRes var intermediateBuffer = context.resources.GetTexture(data.intermediateBuffer); var inputVolumetric = context.resources.GetTexture(data.volumetricLighting); - data.skyManager.RenderSky(data.hdCamera, data.sunLight, destination, depthBuffer, data.debugDisplaySettings, m_FrameCount, context.cmd); + data.skyManager.RenderSky(data.hdCamera, data.sunLight, destination, depthBuffer, data.debugDisplaySettings, data.frameCount, context.cmd); if (Fog.IsFogEnabled(data.hdCamera) || Fog.IsPBRFogEnabled(data.hdCamera)) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs index 9d65e4b8e8d..af5df719361 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs @@ -62,6 +62,7 @@ Color GetColorBufferClearColor(HDCamera hdCamera) return clearColor; } + // XR Specific class XRRenderingPassData { @@ -69,7 +70,7 @@ class XRRenderingPassData public XRPass xr; } - void StartSinglePass(RenderGraph renderGraph, HDCamera hdCamera) + internal static void StartSinglePass(RenderGraph renderGraph, HDCamera hdCamera) { if (hdCamera.xr.enabled) { @@ -87,7 +88,7 @@ void StartSinglePass(RenderGraph renderGraph, HDCamera hdCamera) } } - void StopSinglePass(RenderGraph renderGraph, HDCamera hdCamera) + internal static void StopSinglePass(RenderGraph renderGraph, HDCamera hdCamera) { if (hdCamera.xr.enabled) { @@ -133,7 +134,7 @@ class RenderOcclusionMeshesPassData public RenderGraphMutableResource depthBuffer; } - void RenderOcclusionMeshes(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource depthBuffer) + void RenderXROcclusionMeshes(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource depthBuffer) { if (hdCamera.xr.enabled && m_Asset.currentPlatformRenderPipelineSettings.xrSettings.occlusionMesh) { @@ -151,4 +152,43 @@ void RenderOcclusionMeshes(RenderGraph renderGraph, HDCamera hdCamera, RenderGra } } } + + public struct XRPassScope : System.IDisposable + { + readonly RenderGraph m_RenderGraph; + readonly HDCamera m_HDCamera; + + bool m_Disposed; + + public XRPassScope(RenderGraph renderGraph, HDCamera hdCamera) + { + m_RenderGraph = renderGraph; + m_HDCamera = hdCamera; + m_Disposed = false; + + HDRenderPipeline.StartSinglePass(renderGraph, hdCamera); + } + + public void Dispose() + { + Dispose(true); + } + + // Protected implementation of Dispose pattern. + void Dispose(bool disposing) + { + if (m_Disposed) + return; + + // As this is a struct, it could have been initialized using an empty constructor so we + // need to make sure `cmd` isn't null to avoid a crash. Switching to a class would fix + // this but will generate garbage on every frame (and this struct is used quite a lot). + if (disposing) + { + HDRenderPipeline.StopSinglePass(m_RenderGraph, m_HDCamera); + } + + m_Disposed = true; + } + } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index da615de3797..41dadbb2a8c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -1996,17 +1996,17 @@ AOVRequestData aovRequest else if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && VolumeManager.instance.stack.GetComponent().enable.value) { - // Update the light clusters that we need to update - BuildRayTracingLightCluster(cmd, hdCamera); + // Update the light clusters that we need to update + BuildRayTracingLightCluster(cmd, hdCamera); - // We only request the light cluster if we are gonna use it for debug mode - if (FullScreenDebugMode.LightCluster == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode && GetRayTracingClusterState()) - { - HDRaytracingLightCluster lightCluster = RequestLightCluster(); - lightCluster.EvaluateClusterDebugView(cmd, hdCamera); - } + // We only request the light cluster if we are gonna use it for debug mode + if (FullScreenDebugMode.LightCluster == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode && GetRayTracingClusterState()) + { + HDRaytracingLightCluster lightCluster = RequestLightCluster(); + lightCluster.EvaluateClusterDebugView(cmd, hdCamera); + } - RenderPathTracing(hdCamera, cmd, m_CameraColorBuffer, renderContext, m_FrameCount); + RenderPathTracing(hdCamera, cmd, m_CameraColorBuffer, renderContext, m_FrameCount); } else { From 6f16b8abba7ec75987a613d5c631866e8f3b0977 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 27 Nov 2019 15:57:21 +0100 Subject: [PATCH 04/92] Renamed XRPassScope to XRSinglePassScope --- .../RenderPipeline/HDRenderPipeline.Prepass.cs | 2 +- .../RenderPipeline/HDRenderPipeline.RenderGraph.cs | 4 ++-- .../HDRenderPipeline.RenderGraphUtils.cs | 12 ++++++------ 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index 275060421b0..b9e40ccc419 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -117,7 +117,7 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, RenderGraphMutableResource RenderXROcclusionMeshes(renderGraph, hdCamera, result.depthBuffer); - using (new XRPassScope(renderGraph, hdCamera)) + using (new XRSinglePassScope(renderGraph, hdCamera)) { // TODO RENDERGRAPH //// Bind the custom color/depth before the first custom pass diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index e61d6acf96e..25d6a24c1d6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -38,7 +38,7 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, if (m_CurrentDebugDisplaySettings.IsDebugMaterialDisplayEnabled() || m_CurrentDebugDisplaySettings.IsMaterialValidationEnabled() || CoreUtils.IsSceneLightingDisabled(hdCamera.camera)) { - using (new XRPassScope(m_RenderGraph, hdCamera)) + using (new XRSinglePassScope(m_RenderGraph, hdCamera)) { RenderDebugViewMaterial(m_RenderGraph, cullingResults, hdCamera, colorBuffer); colorBuffer = ResolveMSAAColor(m_RenderGraph, hdCamera, colorBuffer); @@ -114,7 +114,7 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, var volumetricLighting = VolumetricLightingPass(m_RenderGraph, hdCamera, volumetricDensityBuffer, m_TileAndClusterData.bigTileLightList, shadowResult, m_FrameCount); - StartSinglePass(m_RenderGraph, hdCamera); + StartXRSinglePass(m_RenderGraph, hdCamera); var deferredLightingOutput = RenderDeferredLighting(m_RenderGraph, hdCamera, colorBuffer, prepassOutput.depthBuffer, prepassOutput.depthPyramidTexture, lightingBuffers, prepassOutput.gbuffer, shadowResult); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs index af5df719361..7b02ee06bdc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs @@ -70,7 +70,7 @@ class XRRenderingPassData public XRPass xr; } - internal static void StartSinglePass(RenderGraph renderGraph, HDCamera hdCamera) + internal static void StartXRSinglePass(RenderGraph renderGraph, HDCamera hdCamera) { if (hdCamera.xr.enabled) { @@ -88,7 +88,7 @@ internal static void StartSinglePass(RenderGraph renderGraph, HDCamera hdCamera) } } - internal static void StopSinglePass(RenderGraph renderGraph, HDCamera hdCamera) + internal static void StopXRSinglePass(RenderGraph renderGraph, HDCamera hdCamera) { if (hdCamera.xr.enabled) { @@ -153,20 +153,20 @@ void RenderXROcclusionMeshes(RenderGraph renderGraph, HDCamera hdCamera, RenderG } } - public struct XRPassScope : System.IDisposable + public struct XRSinglePassScope : System.IDisposable { readonly RenderGraph m_RenderGraph; readonly HDCamera m_HDCamera; bool m_Disposed; - public XRPassScope(RenderGraph renderGraph, HDCamera hdCamera) + public XRSinglePassScope(RenderGraph renderGraph, HDCamera hdCamera) { m_RenderGraph = renderGraph; m_HDCamera = hdCamera; m_Disposed = false; - HDRenderPipeline.StartSinglePass(renderGraph, hdCamera); + HDRenderPipeline.StartXRSinglePass(renderGraph, hdCamera); } public void Dispose() @@ -185,7 +185,7 @@ void Dispose(bool disposing) // this but will generate garbage on every frame (and this struct is used quite a lot). if (disposing) { - HDRenderPipeline.StopSinglePass(m_RenderGraph, m_HDCamera); + HDRenderPipeline.StopXRSinglePass(m_RenderGraph, m_HDCamera); } m_Disposed = true; From 13617b1b2c8aa9e53ab8b1f59553a040f706de9a Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 27 Nov 2019 17:16:41 +0100 Subject: [PATCH 05/92] RenderAfterPostProcess is now static --- .../RenderPipeline/HDRenderPipeline.cs | 92 +++++++++++++------ 1 file changed, 66 insertions(+), 26 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 41dadbb2a8c..ad4c11d5312 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -2285,7 +2285,9 @@ void Callback(CommandBuffer c, HDCamera cam) RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforePostProcess); aovRequest.PushCameraTexture(cmd, AOVBuffers.Color, hdCamera, m_CameraColorBuffer, aovBuffers); - RenderPostProcess(cullingResults, hdCamera, target.id, renderContext, cmd); + + RenderTargetIdentifier postProcessDest = HDUtils.PostProcessIsFinalPass() ? target.id : m_IntermediateAfterPostProcessBuffer; + RenderPostProcess(cullingResults, hdCamera, postProcessDest, renderContext, cmd); bool hasAfterPostProcessCustomPass = RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterPostProcess); @@ -2921,14 +2923,14 @@ DepthPrepassParameters PrepareDepthPrepass(CullingResults cull, HDCamera hdCamer return result; } - static void RenderDepthPrepass( ScriptableRenderContext renderContext, - CommandBuffer cmd, - FrameSettings frameSettings, - RenderTargetIdentifier[] mrt, - RTHandle depthBuffer, - in RendererList depthOnlyRendererList, - in RendererList mrtRendererList, - bool hasDepthOnlyPass, + static void RenderDepthPrepass( ScriptableRenderContext renderContext, + CommandBuffer cmd, + FrameSettings frameSettings, + RenderTargetIdentifier[] mrt, + RTHandle depthBuffer, + in RendererList depthOnlyRendererList, + in RendererList mrtRendererList, + bool hasDepthOnlyPass, in RendererList rayTracingOpaqueRL, in RendererList rayTracingTransparentRL ) @@ -4244,15 +4246,49 @@ void ClearBuffers(HDCamera hdCamera, CommandBuffer cmd) } } - void RenderPostProcess(CullingResults cullResults, HDCamera hdCamera, RenderTargetIdentifier finalRT, ScriptableRenderContext renderContext, CommandBuffer cmd) + struct PostProcessParameters + { + public HDCamera hdCamera; + public bool flipYInPostProcess; + public BlueNoise blueNoise; + + // After Postprocess + public float time; + public float lastTime; + public int frameCount; + public RendererListDesc opaqueAfterPPDesc; + public RendererListDesc transparentAfterPPDesc; + } + + PostProcessParameters PreparePostProcess(CullingResults cullResults, HDCamera hdCamera) { + PostProcessParameters result = new PostProcessParameters(); + result.hdCamera = hdCamera; // Y-Flip needs to happen during the post process pass only if it's the final pass and is the regular game view // SceneView flip is handled by the editor internal code and GameView rendering into render textures should not be flipped in order to respect Unity texture coordinates convention - bool flipInPostProcesses = HDUtils.PostProcessIsFinalPass() && (hdCamera.flipYMode == HDAdditionalCameraData.FlipYMode.ForceFlipY || hdCamera.isMainGameView); - RenderTargetIdentifier destination = HDUtils.PostProcessIsFinalPass() ? finalRT : m_IntermediateAfterPostProcessBuffer; + result.flipYInPostProcess = HDUtils.PostProcessIsFinalPass() && (hdCamera.flipYMode == HDAdditionalCameraData.FlipYMode.ForceFlipY || hdCamera.isMainGameView); + result.blueNoise = m_BlueNoise; + + result.time = m_Time; + result.lastTime = m_LastTime; + result.frameCount = m_FrameCount; + result.opaqueAfterPPDesc = CreateOpaqueRendererListDesc(cullResults, hdCamera.camera, HDShaderPassNames.s_ForwardOnlyName, renderQueueRange: HDRenderQueue.k_RenderQueue_AfterPostProcessOpaque); + result.transparentAfterPPDesc = CreateTransparentRendererListDesc(cullResults, hdCamera.camera, HDShaderPassNames.s_ForwardOnlyName, renderQueueRange: HDRenderQueue.k_RenderQueue_AfterPostProcessTransparent); + + return result; + } + + void RenderPostProcess(CullingResults cullResults, HDCamera hdCamera, RenderTargetIdentifier destination, ScriptableRenderContext renderContext, CommandBuffer cmd) + { + PostProcessParameters parameters = PreparePostProcess(cullResults, hdCamera); // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass - RenderAfterPostProcess(cullResults, hdCamera, renderContext, cmd); + RenderAfterPostProcess( parameters + , GetAfterPostProcessOffScreenBuffer() + , m_SharedRTManager.GetDepthStencilBuffer() + , RendererList.Create(parameters.opaqueAfterPPDesc) + , RendererList.Create(parameters.transparentAfterPPDesc) + , renderContext, cmd); // Set the depth buffer to the main one to avoid missing out on transparent depth for post process. cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); @@ -4261,19 +4297,20 @@ void RenderPostProcess(CullingResults cullResults, HDCamera hdCamera, RenderTarg m_PostProcessSystem.Render( cmd: cmd, camera: hdCamera, - blueNoise: m_BlueNoise, + blueNoise: parameters.blueNoise, colorBuffer: m_CameraColorBuffer, afterPostProcessTexture: GetAfterPostProcessOffScreenBuffer(), lightingBuffer: null, finalRT: destination, depthBuffer: m_SharedRTManager.GetDepthStencilBuffer(), - flipY: flipInPostProcesses + flipY: parameters.flipYInPostProcess ); } RTHandle GetAfterPostProcessOffScreenBuffer() { + // Here we share GBuffer albedo buffer since it's not needed anymore else we if (currentPlatformRenderPipelineSettings.supportedLitShaderMode == RenderPipelineSettings.SupportedLitShaderMode.ForwardOnly) return GetSSSBuffer(); else @@ -4281,8 +4318,14 @@ RTHandle GetAfterPostProcessOffScreenBuffer() } - void RenderAfterPostProcess(CullingResults cullResults, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd) + static void RenderAfterPostProcess( PostProcessParameters parameters, + RTHandle destination, + RTHandle depthStencilBuffer, + in RendererList opaqueAfterPostProcessRendererList, + in RendererList transparentAfterPostProcessRendererList, + ScriptableRenderContext renderContext, CommandBuffer cmd) { + var hdCamera = parameters.hdCamera; if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.AfterPostprocess)) return; @@ -4295,22 +4338,19 @@ void RenderAfterPostProcess(CullingResults cullResults, HDCamera hdCamera, Scrip // In order to avoid that we decide that objects rendered after Post processes while TAA is active will not benefit from the depth buffer so we disable it. bool taaEnabled = hdCamera.IsTAAEnabled(); hdCamera.UpdateAllViewConstants(false); - hdCamera.SetupGlobalParams(cmd, m_Time, m_LastTime, m_FrameCount); + hdCamera.SetupGlobalParams(cmd, parameters.time, parameters.lastTime, parameters.frameCount); + bool useDepthBuffer = !hdCamera.IsTAAEnabled() && hdCamera.frameSettings.IsEnabled(FrameSettingsField.ZTestAfterPostProcessTAA); - // Here we share GBuffer albedo buffer since it's not needed anymore // Note: We bind the depth only if the ZTest for After Post Process is enabled. It is disabled by // default so we're consistent in the behavior: no ZTest for After Post Process materials). - if (taaEnabled || !hdCamera.frameSettings.IsEnabled(FrameSettingsField.ZTestAfterPostProcessTAA)) - CoreUtils.SetRenderTarget(cmd, GetAfterPostProcessOffScreenBuffer(), clearFlag: ClearFlag.Color, clearColor: Color.black); + if (!useDepthBuffer) + CoreUtils.SetRenderTarget(cmd, destination, clearFlag: ClearFlag.Color, clearColor: Color.black); else - CoreUtils.SetRenderTarget(cmd, GetAfterPostProcessOffScreenBuffer(), m_SharedRTManager.GetDepthStencilBuffer(), clearFlag: ClearFlag.Color, clearColor: Color.black); + CoreUtils.SetRenderTarget(cmd, destination, depthStencilBuffer, clearFlag: ClearFlag.Color, clearColor: Color.black); cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 1); - var opaqueRendererList = RendererList.Create(CreateOpaqueRendererListDesc(cullResults, hdCamera.camera, HDShaderPassNames.s_ForwardOnlyName, renderQueueRange: HDRenderQueue.k_RenderQueue_AfterPostProcessOpaque)); - DrawOpaqueRendererList(renderContext, cmd, hdCamera.frameSettings, opaqueRendererList); - // Setup off-screen transparency here - var transparentRendererList = RendererList.Create(CreateTransparentRendererListDesc(cullResults, hdCamera.camera, HDShaderPassNames.s_ForwardOnlyName, renderQueueRange: HDRenderQueue.k_RenderQueue_AfterPostProcessTransparent)); - DrawTransparentRendererList(renderContext, cmd, hdCamera.frameSettings, transparentRendererList); + DrawOpaqueRendererList(renderContext, cmd, hdCamera.frameSettings, opaqueAfterPostProcessRendererList); + DrawTransparentRendererList(renderContext, cmd, hdCamera.frameSettings, transparentAfterPostProcessRendererList); cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 0); } } From 0e7152c5628eb2b72d8d2311032fe78d3c40bf19 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 27 Nov 2019 18:37:13 +0100 Subject: [PATCH 06/92] Add AfterPostProcess to RenderGraph (WIP) --- .../HDRenderPipeline.PostProcess.cs | 21 +++++++++++++++++ .../HDRenderPipeline.PostProcess.cs.meta | 11 +++++++++ .../HDRenderPipeline.RenderGraph.cs | 23 ++++++++++++++++++- 3 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs create mode 100644 com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs.meta diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs new file mode 100644 index 00000000000..f5fea6e523c --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs @@ -0,0 +1,21 @@ +using UnityEngine.Experimental.Rendering; +using UnityEngine.Experimental.Rendering.RenderGraphModule; + +namespace UnityEngine.Rendering.HighDefinition +{ + public partial class HDRenderPipeline + { + void RenderPostProcess() + { + PostProcessParameters parameters = PreparePostProcess(cullResults, hdCamera); + + // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass + RenderAfterPostProcess( parameters + , GetAfterPostProcessOffScreenBuffer() + , m_SharedRTManager.GetDepthStencilBuffer() + , RendererList.Create(parameters.opaqueAfterPPDesc) + , RendererList.Create(parameters.transparentAfterPPDesc) + , renderContext, cmd); + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs.meta b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs.meta new file mode 100644 index 00000000000..b78c26695bf --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0e175827f449a9f4a8395f10e2b02f7f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index 25d6a24c1d6..6ca73746bca 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -165,7 +165,28 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, aovRequest.PushCameraTexture(m_RenderGraph, AOVBuffers.Color, hdCamera, colorBuffer, aovBuffers); - //RenderPostProcess(cullingResults, hdCamera, target.id, renderContext, cmd); + RenderPostProcess(m_RenderGraph, cullingResults, hdCamera, target.id); + + bool hasAfterPostProcessCustomPass = RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterPostProcess); + + // TODO RENDERGRAPH + //// Copy and rescale depth buffer for XR devices + //if (hdCamera.xr.enabled && hdCamera.xr.copyDepth) + //{ + // using (new ProfilingSample(cmd, "XR depth copy")) + // { + // var depthBuffer = m_SharedRTManager.GetDepthStencilBuffer(); + // var rtScale = depthBuffer.rtHandleProperties.rtHandleScale / DynamicResolutionHandler.instance.GetCurrentScale(); + + // m_CopyDepthPropertyBlock.SetTexture(HDShaderIDs._InputDepth, depthBuffer); + // m_CopyDepthPropertyBlock.SetVector(HDShaderIDs._BlitScaleBias, rtScale); + // m_CopyDepthPropertyBlock.SetInt("_FlipY", 1); + + // cmd.SetRenderTarget(target.id, 0, CubemapFace.Unknown, -1); + // cmd.SetViewport(hdCamera.finalViewport); + // CoreUtils.DrawFullScreen(cmd, m_CopyDepth, m_CopyDepthPropertyBlock); + // } + //} // In developer build, we always render post process in m_AfterPostProcessBuffer at (0,0) in which we will then render debug. // Because of this, we need another blit here to the final render target at the right viewport. From f81dd5b17bc7253895c6358102840a5362eb45e7 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 28 Nov 2019 10:56:15 +0100 Subject: [PATCH 07/92] AfterPostProcess implementation --- .../HDRenderPipeline.PostProcess.cs | 39 +++++++++++++++---- .../HDRenderPipeline.RenderGraph.cs | 7 ++-- .../RenderPipeline/HDRenderPipeline.cs | 22 +++++------ 3 files changed, 45 insertions(+), 23 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs index f5fea6e523c..1a78e39351d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs @@ -5,17 +5,40 @@ namespace UnityEngine.Rendering.HighDefinition { public partial class HDRenderPipeline { - void RenderPostProcess() + class AfterPostProcessPassData { - PostProcessParameters parameters = PreparePostProcess(cullResults, hdCamera); + public PostProcessParameters parameters; + public RenderGraphMutableResource afterPostProcessBuffer; + public RenderGraphMutableResource depthStencilBuffer; + public RenderGraphResource opaqueAfterPostprocessRL; + public RenderGraphResource transparentAfterPostprocessRL; + } + + void RenderPostProcess(RenderGraph renderGraph, RenderGraphMutableResource depthBuffer, CullingResults cullResults, HDCamera hdCamera) + { + m_SSSColor = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R8G8B8A8_SRGB, dimension: TextureXR.dimension, useDynamicScale: true, name: "SSSBuffer"); // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass - RenderAfterPostProcess( parameters - , GetAfterPostProcessOffScreenBuffer() - , m_SharedRTManager.GetDepthStencilBuffer() - , RendererList.Create(parameters.opaqueAfterPPDesc) - , RendererList.Create(parameters.transparentAfterPPDesc) - , renderContext, cmd); + using (var builder = renderGraph.AddRenderPass("AfterPostProcess", out var passData, CustomSamplerId.GBuffer.GetSampler())) + { + passData.parameters = PreparePostProcess(cullResults, hdCamera); + passData.afterPostProcessBuffer = builder.UseColorBuffer(renderGraph.CreateTexture( + new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R8G8B8A8_SRGB, clearBuffer = true, clearColor = Color.black, name = "OffScreen AfterPostProcess" }), 0); + if (passData.parameters.useDepthBuffer) + passData.depthStencilBuffer = builder.UseDepthBuffer(depthBuffer, DepthAccess.ReadWrite); + passData.opaqueAfterPostprocessRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.opaqueAfterPPDesc)); + passData.transparentAfterPostprocessRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.transparentAfterPPDesc)); + + builder.SetRenderFunc( + (AfterPostProcessPassData data, RenderGraphContext ctx) => + { + RenderAfterPostProcess( data.parameters + , ctx.resources.GetRendererList(data.opaqueAfterPostprocessRL) + , ctx.resources.GetRendererList(data.transparentAfterPostprocessRL) + , ctx.renderContext, ctx.cmd); + + }); + } } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index 6ca73746bca..69e75c15560 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -165,9 +165,10 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, aovRequest.PushCameraTexture(m_RenderGraph, AOVBuffers.Color, hdCamera, colorBuffer, aovBuffers); - RenderPostProcess(m_RenderGraph, cullingResults, hdCamera, target.id); + RenderPostProcess(m_RenderGraph, prepassOutput.depthBuffer, cullingResults, hdCamera); - bool hasAfterPostProcessCustomPass = RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterPostProcess); + // TODO RENDERGRAPH + //bool hasAfterPostProcessCustomPass = RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterPostProcess); // TODO RENDERGRAPH //// Copy and rescale depth buffer for XR devices @@ -190,7 +191,7 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, // In developer build, we always render post process in m_AfterPostProcessBuffer at (0,0) in which we will then render debug. // Because of this, we need another blit here to the final render target at the right viewport. - //if (!HDUtils.PostProcessIsFinalPass() || aovRequest.isValid) + //if (!HDUtils.PostProcessIsFinalPass() || aovRequest.isValid || hasAfterPostProcessCustomPass) { hdCamera.ExecuteCaptureActions(m_RenderGraph, colorBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index ddc9bb5a05b..226d88863bd 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -4254,6 +4254,7 @@ struct PostProcessParameters public BlueNoise blueNoise; // After Postprocess + public bool useDepthBuffer; public float time; public float lastTime; public int frameCount; @@ -4270,6 +4271,7 @@ PostProcessParameters PreparePostProcess(CullingResults cullResults, HDCamera hd result.flipYInPostProcess = HDUtils.PostProcessIsFinalPass() && (hdCamera.flipYMode == HDAdditionalCameraData.FlipYMode.ForceFlipY || hdCamera.isMainGameView); result.blueNoise = m_BlueNoise; + result.useDepthBuffer = !hdCamera.IsTAAEnabled() && hdCamera.frameSettings.IsEnabled(FrameSettingsField.ZTestAfterPostProcessTAA); result.time = m_Time; result.lastTime = m_LastTime; result.frameCount = m_FrameCount; @@ -4283,10 +4285,16 @@ void RenderPostProcess(CullingResults cullResults, HDCamera hdCamera, RenderTarg { PostProcessParameters parameters = PreparePostProcess(cullResults, hdCamera); + // Note: We bind the depth only if the ZTest for After Post Process is enabled. It is disabled by + // default so we're consistent in the behavior: no ZTest for After Post Process materials). + if (!parameters.useDepthBuffer) + CoreUtils.SetRenderTarget(cmd, GetAfterPostProcessOffScreenBuffer(), clearFlag: ClearFlag.Color, clearColor: Color.black); + else + CoreUtils.SetRenderTarget(cmd, GetAfterPostProcessOffScreenBuffer(), m_SharedRTManager.GetDepthStencilBuffer(), clearFlag: ClearFlag.Color, clearColor: Color.black); + + // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass RenderAfterPostProcess( parameters - , GetAfterPostProcessOffScreenBuffer() - , m_SharedRTManager.GetDepthStencilBuffer() , RendererList.Create(parameters.opaqueAfterPPDesc) , RendererList.Create(parameters.transparentAfterPPDesc) , renderContext, cmd); @@ -4320,8 +4328,6 @@ RTHandle GetAfterPostProcessOffScreenBuffer() static void RenderAfterPostProcess( PostProcessParameters parameters, - RTHandle destination, - RTHandle depthStencilBuffer, in RendererList opaqueAfterPostProcessRendererList, in RendererList transparentAfterPostProcessRendererList, ScriptableRenderContext renderContext, CommandBuffer cmd) @@ -4340,14 +4346,6 @@ static void RenderAfterPostProcess( PostProcessParameters parameters, bool taaEnabled = hdCamera.IsTAAEnabled(); hdCamera.UpdateAllViewConstants(false); hdCamera.SetupGlobalParams(cmd, parameters.time, parameters.lastTime, parameters.frameCount); - bool useDepthBuffer = !hdCamera.IsTAAEnabled() && hdCamera.frameSettings.IsEnabled(FrameSettingsField.ZTestAfterPostProcessTAA); - - // Note: We bind the depth only if the ZTest for After Post Process is enabled. It is disabled by - // default so we're consistent in the behavior: no ZTest for After Post Process materials). - if (!useDepthBuffer) - CoreUtils.SetRenderTarget(cmd, destination, clearFlag: ClearFlag.Color, clearColor: Color.black); - else - CoreUtils.SetRenderTarget(cmd, destination, depthStencilBuffer, clearFlag: ClearFlag.Color, clearColor: Color.black); cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 1); DrawOpaqueRendererList(renderContext, cmd, hdCamera.frameSettings, opaqueAfterPostProcessRendererList); From d36bccf34456d11543b6b4a59423bab49ff085f9 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 28 Nov 2019 11:16:29 +0100 Subject: [PATCH 08/92] Fixed wrong RTHandle allocation --- .../Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs index 1a78e39351d..d69265c7b34 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs @@ -16,8 +16,6 @@ class AfterPostProcessPassData void RenderPostProcess(RenderGraph renderGraph, RenderGraphMutableResource depthBuffer, CullingResults cullResults, HDCamera hdCamera) { - m_SSSColor = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R8G8B8A8_SRGB, dimension: TextureXR.dimension, useDynamicScale: true, name: "SSSBuffer"); - // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass using (var builder = renderGraph.AddRenderPass("AfterPostProcess", out var passData, CustomSamplerId.GBuffer.GetSampler())) { From dd614e63c639630ddbcffc497be06872efd3f85e Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 28 Nov 2019 11:16:49 +0100 Subject: [PATCH 09/92] Fixed light layers texture binding during deferred lighting pass --- .../Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs | 8 ++++++++ .../Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs | 4 +++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index f5b4ab66686..615a4200449 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -175,6 +175,7 @@ class DeferredLightingPassData public RenderGraphResource depthTexture; public int gbufferCount; + public int lightLayersTextureIndex; public RenderGraphResource[] gbuffer = new RenderGraphResource[8]; } @@ -216,6 +217,7 @@ LightingOutput RenderDeferredLighting( RenderGraph renderGraph, ReadLightingBuffers(lightingBuffers, builder); + passData.lightLayersTextureIndex = gbuffer.lightLayersTextureIndex; passData.gbufferCount = gbuffer.gBufferCount; for (int i = 0; i < gbuffer.gBufferCount; ++i) passData.gbuffer[i] = builder.ReadTexture(gbuffer.mrt[i]); @@ -238,9 +240,15 @@ LightingOutput RenderDeferredLighting( RenderGraph renderGraph, // TODO: try to find a better way to bind this. // Issue is that some GBuffers have several names (for example normal buffer is both NormalBuffer and GBuffer1) // So it's not possible to use auto binding via dependency to shaderTagID + // Should probably get rid of auto binding and go explicit all the way (might need to wait for us to remove non rendergraph code path). for (int i = 0; i < data.gbufferCount; ++i) context.cmd.SetGlobalTexture(HDShaderIDs._GBufferTexture[i], context.resources.GetTexture(data.gbuffer[i])); + if (data.lightLayersTextureIndex != -1) + context.cmd.SetGlobalTexture(HDShaderIDs._LightLayersTexture, context.resources.GetTexture(data.gbuffer[data.lightLayersTextureIndex])); + else + context.cmd.SetGlobalTexture(HDShaderIDs._LightLayersTexture, TextureXR.GetWhiteTexture()); + if (data.parameters.enableTile) { bool useCompute = data.parameters.useComputeLightingEvaluation && !k_PreferFragment; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index b9e40ccc419..7254a50040a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -316,6 +316,7 @@ struct GBufferOutput { public RenderGraphResource[] mrt; public int gBufferCount; + public int lightLayersTextureIndex; } void SetupGBufferTargets(RenderGraph renderGraph, HDCamera hdCamera, GBufferPassData passData, RenderGraphMutableResource sssBuffer, ref PrepassOutput prepassOutput, FrameSettings frameSettings, RenderGraphBuilder builder) @@ -334,12 +335,13 @@ void SetupGBufferTargets(RenderGraph renderGraph, HDCamera hdCamera, GBufferPass passData.gbufferRT[3] = builder.UseColorBuffer(renderGraph.CreateTexture( new TextureDesc(Vector2.one, true, true) { colorFormat = Builtin.GetLightingBufferFormat(), clearBuffer = clearGBuffer, clearColor = Color.clear, name = "GBuffer3" }, HDShaderIDs._GBufferTexture[3]), 3); + prepassOutput.gbuffer.lightLayersTextureIndex = -1; int currentIndex = 4; if (lightLayers) { passData.gbufferRT[currentIndex] = builder.UseColorBuffer(renderGraph.CreateTexture( new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, clearBuffer = clearGBuffer, clearColor = Color.clear, name = "LightLayers" }, HDShaderIDs._LightLayersTexture), currentIndex); - currentIndex++; + prepassOutput.gbuffer.lightLayersTextureIndex = currentIndex++; } if (shadowMasks) { From 7bcda4546c7ff72f2d6c41a5d8b4ea73f5a6bb41 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 28 Nov 2019 18:04:22 +0100 Subject: [PATCH 10/92] Implemented Post Process Final Pass with RenderGraph --- .../Runtime/RenderGraph/RenderGraph.cs | 5 + .../RenderGraphResourceRegistry.cs | 14 + .../Runtime/Textures/RTHandle.cs | 7 + .../Runtime/Textures/RTHandleSystem.cs | 12 + .../Runtime/Textures/RTHandles.cs | 5 + .../PostProcessSystem.RenderGraph.cs | 267 ++++++++++++++++++ .../PostProcessSystem.RenderGraph.cs.meta | 11 + .../PostProcessing/PostProcessSystem.cs | 148 ++++++---- .../HDRenderPipeline.PostProcess.cs | 65 +++-- .../HDRenderPipeline.RenderGraph.cs | 35 +-- .../RenderPipeline/HDRenderPipeline.cs | 61 ++-- 11 files changed, 513 insertions(+), 117 deletions(-) create mode 100644 com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs create mode 100644 com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs.meta diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs index c6a26aacaee..cbc176e81ee 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs @@ -233,6 +233,11 @@ public RenderGraphMutableResource ImportTexture(RTHandle rt, int shaderProperty return m_Resources.ImportTexture(rt, shaderProperty); } + public RenderGraphMutableResource ImportBackbuffer(RenderTargetIdentifier rt) + { + return m_Resources.ImportBackbuffer(rt); + } + /// /// Create a new Render Graph Texture resource. /// diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs index 15c4d21c8e0..a5ca8d45353 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs @@ -240,6 +240,7 @@ internal RendererListResource(in RendererListDesc desc) } } #endregion + DynamicArray m_TextureResources = new DynamicArray(); Dictionary> m_TexturePool = new Dictionary>(); DynamicArray m_RendererListResources = new DynamicArray(); @@ -247,6 +248,8 @@ internal RendererListResource(in RendererListDesc desc) RenderGraphDebugParams m_RenderGraphDebug; RenderGraphLogger m_Logger; + RTHandle m_CurrentBackbuffer; + // Diagnostic only List<(int, RTHandle)> m_AllocatedTextures = new List<(int, RTHandle)>(); @@ -315,6 +318,17 @@ internal RenderGraphMutableResource ImportTexture(RTHandle rt, int shaderPropert return new RenderGraphMutableResource(newHandle, RenderGraphResourceType.Texture); } + internal RenderGraphMutableResource ImportBackbuffer(RenderTargetIdentifier rt) + { + if (m_CurrentBackbuffer != null) + m_RTHandleSystem.Release(m_CurrentBackbuffer); + + m_CurrentBackbuffer = m_RTHandleSystem.Alloc(rt); + + int newHandle = m_TextureResources.Add(new TextureResource(m_CurrentBackbuffer, 0)); + return new RenderGraphMutableResource(newHandle, RenderGraphResourceType.Texture); + } + internal RenderGraphMutableResource CreateTexture(in TextureDesc desc, int shaderProperty = 0) { ValidateTextureDesc(desc); diff --git a/com.unity.render-pipelines.core/Runtime/Textures/RTHandle.cs b/com.unity.render-pipelines.core/Runtime/Textures/RTHandle.cs index 9b8a18c14a5..7b66cd5e94b 100644 --- a/com.unity.render-pipelines.core/Runtime/Textures/RTHandle.cs +++ b/com.unity.render-pipelines.core/Runtime/Textures/RTHandle.cs @@ -65,6 +65,13 @@ internal void SetTexture(Texture tex) m_NameID = new RenderTargetIdentifier(tex); } + internal void SetTexture(RenderTargetIdentifier tex) + { + m_RT = null; + m_ExternalTexture = null; + m_NameID = tex; + } + public void Release() { m_Owner.Remove(this); diff --git a/com.unity.render-pipelines.core/Runtime/Textures/RTHandleSystem.cs b/com.unity.render-pipelines.core/Runtime/Textures/RTHandleSystem.cs index bffedde8490..56416832819 100644 --- a/com.unity.render-pipelines.core/Runtime/Textures/RTHandleSystem.cs +++ b/com.unity.render-pipelines.core/Runtime/Textures/RTHandleSystem.cs @@ -623,6 +623,18 @@ public RTHandle Alloc(Texture texture) return rth; } + public RTHandle Alloc(RenderTargetIdentifier texture) + { + var rth = new RTHandle(this); + rth.SetTexture(texture); + rth.m_EnableMSAA = false; + rth.m_EnableRandomWrite = false; + rth.useScaling = false; + rth.m_EnableHWDynamicScale = false; + rth.m_Name = ""; + return rth; + } + public static RTHandle Alloc(RTHandle tex) { Debug.LogError("Allocation a RTHandle from another one is forbidden."); diff --git a/com.unity.render-pipelines.core/Runtime/Textures/RTHandles.cs b/com.unity.render-pipelines.core/Runtime/Textures/RTHandles.cs index 23467fa9f9d..295486052fc 100644 --- a/com.unity.render-pipelines.core/Runtime/Textures/RTHandles.cs +++ b/com.unity.render-pipelines.core/Runtime/Textures/RTHandles.cs @@ -147,6 +147,11 @@ public static RTHandle Alloc(Texture tex) return s_DefaultInstance.Alloc(tex); } + public static RTHandle Alloc(RenderTargetIdentifier tex) + { + return s_DefaultInstance.Alloc(tex); + } + public static RTHandle Alloc(RTHandle tex) { Debug.LogError("Allocation a RTHandle from another one is forbidden."); diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs new file mode 100644 index 00000000000..98811e346fd --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs @@ -0,0 +1,267 @@ +using UnityEngine.Experimental.Rendering; +using UnityEngine.Experimental.Rendering.RenderGraphModule; + +namespace UnityEngine.Rendering.HighDefinition +{ + partial class PostProcessSystem + { + public void Render( RenderGraph renderGraph, + HDCamera hdCamera, + BlueNoise blueNoise, + RenderGraphResource colorBuffer, + RenderGraphResource afterPostProcessTexture, + RenderGraphMutableResource depthBuffer, + RenderGraphMutableResource finalRT, + bool flipY) + { + var dynResHandler = DynamicResolutionHandler.instance; + + bool isSceneView = hdCamera.camera.cameraType == CameraType.SceneView; + + // TODO: Implement + RenderGraphResource alphaTexture = new RenderGraphResource(); + //// Save the alpha and apply it back into the final pass if working in fp16 + //if (m_KeepAlpha) + //{ + // using (new ProfilingSample(cmd, "Alpha Copy", CustomSamplerId.AlphaCopy.GetSampler())) + // { + // DoCopyAlpha(cmd, hdCamera, colorBuffer); + // } + //} + + var source = colorBuffer; + + //if (m_PostProcessEnabled) + //{ + // Guard bands (also known as "horrible hack") to avoid bleeding previous RTHandle + // content into smaller viewports with some effects like Bloom that rely on bilinear + // filtering and can't use clamp sampler and the likes + // Note: some platforms can't clear a partial render target so we directly draw black triangles + //{ + // int w = hdCamera.actualWidth; + // int h = hdCamera.actualHeight; + // cmd.SetRenderTarget(source, 0, CubemapFace.Unknown, -1); + + // if (w < source.rt.width || h < source.rt.height) + // { + // cmd.SetViewport(new Rect(w, 0, k_RTGuardBandSize, h)); + // cmd.DrawProcedural(Matrix4x4.identity, m_ClearBlackMaterial, 0, MeshTopology.Triangles, 3, 1); + // cmd.SetViewport(new Rect(0, h, w + k_RTGuardBandSize, k_RTGuardBandSize)); + // cmd.DrawProcedural(Matrix4x4.identity, m_ClearBlackMaterial, 0, MeshTopology.Triangles, 3, 1); + // } + //} + +// // Optional NaN killer before post-processing kicks in +// bool stopNaNs = hdCamera.stopNaNs && m_StopNaNFS; + +//#if UNITY_EDITOR +// if (isSceneView) +// stopNaNs = HDRenderPipelinePreferences.sceneViewStopNaNs; +//#endif + +// if (stopNaNs) +// { +// using (new ProfilingSample(cmd, "Stop NaNs", CustomSamplerId.StopNaNs.GetSampler())) +// { +// var destination = m_Pool.Get(Vector2.one, k_ColorFormat); +// DoStopNaNs(cmd, hdCamera, source, destination); +// PoolSource(ref source, destination); +// } +// } + //} + + //// Dynamic exposure - will be applied in the next frame + //// Not considered as a post-process so it's not affected by its enabled state + //if (!IsExposureFixed() && m_ExposureControlFS) + //{ + // using (new ProfilingSample(cmd, "Dynamic Exposure", CustomSamplerId.Exposure.GetSampler())) + // { + // DoDynamicExposure(cmd, hdCamera, source); + // } + //} + + //if (m_PostProcessEnabled) + //{ + // // Temporal anti-aliasing goes first + // bool taaEnabled = false; + + // if (m_AntialiasingFS) + // { + // taaEnabled = hdCamera.antialiasing == AntialiasingMode.TemporalAntialiasing; + + // if (taaEnabled) + // { + // using (new ProfilingSample(cmd, "Temporal Anti-aliasing", CustomSamplerId.TemporalAntialiasing.GetSampler())) + // { + // var destination = m_Pool.Get(Vector2.one, k_ColorFormat); + // DoTemporalAntialiasing(cmd, hdCamera, source, destination, depthBuffer); + // PoolSource(ref source, destination); + // } + // } + // else if (hdCamera.antialiasing == AntialiasingMode.SubpixelMorphologicalAntiAliasing) + // { + // using (new ProfilingSample(cmd, "SMAA", CustomSamplerId.SMAA.GetSampler())) + // { + // var destination = m_Pool.Get(Vector2.one, k_ColorFormat); + // DoSMAA(cmd, hdCamera, source, destination, depthBuffer); + // PoolSource(ref source, destination); + // } + // } + // } + + // if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.CustomPostProcess)) + // { + // using (new ProfilingSample(cmd, "Custom Post Processes Before PP", CustomSamplerId.CustomPostProcessBeforePP.GetSampler())) + // { + // foreach (var typeString in HDRenderPipeline.currentAsset.beforePostProcessCustomPostProcesses) + // RenderCustomPostProcess(cmd, hdCamera, ref source, colorBuffer, Type.GetType(typeString)); + // } + // } + + // // Depth of Field is done right after TAA as it's easier to just re-project the CoC + // // map rather than having to deal with all the implications of doing it before TAA + // if (m_DepthOfField.IsActive() && !isSceneView && m_DepthOfFieldFS) + // { + // using (new ProfilingSample(cmd, "Depth of Field", CustomSamplerId.DepthOfField.GetSampler())) + // { + // var destination = m_Pool.Get(Vector2.one, k_ColorFormat); + // DoDepthOfField(cmd, hdCamera, source, destination, taaEnabled); + // PoolSource(ref source, destination); + // } + // } + + // // Motion blur after depth of field for aesthetic reasons (better to see motion + // // blurred bokeh rather than out of focus motion blur) + // if (m_MotionBlur.IsActive() && m_AnimatedMaterialsEnabled && !m_ResetHistory && m_MotionBlurFS) + // { + // using (new ProfilingSample(cmd, "Motion Blur", CustomSamplerId.MotionBlur.GetSampler())) + // { + // var destination = m_Pool.Get(Vector2.one, k_ColorFormat); + // DoMotionBlur(cmd, hdCamera, source, destination); + // PoolSource(ref source, destination); + // } + // } + + // // Panini projection is done as a fullscreen pass after all depth-based effects are + // // done and before bloom kicks in + // // This is one effect that would benefit from an overscan mode or supersampling in + // // HDRP to reduce the amount of resolution lost at the center of the screen + // if (m_PaniniProjection.IsActive() && !isSceneView && m_PaniniProjectionFS) + // { + // using (new ProfilingSample(cmd, "Panini Projection", CustomSamplerId.PaniniProjection.GetSampler())) + // { + // var destination = m_Pool.Get(Vector2.one, k_ColorFormat); + // DoPaniniProjection(cmd, hdCamera, source, destination); + // PoolSource(ref source, destination); + // } + // } + + // // Combined post-processing stack - always runs if postfx is enabled + // using (new ProfilingSample(cmd, "Uber", CustomSamplerId.UberPost.GetSampler())) + // { + // // Feature flags are passed to all effects and it's their responsibility to check + // // if they are used or not so they can set default values if needed + // var cs = m_Resources.shaders.uberPostCS; + // var featureFlags = GetUberFeatureFlags(isSceneView); + // int kernel = GetUberKernel(cs, featureFlags); + + // // Generate the bloom texture + // bool bloomActive = m_Bloom.IsActive() && m_BloomFS; + + // if (bloomActive) + // { + // using (new ProfilingSample(cmd, "Bloom", CustomSamplerId.Bloom.GetSampler())) + // { + // DoBloom(cmd, hdCamera, source, cs, kernel); + // } + // } + // else + // { + // cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._BloomTexture, TextureXR.GetBlackTexture()); + // cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._BloomDirtTexture, Texture2D.blackTexture); + // cmd.SetComputeVectorParam(cs, HDShaderIDs._BloomParams, Vector4.zero); + // } + + // // Build the color grading lut + // using (new ProfilingSample(cmd, "Color Grading LUT Builder", CustomSamplerId.ColorGradingLUTBuilder.GetSampler())) + // { + // DoColorGrading(cmd, cs, kernel); + // } + + // // Setup the rest of the effects + // DoLensDistortion(cmd, cs, kernel, featureFlags); + // DoChromaticAberration(cmd, cs, kernel, featureFlags); + // DoVignette(cmd, cs, kernel, featureFlags); + + // // Run + // var destination = m_Pool.Get(Vector2.one, k_ColorFormat); + + // bool outputColorLog = m_HDInstance.m_CurrentDebugDisplaySettings.data.fullScreenDebugMode == FullScreenDebugMode.ColorLog; + // cmd.SetComputeVectorParam(cs, "_DebugFlags", new Vector4(outputColorLog ? 1 : 0, 0, 0, 0)); + // cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._InputTexture, source); + // cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._OutputTexture, destination); + // cmd.DispatchCompute(cs, kernel, (hdCamera.actualWidth + 7) / 8, (hdCamera.actualHeight + 7) / 8, hdCamera.viewCount); + // m_HDInstance.PushFullScreenDebugTexture(hdCamera, cmd, destination, FullScreenDebugMode.ColorLog); + + // // Cleanup + // if (bloomActive) m_Pool.Recycle(m_BloomTexture); + // m_BloomTexture = null; + + // PoolSource(ref source, destination); + // } + + // if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.CustomPostProcess)) + // { + // using (new ProfilingSample(cmd, "Custom Post Processes After PP", CustomSamplerId.CustomPostProcessAfterPP.GetSampler())) + // { + // foreach (var typeString in HDRenderPipeline.currentAsset.afterPostProcessCustomPostProcesses) + // RenderCustomPostProcess(cmd, hdCamera, ref source, colorBuffer, Type.GetType(typeString)); + // } + // } + //} + + //if (dynResHandler.DynamicResolutionEnabled() && // Dynamic resolution is on. + // hdCamera.antialiasing == AntialiasingMode.FastApproximateAntialiasing && + // m_AntialiasingFS) + //{ + // using (new ProfilingSample(cmd, "FXAA", CustomSamplerId.FXAA.GetSampler())) + // { + // var destination = m_Pool.Get(Vector2.one, k_ColorFormat); + // DoFXAA(cmd, hdCamera, source, destination); + // PoolSource(ref source, destination); + // } + //} + + using (var builder = renderGraph.AddRenderPass("Final Pass", out var passData, CustomSamplerId.FinalPost.GetSampler())) + { + passData.parameters = PrepareFinalPass(hdCamera, blueNoise, flipY); + passData.source = builder.ReadTexture(source); + passData.afterPostProcessTexture = builder.ReadTexture(afterPostProcessTexture); + passData.alphaTexture = builder.ReadTexture(m_KeepAlpha ? alphaTexture : renderGraph.ImportTexture(TextureXR.GetWhiteTexture())); + passData.destination = builder.WriteTexture(finalRT); + + builder.SetRenderFunc( + (FinalPassData data, RenderGraphContext ctx) => + { + DoFinalPass( data.parameters, + ctx.resources.GetTexture(data.source), + ctx.resources.GetTexture(data.afterPostProcessTexture), + ctx.resources.GetTexture(data.destination), + ctx.resources.GetTexture(data.alphaTexture), + ctx.cmd); + }); + } + + m_ResetHistory = false; + } + + class FinalPassData + { + public FinalPassParameters parameters; + public RenderGraphResource source; + public RenderGraphResource afterPostProcessTexture; + public RenderGraphResource alphaTexture; + public RenderGraphMutableResource destination; + } + } +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs.meta b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs.meta new file mode 100644 index 00000000000..85fcc5d6b1e --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 76434967396241842bc441718c563f5c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs index 2581cd9269e..3dd15e9caa4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs @@ -10,7 +10,7 @@ namespace UnityEngine.Rendering.HighDefinition // Main class for all post-processing related features - only includes camera effects, no // lighting/surface effect like SSR/AO - sealed class PostProcessSystem + sealed partial class PostProcessSystem { private enum SMAAStage { @@ -361,7 +361,7 @@ void PoolSourceGuard(ref RTHandle src, RTHandle dst, RTHandle colorBuffer) src = dst; } - public void Render(CommandBuffer cmd, HDCamera camera, BlueNoise blueNoise, RTHandle colorBuffer, RTHandle afterPostProcessTexture, RTHandle lightingBuffer, RenderTargetIdentifier finalRT, RTHandle depthBuffer, bool flipY) + public void Render(CommandBuffer cmd, HDCamera camera, BlueNoise blueNoise, RTHandle colorBuffer, RTHandle afterPostProcessTexture, RenderTargetIdentifier finalRT, RTHandle depthBuffer, bool flipY) { var dynResHandler = DynamicResolutionHandler.instance; @@ -432,7 +432,7 @@ void PoolSource(ref RTHandle src, RTHandle dst) { using (new ProfilingSample(cmd, "Dynamic Exposure", CustomSamplerId.Exposure.GetSampler())) { - DoDynamicExposure(cmd, camera, source, lightingBuffer); + DoDynamicExposure(cmd, camera, source); } } @@ -591,7 +591,9 @@ void PoolSource(ref RTHandle src, RTHandle dst) // Final pass using (new ProfilingSample(cmd, "Final Pass", CustomSamplerId.FinalPost.GetSampler())) { - DoFinalPass(cmd, camera, blueNoise, source, afterPostProcessTexture, finalRT, flipY); + var finalPassParameters = PrepareFinalPass(camera, blueNoise, flipY); + RTHandle alphaTexture = m_KeepAlpha ? m_AlphaTexture : TextureXR.GetWhiteTexture(); + DoFinalPass(finalPassParameters, source, afterPostProcessTexture, finalRT, alphaTexture, cmd); PoolSource(ref source, null); } } @@ -767,7 +769,7 @@ void PrepareExposureCurveData(AnimationCurve curve, out float min, out float max } // TODO: Handle light buffer as a source for average luminance - void DoDynamicExposure(CommandBuffer cmd, HDCamera camera, RTHandle colorBuffer, RTHandle lightingBuffer) + void DoDynamicExposure(CommandBuffer cmd, HDCamera camera, RTHandle colorBuffer) { var cs = m_Resources.shaders.exposureCS; int kernel; @@ -792,10 +794,6 @@ void DoDynamicExposure(CommandBuffer cmd, HDCamera camera, RTHandle colorBuffer, m_ExposureVariants[2] = (int)adaptationMode; m_ExposureVariants[3] = 0; - // Pre-pass - //var sourceTex = exposureSettings.luminanceSource == LuminanceSource.LightingBuffer - // ? lightingBuffer - // : colorBuffer; var sourceTex = colorBuffer; kernel = cs.FindKernel("KPrePass"); @@ -1700,7 +1698,7 @@ unsafe void DoBloom(CommandBuffer cmd, HDCamera camera, RTHandle source, Compute // If the scene is less than 50% of 900p, then we operate on full res, since it's going to be cheap anyway and this might improve quality in challenging situations. // Also we switch to bilinear upsampling as it goes less wide than bicubic and due to our border/RTHandle handling, going wide on small resolution - // where small mips have a strong influence, might result problematic. + // where small mips have a strong influence, might result problematic. if (camera.actualWidth < 800 || camera.actualHeight < 450) { scaleW = 1.0f; @@ -2286,65 +2284,118 @@ void DoSMAA(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destin #region Final Pass - void DoFinalPass(CommandBuffer cmd, HDCamera camera, BlueNoise blueNoise, RTHandle source, RTHandle afterPostProcessTexture, RenderTargetIdentifier destination, bool flipY) + struct FinalPassParameters + { + public bool postProcessEnabled; + public Material finalPassMaterial; + public HDCamera hdCamera; + public BlueNoise blueNoise; + public bool flipY; + public System.Random random; + public bool useFXAA; + + public bool filmGrainEnabled; + public Texture filmGrainTexture; + public float filmGrainIntensity; + public float filmGrainResponse; + + public bool ditheringEnabled; + } + + FinalPassParameters PrepareFinalPass(HDCamera hdCamera, BlueNoise blueNoise, bool flipY) + { + FinalPassParameters parameters = new FinalPassParameters(); + + // General + parameters.postProcessEnabled = m_PostProcessEnabled; + parameters.finalPassMaterial = m_FinalPassMaterial; + parameters.hdCamera = hdCamera; + parameters.blueNoise = blueNoise; + parameters.flipY = flipY; + parameters.random = m_Random; + + var dynResHandler = DynamicResolutionHandler.instance; + bool dynamicResIsOn = hdCamera.isMainGameView && dynResHandler.DynamicResolutionEnabled(); + parameters.useFXAA = hdCamera.antialiasing == AntialiasingMode.FastApproximateAntialiasing && !dynamicResIsOn && m_AntialiasingFS; + + // Film Grain + parameters.filmGrainEnabled = m_FilmGrain.IsActive() && m_FilmGrainFS; + if (m_FilmGrain.type.value != FilmGrainLookup.Custom) + parameters.filmGrainTexture = m_Resources.textures.filmGrainTex[(int)m_FilmGrain.type.value]; + else + parameters.filmGrainTexture = m_FilmGrain.texture.value; + parameters.filmGrainIntensity = m_FilmGrain.intensity.value; + parameters.filmGrainResponse = m_FilmGrain.response.value; + + // Dithering + parameters.ditheringEnabled = hdCamera.dithering && m_DitheringFS; + + return parameters; + } + + static void DoFinalPass( in FinalPassParameters parameters, + RTHandle source, + RTHandle afterPostProcessTexture, + RenderTargetIdentifier destination, + RTHandle alphaTexture, + CommandBuffer cmd) { // Final pass has to be done in a pixel shader as it will be the one writing straight // to the backbuffer eventually - m_FinalPassMaterial.shaderKeywords = null; - m_FinalPassMaterial.SetTexture(HDShaderIDs._InputTexture, source); + Material finalPassMaterial = parameters.finalPassMaterial; + HDCamera hdCamera = parameters.hdCamera; + bool flipY = parameters.flipY; + + finalPassMaterial.shaderKeywords = null; + finalPassMaterial.SetTexture(HDShaderIDs._InputTexture, source); var dynResHandler = DynamicResolutionHandler.instance; - bool dynamicResIsOn = camera.isMainGameView && dynResHandler.DynamicResolutionEnabled(); + bool dynamicResIsOn = hdCamera.isMainGameView && dynResHandler.DynamicResolutionEnabled(); if (dynamicResIsOn) { switch (dynResHandler.filter) { case DynamicResUpscaleFilter.Bilinear: - m_FinalPassMaterial.EnableKeyword("BILINEAR"); + finalPassMaterial.EnableKeyword("BILINEAR"); break; case DynamicResUpscaleFilter.CatmullRom: - m_FinalPassMaterial.EnableKeyword("CATMULL_ROM_4"); + finalPassMaterial.EnableKeyword("CATMULL_ROM_4"); break; case DynamicResUpscaleFilter.Lanczos: - m_FinalPassMaterial.EnableKeyword("LANCZOS"); + finalPassMaterial.EnableKeyword("LANCZOS"); break; } } - if (m_PostProcessEnabled) + if (parameters.postProcessEnabled) { - if (camera.antialiasing == AntialiasingMode.FastApproximateAntialiasing && !dynamicResIsOn && m_AntialiasingFS) - m_FinalPassMaterial.EnableKeyword("FXAA"); + if (parameters.useFXAA) + finalPassMaterial.EnableKeyword("FXAA"); - if (m_FilmGrain.IsActive() && m_FilmGrainFS) + if (parameters.filmGrainEnabled) { - var texture = m_FilmGrain.texture.value; - - if (m_FilmGrain.type.value != FilmGrainLookup.Custom) - texture = m_Resources.textures.filmGrainTex[(int)m_FilmGrain.type.value]; - - if (texture != null) // Fail safe if the resources asset breaks :/ + if (parameters.filmGrainTexture != null) // Fail safe if the resources asset breaks :/ { #if HDRP_DEBUG_STATIC_POSTFX int offsetX = 0; int offsetY = 0; #else - int offsetX = (int)(m_Random.NextDouble() * texture.width); - int offsetY = (int)(m_Random.NextDouble() * texture.height); + int offsetX = (int)(parameters.random.NextDouble() * parameters.filmGrainTexture.width); + int offsetY = (int)(parameters.random.NextDouble() * parameters.filmGrainTexture.height); #endif - m_FinalPassMaterial.EnableKeyword("GRAIN"); - m_FinalPassMaterial.SetTexture(HDShaderIDs._GrainTexture, texture); - m_FinalPassMaterial.SetVector(HDShaderIDs._GrainParams, new Vector2(m_FilmGrain.intensity.value * 4f, m_FilmGrain.response.value)); - m_FinalPassMaterial.SetVector(HDShaderIDs._GrainTextureParams, new Vector4(texture.width, texture.height, offsetX, offsetY)); + finalPassMaterial.EnableKeyword("GRAIN"); + finalPassMaterial.SetTexture(HDShaderIDs._GrainTexture, parameters.filmGrainTexture); + finalPassMaterial.SetVector(HDShaderIDs._GrainParams, new Vector2(parameters.filmGrainIntensity * 4f, parameters.filmGrainResponse)); + finalPassMaterial.SetVector(HDShaderIDs._GrainTextureParams, new Vector4(parameters.filmGrainTexture.width, parameters.filmGrainTexture.height, offsetX, offsetY)); } } - if (camera.dithering && m_DitheringFS) + if (parameters.ditheringEnabled) { - var blueNoiseTexture = blueNoise.textureArray16L; + var blueNoiseTexture = parameters.blueNoise.textureArray16L; #if HDRP_DEBUG_STATIC_POSTFX int textureId = 0; @@ -2352,26 +2403,21 @@ void DoFinalPass(CommandBuffer cmd, HDCamera camera, BlueNoise blueNoise, RTHand int textureId = Time.frameCount % blueNoiseTexture.depth; #endif - m_FinalPassMaterial.EnableKeyword("DITHER"); - m_FinalPassMaterial.SetTexture(HDShaderIDs._BlueNoiseTexture, blueNoiseTexture); - m_FinalPassMaterial.SetVector(HDShaderIDs._DitherParams, new Vector3(blueNoiseTexture.width, blueNoiseTexture.height, textureId)); + finalPassMaterial.EnableKeyword("DITHER"); + finalPassMaterial.SetTexture(HDShaderIDs._BlueNoiseTexture, blueNoiseTexture); + finalPassMaterial.SetVector(HDShaderIDs._DitherParams, new Vector3(blueNoiseTexture.width, blueNoiseTexture.height, textureId)); } } - m_FinalPassMaterial.SetTexture(HDShaderIDs._AlphaTexture, - m_KeepAlpha - ? m_AlphaTexture.rt - : (Texture)Texture2D.whiteTexture - ); - - m_FinalPassMaterial.SetVector(HDShaderIDs._UVTransform, + finalPassMaterial.SetTexture(HDShaderIDs._AlphaTexture, alphaTexture); + finalPassMaterial.SetVector(HDShaderIDs._UVTransform, flipY ? new Vector4(1.0f, -1.0f, 0.0f, 1.0f) : new Vector4(1.0f, 1.0f, 0.0f, 0.0f) ); // Blit to backbuffer - Rect backBufferRect = camera.finalViewport; + Rect backBufferRect = hdCamera.finalViewport; // When post process is not the final pass, we render at (0,0) so that subsequent rendering does not have to bother about viewports. // Final viewport is handled in the final blit in this case @@ -2386,17 +2432,17 @@ void DoFinalPass(CommandBuffer cmd, HDCamera camera, BlueNoise blueNoise, RTHand backBufferRect.x = backBufferRect.y = 0; } - if (camera.frameSettings.IsEnabled(FrameSettingsField.AfterPostprocess)) + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.AfterPostprocess)) { - m_FinalPassMaterial.EnableKeyword("APPLY_AFTER_POST"); - m_FinalPassMaterial.SetTexture(HDShaderIDs._AfterPostProcessTexture, afterPostProcessTexture); + finalPassMaterial.EnableKeyword("APPLY_AFTER_POST"); + finalPassMaterial.SetTexture(HDShaderIDs._AfterPostProcessTexture, afterPostProcessTexture); } else { - m_FinalPassMaterial.SetTexture(HDShaderIDs._AfterPostProcessTexture, TextureXR.GetBlackTexture()); + finalPassMaterial.SetTexture(HDShaderIDs._AfterPostProcessTexture, TextureXR.GetBlackTexture()); } - HDUtils.DrawFullScreen(cmd, backBufferRect, m_FinalPassMaterial, destination); + HDUtils.DrawFullScreen(cmd, backBufferRect, finalPassMaterial, destination); } #endregion diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs index d69265c7b34..fa30997ff2f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs @@ -14,29 +14,58 @@ class AfterPostProcessPassData public RenderGraphResource transparentAfterPostprocessRL; } - void RenderPostProcess(RenderGraph renderGraph, RenderGraphMutableResource depthBuffer, CullingResults cullResults, HDCamera hdCamera) + RenderGraphMutableResource RenderPostProcess( RenderGraph renderGraph, + RenderGraphResource inputColor, + RenderGraphMutableResource depthBuffer, + RenderGraphMutableResource backBuffer, + CullingResults cullResults, + HDCamera hdCamera) { - // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass - using (var builder = renderGraph.AddRenderPass("AfterPostProcess", out var passData, CustomSamplerId.GBuffer.GetSampler())) + PostProcessParameters parameters = PreparePostProcess(cullResults, hdCamera); + + RenderGraphResource afterPostProcessBuffer = renderGraph.ImportTexture(TextureXR.GetBlackTexture()); + RenderGraphMutableResource dest = HDUtils.PostProcessIsFinalPass() ? backBuffer : renderGraph.CreateTexture( + new TextureDesc(Vector2.one, true, true) { colorFormat = GetColorBufferFormat(), name = "Intermediate Postprocess buffer" }); + + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.AfterPostprocess)) { - passData.parameters = PreparePostProcess(cullResults, hdCamera); - passData.afterPostProcessBuffer = builder.UseColorBuffer(renderGraph.CreateTexture( - new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R8G8B8A8_SRGB, clearBuffer = true, clearColor = Color.black, name = "OffScreen AfterPostProcess" }), 0); - if (passData.parameters.useDepthBuffer) - passData.depthStencilBuffer = builder.UseDepthBuffer(depthBuffer, DepthAccess.ReadWrite); - passData.opaqueAfterPostprocessRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.opaqueAfterPPDesc)); - passData.transparentAfterPostprocessRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.transparentAfterPPDesc)); - - builder.SetRenderFunc( - (AfterPostProcessPassData data, RenderGraphContext ctx) => + // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass + using (var builder = renderGraph.AddRenderPass("After Post-Process", out var passData, CustomSamplerId.AfterPostProcessing.GetSampler())) { - RenderAfterPostProcess( data.parameters - , ctx.resources.GetRendererList(data.opaqueAfterPostprocessRL) - , ctx.resources.GetRendererList(data.transparentAfterPostprocessRL) - , ctx.renderContext, ctx.cmd); + passData.parameters = parameters; + passData.afterPostProcessBuffer = builder.UseColorBuffer(renderGraph.CreateTexture( + new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R8G8B8A8_SRGB, clearBuffer = true, clearColor = Color.black, name = "OffScreen AfterPostProcess" }), 0); + if (passData.parameters.useDepthBuffer) + passData.depthStencilBuffer = builder.UseDepthBuffer(depthBuffer, DepthAccess.ReadWrite); + passData.opaqueAfterPostprocessRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.opaqueAfterPPDesc)); + passData.transparentAfterPostprocessRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.transparentAfterPPDesc)); + + builder.SetRenderFunc( + (AfterPostProcessPassData data, RenderGraphContext ctx) => + { + RenderAfterPostProcess(data.parameters + , ctx.resources.GetRendererList(data.opaqueAfterPostprocessRL) + , ctx.resources.GetRendererList(data.transparentAfterPostprocessRL) + , ctx.renderContext, ctx.cmd); - }); + }); + + afterPostProcessBuffer = passData.afterPostProcessBuffer; + } } + + m_PostProcessSystem.Render( + renderGraph, + parameters.hdCamera, + parameters.blueNoise, + inputColor, + afterPostProcessBuffer, + depthBuffer, + dest, + parameters.flipYInPostProcess + ); + + return dest; } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index 69e75c15560..c52db2ffce5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -23,6 +23,7 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, || camera.cameraType == CameraType.SceneView; #endif + RenderGraphMutableResource backBuffer = m_RenderGraph.ImportBackbuffer(target.id); RenderGraphMutableResource colorBuffer = CreateColorBuffer(m_RenderGraph, hdCamera, msaa); RenderGraphMutableResource currentColorPyramid = m_RenderGraph.ImportTexture(hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ColorBufferMipChain), HDShaderIDs._ColorPyramidTexture); @@ -165,10 +166,11 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, aovRequest.PushCameraTexture(m_RenderGraph, AOVBuffers.Color, hdCamera, colorBuffer, aovBuffers); - RenderPostProcess(m_RenderGraph, prepassOutput.depthBuffer, cullingResults, hdCamera); + RenderGraphMutableResource postProcessDest = RenderPostProcess(m_RenderGraph, colorBuffer, prepassOutput.depthBuffer, backBuffer, cullingResults, hdCamera); // TODO RENDERGRAPH //bool hasAfterPostProcessCustomPass = RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterPostProcess); + bool hasAfterPostProcessCustomPass = false; // TODO RENDERGRAPH //// Copy and rescale depth buffer for XR devices @@ -191,21 +193,21 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, // In developer build, we always render post process in m_AfterPostProcessBuffer at (0,0) in which we will then render debug. // Because of this, we need another blit here to the final render target at the right viewport. - //if (!HDUtils.PostProcessIsFinalPass() || aovRequest.isValid || hasAfterPostProcessCustomPass) + if (!HDUtils.PostProcessIsFinalPass() || aovRequest.isValid || hasAfterPostProcessCustomPass) { hdCamera.ExecuteCaptureActions(m_RenderGraph, colorBuffer); - colorBuffer = RenderDebug( m_RenderGraph, - hdCamera, - colorBuffer, - prepassOutput.depthBuffer, - prepassOutput.depthPyramidTexture, - m_DebugFullScreenTexture, - colorPickerTexture, - shadowResult, - cullingResults); + postProcessDest = RenderDebug( m_RenderGraph, + hdCamera, + postProcessDest, + prepassOutput.depthBuffer, + prepassOutput.depthPyramidTexture, + m_DebugFullScreenTexture, + colorPickerTexture, + shadowResult, + cullingResults); - BlitFinalCameraTexture(m_RenderGraph, hdCamera, colorBuffer, target.id, prepassOutput.resolvedMotionVectorsBuffer, prepassOutput.resolvedNormalBuffer); + BlitFinalCameraTexture(m_RenderGraph, hdCamera, postProcessDest, backBuffer, prepassOutput.resolvedMotionVectorsBuffer, prepassOutput.resolvedNormalBuffer); aovRequest.PushCameraTexture(m_RenderGraph, AOVBuffers.Output, hdCamera, colorBuffer, aovBuffers); } @@ -241,16 +243,16 @@ class FinalBlitPassData { public BlitFinalCameraTextureParameters parameters; public RenderGraphResource source; - public RenderTargetIdentifier destination; + public RenderGraphMutableResource destination; } - void BlitFinalCameraTexture(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphResource source, RenderTargetIdentifier destination, RenderGraphResource motionVectors, RenderGraphResource normalBuffer) + void BlitFinalCameraTexture(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphResource source, RenderGraphMutableResource destination, RenderGraphResource motionVectors, RenderGraphResource normalBuffer) { using (var builder = renderGraph.AddRenderPass("Final Blit (Dev Build Only)", out var passData)) { passData.parameters = PrepareFinalBlitParameters(hdCamera, 0); // todo viewIndex passData.source = builder.ReadTexture(source); - passData.destination = destination; + passData.destination = builder.WriteTexture(destination); // TODO REMOVE: Dummy read to avoid early release before render graph is full implemented. bool msaa = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); @@ -262,7 +264,8 @@ void BlitFinalCameraTexture(RenderGraph renderGraph, HDCamera hdCamera, RenderGr (FinalBlitPassData data, RenderGraphContext context) => { var sourceTexture = context.resources.GetTexture(data.source); - BlitFinalCameraTexture(data.parameters, context.renderGraphPool.GetTempMaterialPropertyBlock(), sourceTexture, data.destination, context.cmd); + var destinationTexture = context.resources.GetTexture(data.destination); + BlitFinalCameraTexture(data.parameters, context.renderGraphPool.GetTempMaterialPropertyBlock(), sourceTexture, destinationTexture, context.cmd); }); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 226d88863bd..99f935d0f56 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -4285,19 +4285,25 @@ void RenderPostProcess(CullingResults cullResults, HDCamera hdCamera, RenderTarg { PostProcessParameters parameters = PreparePostProcess(cullResults, hdCamera); - // Note: We bind the depth only if the ZTest for After Post Process is enabled. It is disabled by - // default so we're consistent in the behavior: no ZTest for After Post Process materials). - if (!parameters.useDepthBuffer) - CoreUtils.SetRenderTarget(cmd, GetAfterPostProcessOffScreenBuffer(), clearFlag: ClearFlag.Color, clearColor: Color.black); - else - CoreUtils.SetRenderTarget(cmd, GetAfterPostProcessOffScreenBuffer(), m_SharedRTManager.GetDepthStencilBuffer(), clearFlag: ClearFlag.Color, clearColor: Color.black); + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.AfterPostprocess)) + { + using (new ProfilingSample(cmd, "After Post-process", CustomSamplerId.AfterPostProcessing.GetSampler())) + { + // Note: We bind the depth only if the ZTest for After Post Process is enabled. It is disabled by + // default so we're consistent in the behavior: no ZTest for After Post Process materials). + if (!parameters.useDepthBuffer) + CoreUtils.SetRenderTarget(cmd, GetAfterPostProcessOffScreenBuffer(), clearFlag: ClearFlag.Color, clearColor: Color.black); + else + CoreUtils.SetRenderTarget(cmd, GetAfterPostProcessOffScreenBuffer(), m_SharedRTManager.GetDepthStencilBuffer(), clearFlag: ClearFlag.Color, clearColor: Color.black); + // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass + RenderAfterPostProcess(parameters + , RendererList.Create(parameters.opaqueAfterPPDesc) + , RendererList.Create(parameters.transparentAfterPPDesc) + , renderContext, cmd); - // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass - RenderAfterPostProcess( parameters - , RendererList.Create(parameters.opaqueAfterPPDesc) - , RendererList.Create(parameters.transparentAfterPPDesc) - , renderContext, cmd); + } + } // Set the depth buffer to the main one to avoid missing out on transparent depth for post process. cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); @@ -4309,7 +4315,6 @@ void RenderPostProcess(CullingResults cullResults, HDCamera hdCamera, RenderTarg blueNoise: parameters.blueNoise, colorBuffer: m_CameraColorBuffer, afterPostProcessTexture: GetAfterPostProcessOffScreenBuffer(), - lightingBuffer: null, finalRT: destination, depthBuffer: m_SharedRTManager.GetDepthStencilBuffer(), flipY: parameters.flipYInPostProcess @@ -4332,26 +4337,18 @@ static void RenderAfterPostProcess( PostProcessParameters parameters, in RendererList transparentAfterPostProcessRendererList, ScriptableRenderContext renderContext, CommandBuffer cmd) { - var hdCamera = parameters.hdCamera; - if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.AfterPostprocess)) - return; - - using (new ProfilingSample(cmd, "After Post-process", CustomSamplerId.AfterPostProcessing.GetSampler())) - { - // Note about AfterPostProcess and TAA: - // When TAA is enabled rendering is jittered and then resolved during the post processing pass. - // It means that any rendering done after post processing need to disable jittering. This is what we do with hdCamera.UpdateViewConstants(false); - // The issue is that the only available depth buffer is jittered so pixels would wobble around depth tested edges. - // In order to avoid that we decide that objects rendered after Post processes while TAA is active will not benefit from the depth buffer so we disable it. - bool taaEnabled = hdCamera.IsTAAEnabled(); - hdCamera.UpdateAllViewConstants(false); - hdCamera.SetupGlobalParams(cmd, parameters.time, parameters.lastTime, parameters.frameCount); - - cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 1); - DrawOpaqueRendererList(renderContext, cmd, hdCamera.frameSettings, opaqueAfterPostProcessRendererList); - DrawTransparentRendererList(renderContext, cmd, hdCamera.frameSettings, transparentAfterPostProcessRendererList); - cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 0); - } + // Note about AfterPostProcess and TAA: + // When TAA is enabled rendering is jittered and then resolved during the post processing pass. + // It means that any rendering done after post processing need to disable jittering. This is what we do with hdCamera.UpdateViewConstants(false); + // The issue is that the only available depth buffer is jittered so pixels would wobble around depth tested edges. + // In order to avoid that we decide that objects rendered after Post processes while TAA is active will not benefit from the depth buffer so we disable it. + parameters.hdCamera.UpdateAllViewConstants(false); + parameters.hdCamera.SetupGlobalParams(cmd, parameters.time, parameters.lastTime, parameters.frameCount); + + cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 1); + DrawOpaqueRendererList(renderContext, cmd, parameters.hdCamera.frameSettings, opaqueAfterPostProcessRendererList); + DrawTransparentRendererList(renderContext, cmd, parameters.hdCamera.frameSettings, transparentAfterPostProcessRendererList); + cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 0); } void SendGeometryGraphicsBuffers(CommandBuffer cmd, HDCamera hdCamera) From 9b45bac4310970bbd9b79044f8a9bbf319bd1c81 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Mon, 10 Feb 2020 17:31:06 +0100 Subject: [PATCH 11/92] Post merge fixes --- .../PostProcessing/PostProcessSystem.cs | 2 +- .../HDRenderPipeline.PostProcess.cs | 2 +- .../HDRenderPipeline.RenderGraph.cs | 6 +---- .../RenderPipeline/HDRenderPipeline.cs | 27 +++++-------------- .../Runtime/RenderPipeline/Utility/HDUtils.cs | 17 ++++++++++-- 5 files changed, 25 insertions(+), 29 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs index 049ba1219c8..7f60361e074 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs @@ -2536,7 +2536,7 @@ static void DoFinalPass( in FinalPassParameters parameters, // When post process is not the final pass, we render at (0,0) so that subsequent rendering does not have to bother about viewports. // Final viewport is handled in the final blit in this case - if (!HDUtils.PostProcessIsFinalPass()) + if (!HDUtils.PostProcessIsFinalPass(hdCamera)) { if (dynResHandler.HardwareDynamicResIsEnabled()) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs index 97a1fe5642b..af3bf866fdb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs @@ -24,7 +24,7 @@ RenderGraphMutableResource RenderPostProcess( RenderGraph rend PostProcessParameters parameters = PreparePostProcess(cullResults, hdCamera); RenderGraphResource afterPostProcessBuffer = renderGraph.ImportTexture(TextureXR.GetBlackTexture()); - RenderGraphMutableResource dest = HDUtils.PostProcessIsFinalPass() ? backBuffer : renderGraph.CreateTexture( + RenderGraphMutableResource dest = HDUtils.PostProcessIsFinalPass(parameters.hdCamera) ? backBuffer : renderGraph.CreateTexture( new TextureDesc(Vector2.one, true, true) { colorFormat = GetColorBufferFormat(), name = "Intermediate Postprocess buffer" }); if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.AfterPostprocess)) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index 64381590edb..79aee4eb9c3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -168,10 +168,6 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, RenderGraphMutableResource postProcessDest = RenderPostProcess(m_RenderGraph, colorBuffer, prepassOutput.depthBuffer, backBuffer, cullingResults, hdCamera); - // TODO RENDERGRAPH - //bool hasAfterPostProcessCustomPass = RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterPostProcess); - bool hasAfterPostProcessCustomPass = false; - // TODO RENDERGRAPH //// Copy and rescale depth buffer for XR devices //if (hdCamera.xr.enabled && hdCamera.xr.copyDepth) @@ -193,7 +189,7 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, // In developer build, we always render post process in m_AfterPostProcessBuffer at (0,0) in which we will then render debug. // Because of this, we need another blit here to the final render target at the right viewport. - if (!HDUtils.PostProcessIsFinalPass() || aovRequest.isValid || hasAfterPostProcessCustomPass) + if (!HDUtils.PostProcessIsFinalPass(hdCamera) || aovRequest.isValid) { hdCamera.ExecuteCaptureActions(m_RenderGraph, colorBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index eea2f4f57b8..1324453f9ad 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -2323,12 +2323,10 @@ void Callback(CommandBuffer c, HDCamera cam) RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforePostProcess); - bool hasAfterPostProcessCustomPass = WillCustomPassBeExecuted(hdCamera, CustomPassInjectionPoint.AfterPostProcess); - aovRequest.PushCameraTexture(cmd, AOVBuffers.Color, hdCamera, m_CameraColorBuffer, aovBuffers); - RenderTargetIdentifier postProcessDest = HDUtils.PostProcessIsFinalPass() ? target.id : m_IntermediateAfterPostProcessBuffer; - RenderPostProcess(cullingResults, hdCamera, postProcessDest, renderContext, cmd, !hasAfterPostProcessCustomPass); + RenderTargetIdentifier postProcessDest = HDUtils.PostProcessIsFinalPass(hdCamera) ? target.id : m_IntermediateAfterPostProcessBuffer; + RenderPostProcess(cullingResults, hdCamera, postProcessDest, renderContext, cmd); RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterPostProcess); @@ -2352,7 +2350,7 @@ void Callback(CommandBuffer c, HDCamera cam) // In developer build, we always render post process in m_AfterPostProcessBuffer at (0,0) in which we will then render debug. // Because of this, we need another blit here to the final render target at the right viewport. - if (!HDUtils.PostProcessIsFinalPass() || aovRequest.isValid || hasAfterPostProcessCustomPass) + if (!HDUtils.PostProcessIsFinalPass(hdCamera) || aovRequest.isValid) { hdCamera.ExecuteCaptureActions(m_IntermediateAfterPostProcessBuffer, cmd); @@ -3565,19 +3563,6 @@ bool RenderCustomPass(ScriptableRenderContext context, CommandBuffer cmd, HDCame return customPass.Execute(context, cmd, hdCamera, cullingResults, m_SharedRTManager, customPassTargets); } - bool WillCustomPassBeExecuted(HDCamera hdCamera, CustomPassInjectionPoint injectionPoint) - { - if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.CustomPass)) - return false; - - var customPass = CustomPassVolume.GetActivePassVolume(injectionPoint); - - if (customPass == null) - return false; - - return customPass.WillExecuteInjectionPoint(hdCamera); - } - void RenderTransparentDepthPrepass(CullingResults cull, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd) { if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.TransparentPrepass)) @@ -4343,7 +4328,8 @@ void ClearBuffers(HDCamera hdCamera, CommandBuffer cmd) struct PostProcessParameters { - public HDCamera hdCamera; + public HDCamera hdCamera; + public bool postProcessIsFinalPass; public bool flipYInPostProcess; public BlueNoise blueNoise; @@ -4360,9 +4346,10 @@ PostProcessParameters PreparePostProcess(CullingResults cullResults, HDCamera hd { PostProcessParameters result = new PostProcessParameters(); result.hdCamera = hdCamera; + result.postProcessIsFinalPass = HDUtils.PostProcessIsFinalPass(hdCamera); // Y-Flip needs to happen during the post process pass only if it's the final pass and is the regular game view // SceneView flip is handled by the editor internal code and GameView rendering into render textures should not be flipped in order to respect Unity texture coordinates convention - result.flipYInPostProcess = HDUtils.PostProcessIsFinalPass() && (hdCamera.flipYMode == HDAdditionalCameraData.FlipYMode.ForceFlipY || hdCamera.isMainGameView); + result.flipYInPostProcess = result.postProcessIsFinalPass && (hdCamera.flipYMode == HDAdditionalCameraData.FlipYMode.ForceFlipY || hdCamera.isMainGameView); result.blueNoise = m_BlueNoise; result.useDepthBuffer = !hdCamera.IsTAAEnabled() && hdCamera.frameSettings.IsEnabled(FrameSettingsField.ZTestAfterPostProcessTAA); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs index 9c37c1b5383..19d9e196072 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs @@ -693,12 +693,25 @@ internal static float ComputeWeightedLinearFadeDistance(Vector3 position1, Vecto return distanceFade * weight; } - internal static bool PostProcessIsFinalPass() + internal static bool WillCustomPassBeExecuted(HDCamera hdCamera, CustomPassInjectionPoint injectionPoint) + { + if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.CustomPass)) + return false; + + var customPass = CustomPassVolume.GetActivePassVolume(injectionPoint); + + if (customPass == null) + return false; + + return customPass.WillExecuteInjectionPoint(hdCamera); + } + + internal static bool PostProcessIsFinalPass(HDCamera hdCamera) { // Post process pass is the final blit only when not in developer mode. // In developer mode, we support a range of debug rendering that needs to occur after post processes. // In order to simplify writing them, we don't Y-flip in the post process pass but add a final blit at the end of the frame. - return !Debug.isDebugBuild; + return !Debug.isDebugBuild && !WillCustomPassBeExecuted(hdCamera, CustomPassInjectionPoint.AfterPostProcess); } // These two convertion functions are used to store GUID assets inside materials, From 6676461ab9bb00f3c54e6bd08a7b1d07b0b41499 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 11 Feb 2020 11:51:29 +0100 Subject: [PATCH 12/92] Fixed some issues with missing buffers in SSS and deferred lighting compute shaders. --- .../SubsurfaceScatteringManager.cs | 7 +++++-- .../RenderPipeline/HDRenderPipeline.LightLoop.cs | 10 ++++++++-- .../HDRenderPipeline.SubsurfaceScattering.cs | 1 + 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index aadd0051593..ebedd03fe36 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -246,6 +246,7 @@ struct SubsurfaceScatteringParameters public Vector4[] filterKernels; public Vector4[] shapeParams; public float[] diffusionProfileHashes; + public ComputeBuffer coarseStencilBuffer; } @@ -280,6 +281,8 @@ SubsurfaceScatteringParameters PrepareSubsurfaceScatteringParameters(HDCamera hd parameters.shapeParams = m_SSSShapeParams; parameters.diffusionProfileHashes = m_SSSDiffusionProfileHashes; + parameters.coarseStencilBuffer = m_SharedRTManager.GetCoarseStencilBuffer(); + return parameters; } @@ -425,7 +428,7 @@ void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle c resources.depthStencilBuffer = depthStencilBufferRT; resources.depthTexture = depthTextureRT; resources.cameraFilteringBuffer = m_SSSCameraFilteringBuffer; - resources.coarseStencilBuffer = m_SharedRTManager.GetCoarseStencilBuffer(); + resources.coarseStencilBuffer = parameters.coarseStencilBuffer; resources.sssBuffer = m_SSSColor; // For Jimenez we always need an extra buffer, for Disney it depends on platform @@ -442,7 +445,7 @@ void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle c } } } - + // Combines specular lighting and diffuse lighting with subsurface scattering. // In the case our frame is MSAA, for the moment given the fact that we do not have read/write access to the stencil buffer of the MSAA target; we need to keep this pass MSAA diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 966eac7b232..fbffb557fcc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -176,6 +176,13 @@ LightingOutput RenderDeferredLighting( RenderGraph renderGraph, { passData.sssDiffuseLightingBuffer = builder.WriteTexture(lightingBuffers.diffuseLightingBuffer); } + else + { + // TODO RENDERGRAPH: Check how to avoid this kind of pattern. + // Unfortunately, the low level needs this texture to always be bound with UAV enabled, so in order to avoid effectively creating the full resolution texture here, + // we need to create a small dummy texture. + passData.sssDiffuseLightingBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(1, 1, true, true) { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = true } )); + } passData.depthBuffer = builder.ReadTexture(depthStencilBuffer); passData.depthTexture = builder.ReadTexture(depthPyramidTexture); @@ -196,8 +203,7 @@ LightingOutput RenderDeferredLighting( RenderGraph renderGraph, { data.resources.colorBuffers = context.renderGraphPool.GetTempArray(2); data.resources.colorBuffers[0] = context.resources.GetTexture(data.colorBuffer); - if (data.parameters.outputSplitLighting) - data.resources.colorBuffers[1] = context.resources.GetTexture(data.sssDiffuseLightingBuffer); + data.resources.colorBuffers[1] = context.resources.GetTexture(data.sssDiffuseLightingBuffer); data.resources.depthStencilBuffer = context.resources.GetTexture(data.depthBuffer); data.resources.depthTexture = context.resources.GetTexture(data.depthTexture); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs index dc96240c3fb..5754058c42e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs @@ -63,6 +63,7 @@ void RenderSubsurfaceScattering(RenderGraph renderGraph, HDCamera hdCamera, Rend resources.depthTexture = context.resources.GetTexture(data.depthTexture); resources.cameraFilteringBuffer = context.resources.GetTexture(data.cameraFilteringBuffer); resources.sssBuffer = context.resources.GetTexture(data.sssBuffer); + resources.coarseStencilBuffer = data.parameters.coarseStencilBuffer; RenderSubsurfaceScattering(data.parameters, resources, context.cmd); }); From 40d7d37a9a053bdd122f7471ea86bcfd73de7c84 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 11 Feb 2020 14:57:25 +0100 Subject: [PATCH 13/92] Fixed alpha in post processes --- .../Runtime/PostProcessing/PostProcessSystem.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs index 08ec11e5a33..733ad41232b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs @@ -2417,7 +2417,7 @@ FinalPassParameters PrepareFinalPass(HDCamera hdCamera, BlueNoise blueNoise, boo parameters.blueNoise = blueNoise; parameters.flipY = flipY; parameters.random = m_Random; - parameters.enableAlpha = m_KeepAlpha; + parameters.enableAlpha = m_EnableAlpha; var dynResHandler = DynamicResolutionHandler.instance; bool dynamicResIsOn = hdCamera.isMainGameView && dynResHandler.DynamicResolutionEnabled(); From 3fc77fab41c996e9ec3283706c6fcb7064e73e09 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 13 Feb 2020 10:30:55 +0100 Subject: [PATCH 14/92] Removed RenderGraphResource and RenderGraphMutableResource in favor of more explicit RendererListHandle and TextureHandle --- .../Runtime/RenderGraph/RenderGraph.cs | 63 +++-- .../Runtime/RenderGraph/RenderGraphBuilder.cs | 22 +- .../RenderGraph/RenderGraphResource.cs | 76 ------ .../RenderGraph/RenderGraphResource.cs.meta | 11 - .../RenderGraphResourceRegistry.cs | 100 ++++---- .../AmbientOcclusion.RenderGraph.cs | 50 ++-- .../Shadow/HDShadowManager.RenderGraph.cs | 22 +- .../PostProcessSystem.RenderGraph.cs | 28 +-- .../Runtime/RenderPipeline/Camera/HDCamera.cs | 6 +- .../RenderPipeline/HDRenderPipeline.Debug.cs | 84 +++---- .../HDRenderPipeline.LightLoop.cs | 132 +++++----- .../HDRenderPipeline.PostProcess.cs | 26 +- .../HDRenderPipeline.Prepass.cs | 142 +++++------ .../HDRenderPipeline.RenderGraph.cs | 226 +++++++++--------- .../HDRenderPipeline.RenderGraphUtils.cs | 4 +- .../HDRenderPipeline.SubsurfaceScattering.cs | 18 +- .../RenderPass/AOV/AOVRequestData.cs | 6 +- 17 files changed, 466 insertions(+), 550 deletions(-) delete mode 100644 com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResource.cs delete mode 100644 com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResource.cs.meta diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs index d53f50a5883..67659f34c2f 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs @@ -103,20 +103,20 @@ internal RenderFunc GetExecuteDelegate() internal abstract void Release(RenderGraphContext renderGraphContext); internal abstract bool HasRenderFunc(); - internal string name; - internal int index; - internal ProfilingSampler customSampler; - internal List resourceReadList = new List(); - internal List resourceWriteList = new List(); - internal List usedRendererListList = new List(); - internal bool enableAsyncCompute; - internal RenderGraphMutableResource depthBuffer { get { return m_DepthBuffer; } } - internal RenderGraphMutableResource[] colorBuffers { get { return m_ColorBuffers; } } - internal int colorBufferMaxIndex { get { return m_MaxColorBufferIndex; } } - - protected RenderGraphMutableResource[] m_ColorBuffers = new RenderGraphMutableResource[RenderGraph.kMaxMRTCount]; - protected RenderGraphMutableResource m_DepthBuffer; - protected int m_MaxColorBufferIndex = -1; + internal string name; + internal int index; + internal ProfilingSampler customSampler; + internal List resourceReadList = new List(); + internal List resourceWriteList = new List(); + internal List usedRendererListList = new List(); + internal bool enableAsyncCompute; + internal TextureHandle depthBuffer { get { return m_DepthBuffer; } } + internal TextureHandle[] colorBuffers { get { return m_ColorBuffers; } } + internal int colorBufferMaxIndex { get { return m_MaxColorBufferIndex; } } + + protected TextureHandle[] m_ColorBuffers = new TextureHandle[kMaxMRTCount]; + protected TextureHandle m_DepthBuffer; + protected int m_MaxColorBufferIndex = -1; internal void Clear() { @@ -130,14 +130,14 @@ internal void Clear() // Invalidate everything m_MaxColorBufferIndex = -1; - m_DepthBuffer = new RenderGraphMutableResource(); + m_DepthBuffer = new TextureHandle(); for (int i = 0; i < RenderGraph.kMaxMRTCount; ++i) { - m_ColorBuffers[i] = new RenderGraphMutableResource(); + m_ColorBuffers[i] = new TextureHandle(); } } - internal void SetColorBuffer(in RenderGraphMutableResource resource, int index) + internal void SetColorBuffer(TextureHandle resource, int index) { Debug.Assert(index < RenderGraph.kMaxMRTCount && index >= 0); m_MaxColorBufferIndex = Math.Max(m_MaxColorBufferIndex, index); @@ -145,7 +145,7 @@ internal void SetColorBuffer(in RenderGraphMutableResource resource, int index) resourceWriteList.Add(resource); } - internal void SetDepthBuffer(in RenderGraphMutableResource resource, DepthAccess flags) + internal void SetDepthBuffer(TextureHandle resource, DepthAccess flags) { m_DepthBuffer = resource; if ((flags | DepthAccess.Read) != 0) @@ -185,7 +185,7 @@ internal override bool HasRenderFunc() RenderGraphResourceRegistry m_Resources; RenderGraphObjectPool m_RenderGraphPool = new RenderGraphObjectPool(); List m_RenderPasses = new List(); - List m_RendererLists = new List(); + List m_RendererLists = new List(); RenderGraphDebugParams m_DebugParameters = new RenderGraphDebugParams(); RenderGraphLogger m_Logger = new RenderGraphLogger(); @@ -241,13 +241,13 @@ public void UnRegisterDebug() /// /// External RTHandle that needs to be imported. /// Optional property that allows you to specify a Shader property name to use for automatic resource binding. - /// A new RenderGraphMutableResource. - public RenderGraphMutableResource ImportTexture(RTHandle rt, int shaderProperty = 0) + /// A new TextureHandle. + public TextureHandle ImportTexture(RTHandle rt, int shaderProperty = 0) { return m_Resources.ImportTexture(rt, shaderProperty); } - public RenderGraphMutableResource ImportBackbuffer(RenderTargetIdentifier rt) + public TextureHandle ImportBackbuffer(RenderTargetIdentifier rt) { return m_Resources.ImportBackbuffer(rt); } @@ -257,8 +257,8 @@ public RenderGraphMutableResource ImportBackbuffer(RenderTargetIdentifier rt) /// /// Texture descriptor. /// Optional property that allows you to specify a Shader property name to use for automatic resource binding. - /// A new RenderGraphMutableResource. - public RenderGraphMutableResource CreateTexture(TextureDesc desc, int shaderProperty = 0) + /// A new TextureHandle. + public TextureHandle CreateTexture(TextureDesc desc, int shaderProperty = 0) { if (m_DebugParameters.tagResourceNamesWithRG) desc.name = string.Format("{0}_RenderGraph", desc.name); @@ -270,8 +270,8 @@ public RenderGraphMutableResource CreateTexture(TextureDesc desc, int shaderProp /// /// Texture from which the descriptor should be used. /// Optional property that allows you to specify a Shader property name to use for automatic resource binding. - /// A new RenderGraphMutableResource. - public RenderGraphMutableResource CreateTexture(in RenderGraphResource texture, int shaderProperty = 0) + /// A new TextureHandle. + public TextureHandle CreateTexture(TextureHandle texture, int shaderProperty = 0) { var desc = m_Resources.GetTextureResourceDesc(texture); if (m_DebugParameters.tagResourceNamesWithRG) @@ -284,13 +284,8 @@ public RenderGraphMutableResource CreateTexture(in RenderGraphResource texture, /// /// /// The input texture descriptor. - public TextureDesc GetTextureDesc(in RenderGraphResource texture) + public TextureDesc GetTextureDesc(TextureHandle texture) { - if (texture.type != RenderGraphResourceType.Texture) - { - throw new ArgumentException("Trying to retrieve a TextureDesc from a resource that is not a texture."); - } - return m_Resources.GetTextureResourceDesc(texture); } @@ -298,8 +293,8 @@ public TextureDesc GetTextureDesc(in RenderGraphResource texture) /// Creates a new Renderer List Render Graph resource. /// /// Renderer List descriptor. - /// A new RenderGraphResource. - public RenderGraphResource CreateRendererList(in RendererListDesc desc) + /// A new TextureHandle. + public RendererListHandle CreateRendererList(in RendererListDesc desc) { return m_Resources.CreateRendererList(desc); } diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilder.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilder.cs index 8e2d1e5ae13..10997c6531a 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilder.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilder.cs @@ -20,11 +20,8 @@ public struct RenderGraphBuilder : IDisposable /// The Texture resource to use as a color render target. /// Index for multiple render target usage. /// An updated resource handle to the input resource. - public RenderGraphMutableResource UseColorBuffer(in RenderGraphMutableResource input, int index) + public TextureHandle UseColorBuffer(TextureHandle input, int index) { - if (input.type != RenderGraphResourceType.Texture) - throw new ArgumentException("Trying to write to a resource that is not a texture or is invalid."); - m_RenderPass.SetColorBuffer(input, index); m_Resources.UpdateTextureFirstWrite(input, m_RenderPass.index); return input; @@ -36,11 +33,8 @@ public RenderGraphMutableResource UseColorBuffer(in RenderGraphMutableResource i /// The Texture resource to use as a depth buffer during the pass. /// Specify the access level for the depth buffer. This allows you to say whether you will read from or write to the depth buffer, or do both. /// An updated resource handle to the input resource. - public RenderGraphMutableResource UseDepthBuffer(in RenderGraphMutableResource input, DepthAccess flags) + public TextureHandle UseDepthBuffer(TextureHandle input, DepthAccess flags) { - if (input.type != RenderGraphResourceType.Texture) - throw new ArgumentException("Trying to write to a resource that is not a texture or is invalid."); - m_RenderPass.SetDepthBuffer(input, flags); if ((flags | DepthAccess.Read) != 0) m_Resources.UpdateTextureLastRead(input, m_RenderPass.index); @@ -54,10 +48,8 @@ public RenderGraphMutableResource UseDepthBuffer(in RenderGraphMutableResource i /// /// The Texture resource to read from during the pass. /// An updated resource handle to the input resource. - public RenderGraphResource ReadTexture(in RenderGraphResource input) + public TextureHandle ReadTexture(TextureHandle input) { - if (input.type != RenderGraphResourceType.Texture) - throw new ArgumentException("Trying to read a resource that is not a texture or is invalid."); m_RenderPass.resourceReadList.Add(input); m_Resources.UpdateTextureLastRead(input, m_RenderPass.index); return input; @@ -68,10 +60,8 @@ public RenderGraphResource ReadTexture(in RenderGraphResource input) /// /// The Texture resource to write to during the pass. /// An updated resource handle to the input resource. - public RenderGraphMutableResource WriteTexture(in RenderGraphMutableResource input) + public TextureHandle WriteTexture(TextureHandle input) { - if (input.type != RenderGraphResourceType.Texture) - throw new ArgumentException("Trying to write to a resource that is not a texture or is invalid."); // TODO: Manage resource "version" for debugging purpose m_RenderPass.resourceWriteList.Add(input); m_Resources.UpdateTextureFirstWrite(input, m_RenderPass.index); @@ -83,10 +73,8 @@ public RenderGraphMutableResource WriteTexture(in RenderGraphMutableResource inp /// /// The Renderer List resource to use during the pass. /// An updated resource handle to the input resource. - public RenderGraphResource UseRendererList(in RenderGraphResource input) + public RendererListHandle UseRendererList(RendererListHandle input) { - if (input.type != RenderGraphResourceType.RendererList) - throw new ArgumentException("Trying use a resource that is not a renderer list."); m_RenderPass.usedRendererListList.Add(input); return input; } diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResource.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResource.cs deleted file mode 100644 index 6fa7823c73c..00000000000 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResource.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System.Diagnostics; - -namespace UnityEngine.Experimental.Rendering.RenderGraphModule -{ - internal enum RenderGraphResourceType - { - Invalid = 0, // Don't change this. We need this to be Zero otherwise default zero initialized RenderGraphResource would have a valid Type - Texture, - RendererList - } - - /// - /// Handle to a read-only Render Graph resource. - /// - [DebuggerDisplay("{type} ({handle})")] - public struct RenderGraphResource - { - internal int handle { get; private set; } - internal RenderGraphResourceType type { get; private set; } - - internal RenderGraphResource(RenderGraphMutableResource mutableResource) - { - handle = mutableResource.handle; - type = mutableResource.type; - } - - internal RenderGraphResource(int handle, RenderGraphResourceType type) - { - this.handle = handle; - this.type = type; - } - - /// - /// Is the resource valid? - /// - /// True if the resource is valid. - public bool IsValid() { return type != RenderGraphResourceType.Invalid; } - } - - /// - /// Handle to a writable Render Graph resource. - /// - [DebuggerDisplay("{type} ({handle})")] - public struct RenderGraphMutableResource - { - internal int handle { get; private set; } - internal RenderGraphResourceType type { get; private set; } - internal int version { get; private set; } - - internal RenderGraphMutableResource(int handle, RenderGraphResourceType type) - { - this.handle = handle; - this.type = type; - this.version = 0; - } - - internal RenderGraphMutableResource(RenderGraphMutableResource other) - { - handle = other.handle; - type = other.type; - version = other.version + 1; - } - - /// - /// Build a RenderGraphResource from a RenderGraphMutableResource. - /// - /// Other render graph resource. - /// New RenderGraphResource handle. - public static implicit operator RenderGraphResource(RenderGraphMutableResource handle) - { - return new RenderGraphResource(handle); - } - - internal bool IsValid() { return type != RenderGraphResourceType.Invalid; } - } -} diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResource.cs.meta b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResource.cs.meta deleted file mode 100644 index 806b5b6066f..00000000000 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResource.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 55fda6d61a2814c4e972bb0034ccb063 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs index 8f4ee1c9642..e26172c669a 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs @@ -1,13 +1,44 @@ using System; +using System.Diagnostics; using System.Collections.Generic; using UnityEngine.Rendering; namespace UnityEngine.Experimental.Rendering.RenderGraphModule { + #region Resource Descriptors + // BEHOLD C# COPY PASTA + // Struct can't be inherited and can't have default member values + // Hence the copy paste and the ugly IsValid implementation. + + /// + /// Texture resource handle. + /// + [DebuggerDisplay("Texture ({handle})")] + public struct TextureHandle + { + bool m_IsValid; + internal int handle { get; private set; } + internal TextureHandle(int handle) { this.handle = handle; m_IsValid = true; } + public static implicit operator int(TextureHandle handle) { return handle.handle; } + public bool IsValid() => m_IsValid; + } + + /// + /// Renderer List resource handle. + /// + [DebuggerDisplay("RendererList ({handle})")] + public struct RendererListHandle + { + bool m_IsValid; + internal int handle { get; private set; } + internal RendererListHandle(int handle) { this.handle = handle; m_IsValid = true; } + public static implicit operator int(RendererListHandle handle) { return handle.handle; } + public bool IsValid() => m_IsValid; + } + /// /// The mode that determines the size of a Texture. /// - #region Resource Descriptors public enum TextureSizeMode { ///Explicit size. @@ -287,13 +318,10 @@ internal RendererListResource(in RendererListDesc desc) /// /// Handle to a texture resource. /// The RTHandle associated with the provided resource handle. - public RTHandle GetTexture(in RenderGraphResource handle) + public RTHandle GetTexture(in TextureHandle handle) { #if DEVELOPMENT_BUILD || UNITY_EDITOR - if (handle.type != RenderGraphResourceType.Texture) - throw new InvalidOperationException("Trying to access a RenderGraphResource that is not a texture."); - - var res = m_TextureResources[handle.handle]; + var res = m_TextureResources[handle]; if (res.rt == null && !res.wasReleased) throw new InvalidOperationException(string.Format("Trying to access texture \"{0}\" that was never created. Check that it was written at least once before trying to get it.", res.desc.name)); @@ -301,7 +329,7 @@ public RTHandle GetTexture(in RenderGraphResource handle) if (res.rt == null && res.wasReleased) throw new InvalidOperationException(string.Format("Trying to access texture \"{0}\" that was already released. Check that the last pass where it's read is after this one.", res.desc.name)); #endif - return m_TextureResources[handle.handle].rt; + return m_TextureResources[handle].rt; } /// @@ -309,13 +337,9 @@ public RTHandle GetTexture(in RenderGraphResource handle) /// /// Handle to a Renderer List resource. /// The Renderer List associated with the provided resource handle. - public RendererList GetRendererList(in RenderGraphResource handle) + public RendererList GetRendererList(in RendererListHandle handle) { -#if DEVELOPMENT_BUILD || UNITY_EDITOR - if (handle.type != RenderGraphResourceType.RendererList) - throw new InvalidOperationException("Trying to access a RenderGraphResource that is not a RendererList."); -#endif - return m_RendererListResources[handle.handle].rendererList; + return m_RendererListResources[handle].rendererList; } #endregion @@ -340,13 +364,13 @@ internal void SetRTHandleReferenceSize(int width, int height, MSAASamples msaaSa internal RTHandleProperties GetRTHandleProperties() { return m_RTHandleSystem.rtHandleProperties; } // Texture Creation/Import APIs are internal because creation should only go through RenderGraph - internal RenderGraphMutableResource ImportTexture(RTHandle rt, int shaderProperty = 0) + internal TextureHandle ImportTexture(RTHandle rt, int shaderProperty = 0) { int newHandle = m_TextureResources.Add(new TextureResource(rt, shaderProperty)); - return new RenderGraphMutableResource(newHandle, RenderGraphResourceType.Texture); + return new TextureHandle(newHandle); } - internal RenderGraphMutableResource ImportBackbuffer(RenderTargetIdentifier rt) + internal TextureHandle ImportBackbuffer(RenderTargetIdentifier rt) { if (m_CurrentBackbuffer != null) m_RTHandleSystem.Release(m_CurrentBackbuffer); @@ -354,18 +378,18 @@ internal RenderGraphMutableResource ImportBackbuffer(RenderTargetIdentifier rt) m_CurrentBackbuffer = m_RTHandleSystem.Alloc(rt); int newHandle = m_TextureResources.Add(new TextureResource(m_CurrentBackbuffer, 0)); - return new RenderGraphMutableResource(newHandle, RenderGraphResourceType.Texture); + return new TextureHandle(newHandle); } - internal RenderGraphMutableResource CreateTexture(in TextureDesc desc, int shaderProperty = 0) + internal TextureHandle CreateTexture(in TextureDesc desc, int shaderProperty = 0) { ValidateTextureDesc(desc); int newHandle = m_TextureResources.Add(new TextureResource(desc, shaderProperty)); - return new RenderGraphMutableResource(newHandle, RenderGraphResourceType.Texture); + return new TextureHandle(newHandle); } - internal void UpdateTextureFirstWrite(RenderGraphResource tex, int passIndex) + internal void UpdateTextureFirstWrite(TextureHandle tex, int passIndex) { ref var res = ref GetTextureResource(tex); res.firstWritePassIndex = Math.Min(passIndex, res.firstWritePassIndex); @@ -383,31 +407,31 @@ internal void UpdateTextureFirstWrite(RenderGraphResource tex, int passIndex) //res.lastReadPassIndex = Math.Max(passIndex, res.lastReadPassIndex); } - internal void UpdateTextureLastRead(RenderGraphResource tex, int passIndex) + internal void UpdateTextureLastRead(TextureHandle tex, int passIndex) { ref var res = ref GetTextureResource(tex); res.lastReadPassIndex = Math.Max(passIndex, res.lastReadPassIndex); } - ref TextureResource GetTextureResource(RenderGraphResource res) + ref TextureResource GetTextureResource(TextureHandle res) { - return ref m_TextureResources[res.handle]; + return ref m_TextureResources[res]; } - internal TextureDesc GetTextureResourceDesc(RenderGraphResource res) + internal TextureDesc GetTextureResourceDesc(TextureHandle res) { - return m_TextureResources[res.handle].desc; + return m_TextureResources[res].desc; } - internal RenderGraphResource CreateRendererList(in RendererListDesc desc) + internal RendererListHandle CreateRendererList(in RendererListDesc desc) { ValidateRendererListDesc(desc); int newHandle = m_RendererListResources.Add(new RendererListResource(desc)); - return new RenderGraphResource(newHandle, RenderGraphResourceType.RendererList); + return new RendererListHandle(newHandle); } - internal void CreateAndClearTexturesForPass(RenderGraphContext rgContext, int passIndex, List textures) + internal void CreateAndClearTexturesForPass(RenderGraphContext rgContext, int passIndex, List textures) { foreach (var rgResource in textures) { @@ -477,7 +501,7 @@ void CreateTextureForPass(ref TextureResource resource) resource.cachedHash = hashCode; } - void SetGlobalTextures(RenderGraphContext rgContext, List textures, bool bindDummyTexture) + void SetGlobalTextures(RenderGraphContext rgContext, List textures, bool bindDummyTexture) { foreach (var resource in textures) { @@ -494,17 +518,17 @@ void SetGlobalTextures(RenderGraphContext rgContext, List t } - internal void PreRenderPassSetGlobalTextures(RenderGraphContext rgContext, List textures) + internal void PreRenderPassSetGlobalTextures(RenderGraphContext rgContext, List textures) { SetGlobalTextures(rgContext, textures, false); } - internal void PostRenderPassUnbindGlobalTextures(RenderGraphContext rgContext, List textures) + internal void PostRenderPassUnbindGlobalTextures(RenderGraphContext rgContext, List textures) { SetGlobalTextures(rgContext, textures, true); } - internal void ReleaseTexturesForPass(RenderGraphContext rgContext, int passIndex, List readTextures, List writtenTextures) + internal void ReleaseTexturesForPass(RenderGraphContext rgContext, int passIndex, List readTextures, List writtenTextures) { foreach (var resource in readTextures) { @@ -538,11 +562,9 @@ internal void ReleaseTexturesForPass(RenderGraphContext rgContext, int passIndex } } - void ReleaseTextureForPass(RenderGraphResource res) + void ReleaseTextureForPass(TextureHandle res) { - Debug.Assert(res.type == RenderGraphResourceType.Texture); - - ref var resource = ref m_TextureResources[res.handle]; + ref var resource = ref m_TextureResources[res]; // This can happen because we release texture in two passes (see ReleaseTexturesForPass) and texture can be present in both passes if (resource.rt != null) @@ -638,15 +660,13 @@ bool TryGetRenderTarget(int hashCode, out RTHandle rt) return false; } - internal void CreateRendererLists(List rendererLists) + internal void CreateRendererLists(List rendererLists) { // For now we just create a simple structure // but when the proper API is available in trunk we'll kick off renderer lists creation jobs here. foreach (var rendererList in rendererLists) { - Debug.Assert(rendererList.type == RenderGraphResourceType.RendererList); - - ref var rendererListResource = ref m_RendererListResources[rendererList.handle]; + ref var rendererListResource = ref m_RendererListResources[rendererList]; ref var desc = ref rendererListResource.desc; RendererList newRendererList = RendererList.Create(desc); rendererListResource.rendererList = newRendererList; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.RenderGraph.cs index b1f3897fa76..0a8c43503cc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.RenderGraph.cs @@ -5,16 +5,16 @@ namespace UnityEngine.Rendering.HighDefinition { partial class AmbientOcclusionSystem { - RenderGraphMutableResource CreateAmbientOcclusionTexture(RenderGraph renderGraph) + TextureHandle CreateAmbientOcclusionTexture(RenderGraph renderGraph) { return renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) { enableRandomWrite = true, colorFormat = GraphicsFormat.R8_UNorm, name = "Ambient Occlusion" }, HDShaderIDs._AmbientOcclusionTexture); } - public RenderGraphResource Render(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphResource depthPyramid, RenderGraphResource motionVectors, int frameCount) + public TextureHandle Render(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthPyramid, TextureHandle motionVectors, int frameCount) { var settings = hdCamera.volumeStack.GetComponent(); - RenderGraphResource result; + TextureHandle result; // AO has side effects (as it uses an imported history buffer) // So we can't rely on automatic pass stripping. This is why we have to be explicit here. if (IsActive(hdCamera, settings)) @@ -40,12 +40,12 @@ public RenderGraphResource Render(RenderGraph renderGraph, HDCamera hdCamera, Re class RenderAOPassData { - public RenderAOParameters parameters; - public RenderGraphMutableResource packedData; - public RenderGraphResource depthPyramid; + public RenderAOParameters parameters; + public TextureHandle packedData; + public TextureHandle depthPyramid; } - RenderGraphResource RenderAO(RenderGraph renderGraph, in RenderAOParameters parameters, RenderGraphResource depthPyramid) + TextureHandle RenderAO(RenderGraph renderGraph, in RenderAOParameters parameters, TextureHandle depthPyramid) { using (var builder = renderGraph.AddRenderPass("GTAO Horizon search and integration", out var passData, ProfilingSampler.Get(HDProfileId.HorizonSSAO))) { @@ -70,23 +70,23 @@ RenderGraphResource RenderAO(RenderGraph renderGraph, in RenderAOParameters para class DenoiseAOPassData { - public RenderAOParameters parameters; - public RenderGraphResource packedData; - public RenderGraphMutableResource packedDataBlurred; - public RenderGraphResource currentHistory; - public RenderGraphMutableResource outputHistory; - public RenderGraphMutableResource denoiseOutput; - public RenderGraphResource motionVectors; + public RenderAOParameters parameters; + public TextureHandle packedData; + public TextureHandle packedDataBlurred; + public TextureHandle currentHistory; + public TextureHandle outputHistory; + public TextureHandle denoiseOutput; + public TextureHandle motionVectors; } - RenderGraphResource DenoiseAO( RenderGraph renderGraph, - in RenderAOParameters parameters, - RenderGraphResource motionVectors, - RenderGraphResource aoPackedData, - RenderGraphMutableResource currentHistory, - RenderGraphMutableResource outputHistory) + TextureHandle DenoiseAO( RenderGraph renderGraph, + in RenderAOParameters parameters, + TextureHandle motionVectors, + TextureHandle aoPackedData, + TextureHandle currentHistory, + TextureHandle outputHistory) { - RenderGraphResource denoiseOutput; + TextureHandle denoiseOutput; using (var builder = renderGraph.AddRenderPass("Denoise GTAO", out var passData)) { @@ -132,12 +132,12 @@ RenderGraphResource DenoiseAO( RenderGraph renderGraph, class UpsampleAOPassData { - public RenderAOParameters parameters; - public RenderGraphResource input; - public RenderGraphMutableResource output; + public RenderAOParameters parameters; + public TextureHandle input; + public TextureHandle output; } - RenderGraphResource UpsampleAO(RenderGraph renderGraph, in RenderAOParameters parameters, RenderGraphResource input) + TextureHandle UpsampleAO(RenderGraph renderGraph, in RenderAOParameters parameters, TextureHandle input) { using (var builder = renderGraph.AddRenderPass("Upsample GTAO", out var passData, ProfilingSampler.Get(HDProfileId.UpSampleSSAO))) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs index 9c013ec6139..e007e65f05f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs @@ -5,9 +5,9 @@ namespace UnityEngine.Rendering.HighDefinition { internal struct ShadowResult { - public RenderGraphResource punctualShadowResult; - public RenderGraphResource directionalShadowResult; - public RenderGraphResource areaShadowResult; + public TextureHandle punctualShadowResult; + public TextureHandle directionalShadowResult; + public TextureHandle areaShadowResult; } partial class HDShadowManager @@ -45,25 +45,25 @@ partial class HDShadowAtlas { class RenderShadowsPassData { - public RenderGraphMutableResource atlasTexture; - public RenderGraphMutableResource momentAtlasTexture1; - public RenderGraphMutableResource momentAtlasTexture2; - public RenderGraphMutableResource intermediateSummedAreaTexture; - public RenderGraphMutableResource summedAreaTexture; + public TextureHandle atlasTexture; + public TextureHandle momentAtlasTexture1; + public TextureHandle momentAtlasTexture2; + public TextureHandle intermediateSummedAreaTexture; + public TextureHandle summedAreaTexture; public RenderShadowsParameters parameters; public ShadowDrawingSettings shadowDrawSettings; } - RenderGraphMutableResource AllocateMomentAtlas(RenderGraph renderGraph, string name, int shaderID = 0) + TextureHandle AllocateMomentAtlas(RenderGraph renderGraph, string name, int shaderID = 0) { return renderGraph.CreateTexture(new TextureDesc(width / 2, height / 2) { colorFormat = GraphicsFormat.R32G32_SFloat, useMipMap = true, autoGenerateMips = false, name = name, enableRandomWrite = true }, shaderID); } - internal RenderGraphResource RenderShadows(RenderGraph renderGraph, CullingResults cullResults, FrameSettings frameSettings, string shadowPassName) + internal TextureHandle RenderShadows(RenderGraph renderGraph, CullingResults cullResults, FrameSettings frameSettings, string shadowPassName) { - RenderGraphResource result = new RenderGraphResource(); + TextureHandle result = new TextureHandle(); if (m_ShadowRequests.Count == 0) return result; diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs index b1c73e97753..1c5567b2a4f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs @@ -5,21 +5,21 @@ namespace UnityEngine.Rendering.HighDefinition { partial class PostProcessSystem { - public void Render( RenderGraph renderGraph, - HDCamera hdCamera, - BlueNoise blueNoise, - RenderGraphResource colorBuffer, - RenderGraphResource afterPostProcessTexture, - RenderGraphMutableResource depthBuffer, - RenderGraphMutableResource finalRT, - bool flipY) + public void Render( RenderGraph renderGraph, + HDCamera hdCamera, + BlueNoise blueNoise, + TextureHandle colorBuffer, + TextureHandle afterPostProcessTexture, + TextureHandle depthBuffer, + TextureHandle finalRT, + bool flipY) { var dynResHandler = DynamicResolutionHandler.instance; bool isSceneView = hdCamera.camera.cameraType == CameraType.SceneView; // TODO: Implement - RenderGraphResource alphaTexture = new RenderGraphResource(); + TextureHandle alphaTexture = new TextureHandle(); //// Save the alpha and apply it back into the final pass if working in fp16 //if (m_KeepAlpha) //{ @@ -255,11 +255,11 @@ public void Render( RenderGraph renderGraph, class FinalPassData { - public FinalPassParameters parameters; - public RenderGraphResource source; - public RenderGraphResource afterPostProcessTexture; - public RenderGraphResource alphaTexture; - public RenderGraphMutableResource destination; + public FinalPassParameters parameters; + public TextureHandle source; + public TextureHandle afterPostProcessTexture; + public TextureHandle alphaTexture; + public TextureHandle destination; } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs index 5fb0e9bc083..0f914613258 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs @@ -678,14 +678,14 @@ internal void ExecuteCaptureActions(RTHandle input, CommandBuffer cmd) class ExecuteCaptureActionsPassData { - public RenderGraphResource input; - public RenderGraphMutableResource tempTexture; + public TextureHandle input; + public TextureHandle tempTexture; public IEnumerator> recorderCaptureActions; public Vector2 viewportScale; public Material blitMaterial; } - internal void ExecuteCaptureActions(RenderGraph renderGraph, RenderGraphResource input) + internal void ExecuteCaptureActions(RenderGraph renderGraph, TextureHandle input) { if (m_RecorderCaptureActions == null || !m_RecorderCaptureActions.MoveNext()) return; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs index 65fd2457dad..3faca5410f7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs @@ -6,17 +6,17 @@ namespace UnityEngine.Rendering.HighDefinition { public partial class HDRenderPipeline { - RenderGraphMutableResource m_DebugFullScreenTexture; + TextureHandle m_DebugFullScreenTexture; class ResolveFullScreenDebugPassData { public DebugParameters debugParameters; - public RenderGraphMutableResource output; - public RenderGraphResource input; - public RenderGraphResource depthPyramid; + public TextureHandle output; + public TextureHandle input; + public TextureHandle depthPyramid; } - RenderGraphMutableResource ResolveFullScreenDebug(RenderGraph renderGraph, in DebugParameters debugParameters, RenderGraphResource inputFullScreenDebug, RenderGraphResource depthPyramid) + TextureHandle ResolveFullScreenDebug(RenderGraph renderGraph, in DebugParameters debugParameters, TextureHandle inputFullScreenDebug, TextureHandle depthPyramid) { using (var builder = renderGraph.AddRenderPass("ResolveFullScreenDebug", out var passData)) { @@ -43,11 +43,11 @@ RenderGraphMutableResource ResolveFullScreenDebug(RenderGraph renderGraph, in De class ResolveColorPickerDebugPassData { public DebugParameters debugParameters; - public RenderGraphMutableResource output; - public RenderGraphResource input; + public TextureHandle output; + public TextureHandle input; } - RenderGraphMutableResource ResolveColorPickerDebug(RenderGraph renderGraph, in DebugParameters debugParameters, RenderGraphResource inputColorPickerDebug) + TextureHandle ResolveColorPickerDebug(RenderGraph renderGraph, in DebugParameters debugParameters, TextureHandle inputColorPickerDebug) { using (var builder = renderGraph.AddRenderPass("ResolveColorPickerDebug", out var passData)) { @@ -72,17 +72,17 @@ RenderGraphMutableResource ResolveColorPickerDebug(RenderGraph renderGraph, in D class RenderDebugOverlayPassData { public DebugParameters debugParameters; - public RenderGraphMutableResource colorBuffer; - public RenderGraphMutableResource depthBuffer; - public RenderGraphResource depthPyramidTexture; + public TextureHandle colorBuffer; + public TextureHandle depthBuffer; + public TextureHandle depthPyramidTexture; public ShadowResult shadowTextures; } void RenderDebugOverlays( RenderGraph renderGraph, in DebugParameters debugParameters, - RenderGraphMutableResource colorBuffer, - RenderGraphMutableResource depthBuffer, - RenderGraphResource depthPyramidTexture, + TextureHandle colorBuffer, + TextureHandle depthBuffer, + TextureHandle depthPyramidTexture, in ShadowResult shadowResult) { using (var builder = renderGraph.AddRenderPass("DebugOverlay", out var passData)) @@ -122,17 +122,17 @@ class RenderLightVolumesPassData { public DebugLightVolumes.RenderLightVolumesParameters parameters; // Render target that holds the light count in floating points - public RenderGraphMutableResource lightCountBuffer; + public TextureHandle lightCountBuffer; // Render target that holds the color accumulated value - public RenderGraphMutableResource colorAccumulationBuffer; + public TextureHandle colorAccumulationBuffer; // The output texture of the debug - public RenderGraphMutableResource debugLightVolumesTexture; + public TextureHandle debugLightVolumesTexture; // Required depth texture given that we render multiple render targets - public RenderGraphMutableResource depthBuffer; - public RenderGraphMutableResource destination; + public TextureHandle depthBuffer; + public TextureHandle destination; } - static void RenderLightVolumes(RenderGraph renderGraph, in DebugParameters debugParameters, RenderGraphMutableResource destination, RenderGraphMutableResource depthBuffer, CullingResults cullResults) + static void RenderLightVolumes(RenderGraph renderGraph, in DebugParameters debugParameters, TextureHandle destination, TextureHandle depthBuffer, CullingResults cullResults) { using (var builder = renderGraph.AddRenderPass("LightVolumes", out var passData)) { @@ -167,21 +167,21 @@ static void RenderLightVolumes(RenderGraph renderGraph, in DebugParameters debug } } - RenderGraphMutableResource RenderDebug( RenderGraph renderGraph, - HDCamera hdCamera, - RenderGraphMutableResource colorBuffer, - RenderGraphMutableResource depthBuffer, - RenderGraphResource depthPyramidTexture, - RenderGraphResource fullScreenDebugTexture, - RenderGraphResource colorPickerDebugTexture, - in ShadowResult shadowResult, - CullingResults cullResults) + TextureHandle RenderDebug( RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle depthBuffer, + TextureHandle depthPyramidTexture, + TextureHandle fullScreenDebugTexture, + TextureHandle colorPickerDebugTexture, + in ShadowResult shadowResult, + CullingResults cullResults) { // We don't want any overlay for these kind of rendering if (hdCamera.camera.cameraType == CameraType.Reflection || hdCamera.camera.cameraType == CameraType.Preview) return colorBuffer; - RenderGraphMutableResource output = colorBuffer; + TextureHandle output = colorBuffer; var debugParameters = PrepareDebugParameters(hdCamera, GetDepthBufferMipChainInfo()); if (debugParameters.resolveFullScreenDebug) @@ -209,15 +209,15 @@ RenderGraphMutableResource RenderDebug( RenderGraph renderGraph, class DebugViewMaterialData { - public RenderGraphMutableResource outputColor; - public RenderGraphMutableResource outputDepth; - public RenderGraphResource opaqueRendererList; - public RenderGraphResource transparentRendererList; + public TextureHandle outputColor; + public TextureHandle outputDepth; + public RendererListHandle opaqueRendererList; + public RendererListHandle transparentRendererList; public Material debugGBufferMaterial; public FrameSettings frameSettings; } - void RenderDebugViewMaterial(RenderGraph renderGraph, CullingResults cull, HDCamera hdCamera, RenderGraphMutableResource output) + void RenderDebugViewMaterial(RenderGraph renderGraph, CullingResults cull, HDCamera hdCamera, TextureHandle output) { if (m_CurrentDebugDisplaySettings.data.materialDebugSettings.IsDebugGBufferEnabled() && hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred) { @@ -266,13 +266,13 @@ void RenderDebugViewMaterial(RenderGraph renderGraph, CullingResults cull, HDCam class PushFullScreenDebugPassData { - public RenderGraphResource input; - public RenderGraphMutableResource output; + public TextureHandle input; + public TextureHandle output; public Vector4 scaleBias; public int mipIndex; } - void PushFullScreenLightingDebugTexture(RenderGraph renderGraph, RenderGraphResource input) + void PushFullScreenLightingDebugTexture(RenderGraph renderGraph, TextureHandle input) { // In practice, this is only useful for the SingleShadow debug view. // TODO: See how we can make this nicer than a specific functions just for one case. @@ -282,7 +282,7 @@ void PushFullScreenLightingDebugTexture(RenderGraph renderGraph, RenderGraphReso } } - void PushFullScreenDebugTexture(RenderGraph renderGraph, RenderGraphResource input, FullScreenDebugMode debugMode) + void PushFullScreenDebugTexture(RenderGraph renderGraph, TextureHandle input, FullScreenDebugMode debugMode) { if (debugMode == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode) { @@ -290,7 +290,7 @@ void PushFullScreenDebugTexture(RenderGraph renderGraph, RenderGraphResource inp } } - void PushFullScreenDebugTextureMip(RenderGraph renderGraph, RenderGraphResource input, int lodCount, Vector4 scaleBias, FullScreenDebugMode debugMode) + void PushFullScreenDebugTextureMip(RenderGraph renderGraph, TextureHandle input, int lodCount, Vector4 scaleBias, FullScreenDebugMode debugMode) { if (debugMode == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode) { @@ -300,7 +300,7 @@ void PushFullScreenDebugTextureMip(RenderGraph renderGraph, RenderGraphResource } } - void PushFullScreenDebugTexture(RenderGraph renderGraph, RenderGraphResource input, Vector4 scaleBias, int mipIndex = -1) + void PushFullScreenDebugTexture(RenderGraph renderGraph, TextureHandle input, Vector4 scaleBias, int mipIndex = -1) { using (var builder = renderGraph.AddRenderPass("Push Full Screen Debug", out var passData)) { @@ -326,7 +326,7 @@ void PushFullScreenDebugTexture(RenderGraph renderGraph, RenderGraphResource inp m_FullScreenDebugPushed = true; } - RenderGraphResource PushColorPickerDebugTexture(RenderGraph renderGraph, RenderGraphResource input) + TextureHandle PushColorPickerDebugTexture(RenderGraph renderGraph, TextureHandle input) { using (var builder = renderGraph.AddRenderPass("Push To Color Picker", out var passData)) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index fbffb557fcc..6330fc20cf7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -10,11 +10,11 @@ public partial class HDRenderPipeline { struct LightingBuffers { - public RenderGraphMutableResource sssBuffer; - public RenderGraphMutableResource diffuseLightingBuffer; - public RenderGraphResource ambientOcclusionBuffer; - public RenderGraphResource ssrLightingBuffer; - public RenderGraphResource contactShadowsBuffer; + public TextureHandle sssBuffer; + public TextureHandle diffuseLightingBuffer; + public TextureHandle ambientOcclusionBuffer; + public TextureHandle ssrLightingBuffer; + public TextureHandle contactShadowsBuffer; } static void ReadLightingBuffers(LightingBuffers buffers, RenderGraphBuilder builder) @@ -27,19 +27,19 @@ static void ReadLightingBuffers(LightingBuffers buffers, RenderGraphBuilder buil class BuildGPULightListPassData { - public LightDataGlobalParameters lightDataGlobalParameters; - public ShadowGlobalParameters shadowGlobalParameters; - public LightLoopGlobalParameters lightLoopGlobalParameters; - - public BuildGPULightListParameters buildGPULightListParameters; - public BuildGPULightListResources buildGPULightListResources; - public RenderGraphResource depthBuffer; - public RenderGraphResource stencilTexture; - public RenderGraphResource[] gBuffer = new RenderGraphResource[RenderGraph.kMaxMRTCount]; - public int gBufferCount; + public LightDataGlobalParameters lightDataGlobalParameters; + public ShadowGlobalParameters shadowGlobalParameters; + public LightLoopGlobalParameters lightLoopGlobalParameters; + + public BuildGPULightListParameters buildGPULightListParameters; + public BuildGPULightListResources buildGPULightListResources; + public TextureHandle depthBuffer; + public TextureHandle stencilTexture; + public TextureHandle[] gBuffer = new TextureHandle[RenderGraph.kMaxMRTCount]; + public int gBufferCount; } - void BuildGPULightList(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphResource depthStencilBuffer, RenderGraphResource stencilBufferCopy, GBufferOutput gBuffer) + void BuildGPULightList(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthStencilBuffer, TextureHandle stencilBufferCopy, GBufferOutput gBuffer) { using (var builder = renderGraph.AddRenderPass("Build Light List", out var passData, ProfilingSampler.Get(HDProfileId.BuildLightList))) { @@ -121,7 +121,7 @@ internal ShadowResult RenderShadows(RenderGraph renderGraph, HDCamera hdCamera, return result; } - RenderGraphMutableResource CreateDiffuseLightingBuffer(RenderGraph renderGraph, bool msaa) + TextureHandle CreateDiffuseLightingBuffer(RenderGraph renderGraph, bool msaa) { return renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = !msaa, @@ -133,29 +133,29 @@ class DeferredLightingPassData public DeferredLightingParameters parameters; public DeferredLightingResources resources; - public RenderGraphMutableResource colorBuffer; - public RenderGraphMutableResource sssDiffuseLightingBuffer; - public RenderGraphResource depthBuffer; - public RenderGraphResource depthTexture; + public TextureHandle colorBuffer; + public TextureHandle sssDiffuseLightingBuffer; + public TextureHandle depthBuffer; + public TextureHandle depthTexture; public int gbufferCount; public int lightLayersTextureIndex; - public RenderGraphResource[] gbuffer = new RenderGraphResource[8]; + public TextureHandle[] gbuffer = new TextureHandle[8]; } struct LightingOutput { - public RenderGraphMutableResource colorBuffer; + public TextureHandle colorBuffer; } - LightingOutput RenderDeferredLighting( RenderGraph renderGraph, - HDCamera hdCamera, - RenderGraphMutableResource colorBuffer, - RenderGraphResource depthStencilBuffer, - RenderGraphResource depthPyramidTexture, - in LightingBuffers lightingBuffers, - in GBufferOutput gbuffer, - in ShadowResult shadowResult) + LightingOutput RenderDeferredLighting( RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle depthStencilBuffer, + TextureHandle depthPyramidTexture, + in LightingBuffers lightingBuffers, + in GBufferOutput gbuffer, + in ShadowResult shadowResult) { if (hdCamera.frameSettings.litShaderMode != LitShaderMode.Deferred) return new LightingOutput(); @@ -240,29 +240,29 @@ LightingOutput RenderDeferredLighting( RenderGraph renderGraph, class RenderSSRPassData { public RenderSSRParameters parameters; - public RenderGraphResource depthPyramid; - public RenderGraphResource colorPyramid; - public RenderGraphResource stencilBuffer; - public RenderGraphMutableResource hitPointsTexture; - public RenderGraphMutableResource lightingTexture; - public RenderGraphResource clearCoatMask; - //public RenderGraphMutableResource debugTexture; + public TextureHandle depthPyramid; + public TextureHandle colorPyramid; + public TextureHandle stencilBuffer; + public TextureHandle hitPointsTexture; + public TextureHandle lightingTexture; + public TextureHandle clearCoatMask; + //public TextureHandle debugTexture; } - RenderGraphResource RenderSSR( RenderGraph renderGraph, - HDCamera hdCamera, - RenderGraphResource normalBuffer, - RenderGraphResource motionVectorsBuffer, - RenderGraphResource depthPyramid, - RenderGraphResource stencilBuffer, - RenderGraphResource clearCoatMask) + TextureHandle RenderSSR( RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle normalBuffer, + TextureHandle motionVectorsBuffer, + TextureHandle depthPyramid, + TextureHandle stencilBuffer, + TextureHandle clearCoatMask) { var ssrBlackTexture = renderGraph.ImportTexture(TextureXR.GetBlackTexture(), HDShaderIDs._SsrLightingTexture); if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.SSR)) return ssrBlackTexture; - RenderGraphResource result; + TextureHandle result; // TODO RENDERGRAPH //var settings = hdCamera.volumeStack.GetComponent(); @@ -328,20 +328,20 @@ RenderGraphResource RenderSSR( RenderGraph renderGraph, class RenderContactShadowPassData { - public ContactShadowsParameters parameters; - public LightLoopLightData lightLoopLightData; - public TileAndClusterData tileAndClusterData; - public RenderGraphResource depthTexture; - public RenderGraphMutableResource contactShadowsTexture; - public HDShadowManager shadowManager; + public ContactShadowsParameters parameters; + public LightLoopLightData lightLoopLightData; + public TileAndClusterData tileAndClusterData; + public TextureHandle depthTexture; + public TextureHandle contactShadowsTexture; + public HDShadowManager shadowManager; } - RenderGraphResource RenderContactShadows(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphResource depthTexture, int firstMipOffsetY) + TextureHandle RenderContactShadows(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthTexture, int firstMipOffsetY) { if (!WillRenderContactShadow()) return renderGraph.ImportTexture(TextureXR.GetClearTexture(), HDShaderIDs._ContactShadowTexture); - RenderGraphResource result; + TextureHandle result; using (var builder = renderGraph.AddRenderPass("Contact Shadows", out var passData)) { builder.EnableAsyncCompute(hdCamera.frameSettings.ContactShadowsRunAsync()); @@ -376,17 +376,17 @@ RenderGraphResource RenderContactShadows(RenderGraph renderGraph, HDCamera hdCam class VolumeVoxelizationPassData { public VolumeVoxelizationParameters parameters; - public RenderGraphMutableResource densityBuffer; + public TextureHandle densityBuffer; public ComputeBuffer visibleVolumeBoundsBuffer; public ComputeBuffer visibleVolumeDataBuffer; public ComputeBuffer bigTileLightListBuffer; } - RenderGraphResource VolumeVoxelizationPass( RenderGraph renderGraph, - HDCamera hdCamera, - ComputeBuffer visibleVolumeBoundsBuffer, - ComputeBuffer visibleVolumeDataBuffer, - ComputeBuffer bigTileLightListBuffer) + TextureHandle VolumeVoxelizationPass( RenderGraph renderGraph, + HDCamera hdCamera, + ComputeBuffer visibleVolumeBoundsBuffer, + ComputeBuffer visibleVolumeDataBuffer, + ComputeBuffer bigTileLightListBuffer) { if (Fog.IsVolumetricFogEnabled(hdCamera)) { @@ -422,20 +422,20 @@ RenderGraphResource VolumeVoxelizationPass( RenderGraph renderGraph, return passData.densityBuffer; } } - return new RenderGraphResource(); + return new TextureHandle(); } class VolumetricLightingPassData { public VolumetricLightingParameters parameters; - public RenderGraphResource densityBuffer; - public RenderGraphMutableResource lightingBuffer; - public RenderGraphResource historyBuffer; - public RenderGraphMutableResource feedbackBuffer; + public TextureHandle densityBuffer; + public TextureHandle lightingBuffer; + public TextureHandle historyBuffer; + public TextureHandle feedbackBuffer; public ComputeBuffer bigTileLightListBuffer; } - RenderGraphResource VolumetricLightingPass(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphResource densityBuffer, ComputeBuffer bigTileLightListBuffer, ShadowResult shadowResult, int frameIndex) + TextureHandle VolumetricLightingPass(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle densityBuffer, ComputeBuffer bigTileLightListBuffer, ShadowResult shadowResult, int frameIndex) { if (Fog.IsVolumetricFogEnabled(hdCamera)) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs index af3bf866fdb..0198ccdcf73 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs @@ -7,24 +7,24 @@ public partial class HDRenderPipeline { class AfterPostProcessPassData { - public PostProcessParameters parameters; - public RenderGraphMutableResource afterPostProcessBuffer; - public RenderGraphMutableResource depthStencilBuffer; - public RenderGraphResource opaqueAfterPostprocessRL; - public RenderGraphResource transparentAfterPostprocessRL; + public PostProcessParameters parameters; + public TextureHandle afterPostProcessBuffer; + public TextureHandle depthStencilBuffer; + public RendererListHandle opaqueAfterPostprocessRL; + public RendererListHandle transparentAfterPostprocessRL; } - RenderGraphMutableResource RenderPostProcess( RenderGraph renderGraph, - RenderGraphResource inputColor, - RenderGraphMutableResource depthBuffer, - RenderGraphMutableResource backBuffer, - CullingResults cullResults, - HDCamera hdCamera) + TextureHandle RenderPostProcess( RenderGraph renderGraph, + TextureHandle inputColor, + TextureHandle depthBuffer, + TextureHandle backBuffer, + CullingResults cullResults, + HDCamera hdCamera) { PostProcessParameters parameters = PreparePostProcess(cullResults, hdCamera); - RenderGraphResource afterPostProcessBuffer = renderGraph.ImportTexture(TextureXR.GetBlackTexture()); - RenderGraphMutableResource dest = HDUtils.PostProcessIsFinalPass(parameters.hdCamera) ? backBuffer : renderGraph.CreateTexture( + TextureHandle afterPostProcessBuffer = renderGraph.ImportTexture(TextureXR.GetBlackTexture()); + TextureHandle dest = HDUtils.PostProcessIsFinalPass(parameters.hdCamera) ? backBuffer : renderGraph.CreateTexture( new TextureDesc(Vector2.one, true, true) { colorFormat = GetColorBufferFormat(), name = "Intermediate Postprocess buffer" }); if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.AfterPostprocess)) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index 831bf423fde..fbd32e1c005 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -23,10 +23,10 @@ void InitializePrepass(HDRenderPipelineAsset hdAsset) m_DepthResolveMaterial = CoreUtils.CreateEngineMaterial(asset.renderPipelineResources.shaders.depthValuesPS); m_GBufferOutput = new GBufferOutput(); - m_GBufferOutput.mrt = new RenderGraphResource[RenderGraph.kMaxMRTCount]; + m_GBufferOutput.mrt = new TextureHandle[RenderGraph.kMaxMRTCount]; m_DBufferOutput = new DBufferOutput(); - m_DBufferOutput.mrt = new RenderGraphResource[(int)Decal.DBufferMaterial.Count]; + m_DBufferOutput.mrt = new TextureHandle[(int)Decal.DBufferMaterial.Count]; m_DepthBufferMipChainInfo = new HDUtils.PackedMipChainInfo(); m_DepthBufferMipChainInfo.Allocate(); @@ -53,31 +53,31 @@ struct PrepassOutput { // Buffers that may be output by the prepass. // They will be MSAA depending on the frame settings - public RenderGraphMutableResource depthBuffer; - public RenderGraphMutableResource depthAsColor; - public RenderGraphMutableResource normalBuffer; - public RenderGraphMutableResource motionVectorsBuffer; + public TextureHandle depthBuffer; + public TextureHandle depthAsColor; + public TextureHandle normalBuffer; + public TextureHandle motionVectorsBuffer; // GBuffer output. Will also contain a reference to the normal buffer (as it is shared between deferred and forward objects) - public GBufferOutput gbuffer; + public GBufferOutput gbuffer; - public DBufferOutput dbuffer; + public DBufferOutput dbuffer; // Additional buffers only for MSAA - public RenderGraphMutableResource depthValuesMSAA; + public TextureHandle depthValuesMSAA; // Resolved buffers for MSAA. When MSAA is off, they will be the same reference as the buffers above. - public RenderGraphMutableResource resolvedDepthBuffer; - public RenderGraphMutableResource resolvedNormalBuffer; - public RenderGraphMutableResource resolvedMotionVectorsBuffer; + public TextureHandle resolvedDepthBuffer; + public TextureHandle resolvedNormalBuffer; + public TextureHandle resolvedMotionVectorsBuffer; // Copy of the resolved depth buffer with mip chain - public RenderGraphMutableResource depthPyramidTexture; + public TextureHandle depthPyramidTexture; - public RenderGraphResource stencilBuffer; + public TextureHandle stencilBuffer; } - RenderGraphMutableResource CreateDepthBuffer(RenderGraph renderGraph, bool msaa) + TextureHandle CreateDepthBuffer(RenderGraph renderGraph, bool msaa) { TextureDesc depthDesc = new TextureDesc(Vector2.one, true, true) { depthBufferBits = DepthBits.Depth32, bindTextureMS = msaa, enableMSAA = msaa, clearBuffer = true, name = msaa ? "CameraDepthStencilMSAA" : "CameraDepthStencil" }; @@ -85,21 +85,21 @@ RenderGraphMutableResource CreateDepthBuffer(RenderGraph renderGraph, bool msaa) return renderGraph.CreateTexture(depthDesc); } - RenderGraphMutableResource CreateNormalBuffer(RenderGraph renderGraph, bool msaa) + TextureHandle CreateNormalBuffer(RenderGraph renderGraph, bool msaa) { TextureDesc normalDesc = new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, clearBuffer = NeedClearGBuffer(), clearColor = Color.black, bindTextureMS = msaa, enableMSAA = msaa, enableRandomWrite = !msaa, name = msaa ? "NormalBufferMSAA" : "NormalBuffer" }; return renderGraph.CreateTexture(normalDesc, msaa ? HDShaderIDs._NormalTextureMS : HDShaderIDs._NormalBufferTexture); } - RenderGraphMutableResource CreateMotionVectorBuffer(RenderGraph renderGraph, bool msaa, bool clear) + TextureHandle CreateMotionVectorBuffer(RenderGraph renderGraph, bool msaa, bool clear) { TextureDesc motionVectorDesc = new TextureDesc(Vector2.one, true, true) { colorFormat = Builtin.GetMotionVectorFormat(), bindTextureMS = msaa, enableMSAA = msaa, clearBuffer = clear, clearColor = Color.clear, name = msaa ? "Motion Vectors MSAA" : "Motion Vectors" }; return renderGraph.CreateTexture(motionVectorDesc, HDShaderIDs._CameraMotionVectorsTexture); } - PrepassOutput RenderPrepass(RenderGraph renderGraph, RenderGraphMutableResource sssBuffer, CullingResults cullingResults, HDCamera hdCamera) + PrepassOutput RenderPrepass(RenderGraph renderGraph, TextureHandle sssBuffer, CullingResults cullingResults, HDCamera hdCamera) { m_IsDepthBufferCopyValid = false; @@ -181,20 +181,20 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, RenderGraphMutableResource class DepthPrepassData { - public FrameSettings frameSettings; - public bool msaaEnabled; - public bool hasDepthOnlyPrepass; - public bool renderRayTracingPrepass; + public FrameSettings frameSettings; + public bool msaaEnabled; + public bool hasDepthOnlyPrepass; + public bool renderRayTracingPrepass; - public RenderGraphMutableResource depthBuffer; - public RenderGraphMutableResource depthAsColorBuffer; - public RenderGraphMutableResource normalBuffer; + public TextureHandle depthBuffer; + public TextureHandle depthAsColorBuffer; + public TextureHandle normalBuffer; - public RenderGraphResource rendererListMRT; - public RenderGraphResource rendererListDepthOnly; + public RendererListHandle rendererListMRT; + public RendererListHandle rendererListDepthOnly; - public RenderGraphResource renderListRayTracingOpaque; - public RenderGraphResource renderListRayTracingTransparent; + public RendererListHandle renderListRayTracingOpaque; + public RendererListHandle renderListRayTracingTransparent; } // RenderDepthPrepass render both opaque and opaque alpha tested based on engine configuration. @@ -270,12 +270,12 @@ bool RenderDepthPrepass(RenderGraph renderGraph, CullingResults cull, HDCamera h class ObjectMotionVectorsPassData { - public FrameSettings frameSettings; - public RenderGraphMutableResource depthBuffer; - public RenderGraphMutableResource motionVectorsBuffer; - public RenderGraphMutableResource normalBuffer; - public RenderGraphMutableResource depthAsColorMSAABuffer; - public RenderGraphResource rendererList; + public FrameSettings frameSettings; + public TextureHandle depthBuffer; + public TextureHandle motionVectorsBuffer; + public TextureHandle normalBuffer; + public TextureHandle depthAsColorMSAABuffer; + public RendererListHandle rendererList; } void RenderObjectsMotionVectors(RenderGraph renderGraph, CullingResults cull, HDCamera hdCamera, in PrepassOutput output) @@ -311,20 +311,20 @@ void RenderObjectsMotionVectors(RenderGraph renderGraph, CullingResults cull, HD class GBufferPassData { - public FrameSettings frameSettings; - public RenderGraphResource rendererList; - public RenderGraphMutableResource[] gbufferRT = new RenderGraphMutableResource[RenderGraph.kMaxMRTCount]; - public RenderGraphMutableResource depthBuffer; + public FrameSettings frameSettings; + public RendererListHandle rendererList; + public TextureHandle[] gbufferRT = new TextureHandle[RenderGraph.kMaxMRTCount]; + public TextureHandle depthBuffer; } struct GBufferOutput { - public RenderGraphResource[] mrt; + public TextureHandle[] mrt; public int gBufferCount; public int lightLayersTextureIndex; } - void SetupGBufferTargets(RenderGraph renderGraph, HDCamera hdCamera, GBufferPassData passData, RenderGraphMutableResource sssBuffer, ref PrepassOutput prepassOutput, FrameSettings frameSettings, RenderGraphBuilder builder) + void SetupGBufferTargets(RenderGraph renderGraph, HDCamera hdCamera, GBufferPassData passData, TextureHandle sssBuffer, ref PrepassOutput prepassOutput, FrameSettings frameSettings, RenderGraphBuilder builder) { bool clearGBuffer = NeedClearGBuffer(); bool lightLayers = frameSettings.IsEnabled(FrameSettingsField.LightLayers); @@ -364,7 +364,7 @@ void SetupGBufferTargets(RenderGraph renderGraph, HDCamera hdCamera, GBufferPass // RenderGBuffer do the gbuffer pass. This is only called with deferred. If we use a depth prepass, then the depth prepass will perform the alpha testing for opaque alpha tested and we don't need to do it anymore // during Gbuffer pass. This is handled in the shader and the depth test (equal and no depth write) is done here. - void RenderGBuffer(RenderGraph renderGraph, RenderGraphMutableResource sssBuffer, ref PrepassOutput prepassOutput, CullingResults cull, HDCamera hdCamera) + void RenderGBuffer(RenderGraph renderGraph, TextureHandle sssBuffer, ref PrepassOutput prepassOutput, CullingResults cull, HDCamera hdCamera) { if (hdCamera.frameSettings.litShaderMode != LitShaderMode.Deferred) { @@ -393,15 +393,15 @@ void RenderGBuffer(RenderGraph renderGraph, RenderGraphMutableResource sssBuffer class ResolvePrepassData { - public RenderGraphMutableResource depthBuffer; - public RenderGraphMutableResource depthValuesBuffer; - public RenderGraphMutableResource normalBuffer; - public RenderGraphMutableResource motionVectorsBuffer; - public RenderGraphResource depthAsColorBufferMSAA; - public RenderGraphResource normalBufferMSAA; - public RenderGraphResource motionVectorBufferMSAA; - public Material depthResolveMaterial; - public int depthResolvePassIndex; + public TextureHandle depthBuffer; + public TextureHandle depthValuesBuffer; + public TextureHandle normalBuffer; + public TextureHandle motionVectorsBuffer; + public TextureHandle depthAsColorBufferMSAA; + public TextureHandle normalBufferMSAA; + public TextureHandle motionVectorBufferMSAA; + public Material depthResolveMaterial; + public int depthResolvePassIndex; } void ResolvePrepassBuffers(RenderGraph renderGraph, HDCamera hdCamera, ref PrepassOutput output) @@ -418,7 +418,7 @@ void ResolvePrepassBuffers(RenderGraph renderGraph, HDCamera hdCamera, ref Prepa using (var builder = renderGraph.AddRenderPass("Resolve Prepass MSAA", out var passData)) { // This texture stores a set of depth values that are required for evaluating a bunch of effects in MSAA mode (R = Samples Max Depth, G = Samples Min Depth, G = Samples Average Depth) - RenderGraphMutableResource depthValuesBuffer = renderGraph.CreateTexture( + TextureHandle depthValuesBuffer = renderGraph.CreateTexture( new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R32G32B32A32_SFloat, name = "DepthValuesBuffer" }); passData.depthResolveMaterial = m_DepthResolveMaterial; @@ -448,11 +448,11 @@ void ResolvePrepassBuffers(RenderGraph renderGraph, HDCamera hdCamera, ref Prepa class CopyDepthPassData { - public RenderGraphResource inputDepth; - public RenderGraphMutableResource outputDepth; - public GPUCopy GPUCopy; - public int width; - public int height; + public TextureHandle inputDepth; + public TextureHandle outputDepth; + public GPUCopy GPUCopy; + public int width; + public int height; } void CopyDepthBufferIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, ref PrepassOutput output) @@ -492,8 +492,8 @@ void CopyDepthBufferIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, ref Pre class ResolveStencilPassData { - public RenderGraphResource inputDepth; - public RenderGraphMutableResource resolvedStencil; + public TextureHandle inputDepth; + public TextureHandle resolvedStencil; public ComputeBuffer coarseStencilBuffer; } @@ -529,23 +529,23 @@ void ResolveStencilBufferIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, re class RenderDBufferPassData { - public RenderGraphMutableResource[] mrt = new RenderGraphMutableResource[Decal.GetMaterialDBufferCount()]; - public int dBufferCount; - public RenderGraphResource meshDecalsRendererList; - public RenderGraphMutableResource depthStencilBuffer; + public TextureHandle[] mrt = new TextureHandle[Decal.GetMaterialDBufferCount()]; + public int dBufferCount; + public RendererListHandle meshDecalsRendererList; + public TextureHandle depthStencilBuffer; } struct DBufferOutput { - public RenderGraphResource[] mrt; - public int dBufferCount; + public TextureHandle[] mrt; + public int dBufferCount; } class DBufferNormalPatchData { public DBufferNormalPatchParameters parameters; - public RenderGraphResource depthStencilBuffer; - public RenderGraphMutableResource normalBuffer; + public TextureHandle depthStencilBuffer; + public TextureHandle normalBuffer; } void SetupDBufferTargets(RenderGraph renderGraph, RenderDBufferPassData passData, bool use4RTs, ref PrepassOutput output, RenderGraphBuilder builder) @@ -654,7 +654,7 @@ void DecalNormalPatch(RenderGraph renderGraph, HDCamera hdCamera, ref PrepassOut class GenerateDepthPyramidPassData { - public RenderGraphMutableResource depthTexture; + public TextureHandle depthTexture; public HDUtils.PackedMipChainInfo mipInfo; public MipGenerator mipGenerator; } @@ -688,11 +688,11 @@ void GenerateDepthPyramid(RenderGraph renderGraph, HDCamera hdCamera, ref Prepas class CameraMotionVectorsPassData { public Material cameraMotionVectorsMaterial; - public RenderGraphMutableResource motionVectorsBuffer; - public RenderGraphResource depthTexture; + public TextureHandle motionVectorsBuffer; + public TextureHandle depthTexture; } - void RenderCameraMotionVectors(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphResource depthTexture, RenderGraphMutableResource motionVectorsBuffer) + void RenderCameraMotionVectors(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthTexture, TextureHandle motionVectorsBuffer) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.MotionVectors)) return; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index 79aee4eb9c3..3233e811c8e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -23,9 +23,9 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, || camera.cameraType == CameraType.SceneView; #endif - RenderGraphMutableResource backBuffer = m_RenderGraph.ImportBackbuffer(target.id); - RenderGraphMutableResource colorBuffer = CreateColorBuffer(m_RenderGraph, hdCamera, msaa); - RenderGraphMutableResource currentColorPyramid = m_RenderGraph.ImportTexture(hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ColorBufferMipChain), HDShaderIDs._ColorPyramidTexture); + TextureHandle backBuffer = m_RenderGraph.ImportBackbuffer(target.id); + TextureHandle colorBuffer = CreateColorBuffer(m_RenderGraph, hdCamera, msaa); + TextureHandle currentColorPyramid = m_RenderGraph.ImportTexture(hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ColorBufferMipChain), HDShaderIDs._ColorPyramidTexture); LightingBuffers lightingBuffers = new LightingBuffers(); lightingBuffers.diffuseLightingBuffer = CreateDiffuseLightingBuffer(m_RenderGraph, msaa); @@ -166,7 +166,7 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, aovRequest.PushCameraTexture(m_RenderGraph, AOVBuffers.Color, hdCamera, colorBuffer, aovBuffers); - RenderGraphMutableResource postProcessDest = RenderPostProcess(m_RenderGraph, colorBuffer, prepassOutput.depthBuffer, backBuffer, cullingResults, hdCamera); + TextureHandle postProcessDest = RenderPostProcess(m_RenderGraph, colorBuffer, prepassOutput.depthBuffer, backBuffer, cullingResults, hdCamera); // TODO RENDERGRAPH //// Copy and rescale depth buffer for XR devices @@ -238,11 +238,11 @@ static void ExecuteRenderGraph(RenderGraph renderGraph, HDCamera hdCamera, MSAAS class FinalBlitPassData { public BlitFinalCameraTextureParameters parameters; - public RenderGraphResource source; - public RenderGraphMutableResource destination; + public TextureHandle source; + public TextureHandle destination; } - void BlitFinalCameraTexture(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphResource source, RenderGraphMutableResource destination, RenderGraphResource motionVectors, RenderGraphResource normalBuffer) + void BlitFinalCameraTexture(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle source, TextureHandle destination, TextureHandle motionVectors, TextureHandle normalBuffer) { using (var builder = renderGraph.AddRenderPass("Final Blit (Dev Build Only)", out var passData)) { @@ -272,11 +272,11 @@ class SetFinalTargetPassData public Material copyDepthMaterial; public RenderTargetIdentifier finalTarget; public Rect finalViewport; - public RenderGraphResource depthBuffer; + public TextureHandle depthBuffer; public bool flipY; } - void SetFinalTarget(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphResource depthBuffer, RenderTargetIdentifier finalTarget) + void SetFinalTarget(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthBuffer, RenderTargetIdentifier finalTarget) { using (var builder = renderGraph.AddRenderPass("Set Final Target", out var passData)) { @@ -322,17 +322,17 @@ void SetFinalTarget(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphResou class ForwardPassData { - public RenderGraphResource rendererList; - public RenderGraphMutableResource[] renderTarget = new RenderGraphMutableResource[3]; - public int renderTargetCount; - public RenderGraphMutableResource depthBuffer; - public ComputeBuffer lightListBuffer; - public FrameSettings frameSettings; - public bool decalsEnabled; - public bool renderMotionVecForTransparent; + public RendererListHandle rendererList; + public TextureHandle[] renderTarget = new TextureHandle[3]; + public int renderTargetCount; + public TextureHandle depthBuffer; + public ComputeBuffer lightListBuffer; + public FrameSettings frameSettings; + public bool decalsEnabled; + public bool renderMotionVecForTransparent; } - void PrepareForwardPassData(RenderGraph renderGraph, RenderGraphBuilder builder, ForwardPassData data, bool opaque, FrameSettings frameSettings, RendererListDesc rendererListDesc, RenderGraphMutableResource depthBuffer, ShadowResult shadowResult, DBufferOutput? dbuffer = null) + void PrepareForwardPassData(RenderGraph renderGraph, RenderGraphBuilder builder, ForwardPassData data, bool opaque, FrameSettings frameSettings, RendererListDesc rendererListDesc, TextureHandle depthBuffer, ShadowResult shadowResult, DBufferOutput? dbuffer = null) { bool useFptl = frameSettings.IsEnabled(FrameSettingsField.FPTLForForwardOpaque) && opaque; @@ -356,14 +356,14 @@ void PrepareForwardPassData(RenderGraph renderGraph, RenderGraphBuilder builder, // The RenderForward pass will render the appropriate pass depends on the engine settings. In case of forward only rendering, both "Forward" pass and "ForwardOnly" pass // material will be render for both transparent and opaque. In case of deferred, both path are used for transparent but only "ForwardOnly" is use for opaque. // (Thus why "Forward" and "ForwardOnly" are exclusive, else they will render two times" - void RenderForwardOpaque( RenderGraph renderGraph, - HDCamera hdCamera, - RenderGraphMutableResource colorBuffer, - in LightingBuffers lightingBuffers, - RenderGraphMutableResource depthBuffer, - ShadowResult shadowResult, - DBufferOutput dbuffer, - CullingResults cullResults) + void RenderForwardOpaque( RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + in LightingBuffers lightingBuffers, + TextureHandle depthBuffer, + ShadowResult shadowResult, + DBufferOutput dbuffer, + CullingResults cullResults) { bool debugDisplay = m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled(); @@ -407,15 +407,15 @@ void RenderForwardOpaque( RenderGraph renderGraph, } } - void RenderForwardTransparent( RenderGraph renderGraph, - HDCamera hdCamera, - RenderGraphMutableResource colorBuffer, - RenderGraphMutableResource motionVectorBuffer, - RenderGraphMutableResource depthBuffer, - RenderGraphResource? colorPyramid, - ShadowResult shadowResult, - CullingResults cullResults, - bool preRefractionPass) + void RenderForwardTransparent( RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle motionVectorBuffer, + TextureHandle depthBuffer, + TextureHandle? colorPyramid, + ShadowResult shadowResult, + CullingResults cullResults, + bool preRefractionPass) { // If rough refraction are turned off, we render all transparents in the Transparent pass and we skip the PreRefraction one. if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.Refraction) && preRefractionPass) @@ -441,7 +441,7 @@ void RenderForwardTransparent( RenderGraph renderGraph, bool renderMotionVecForTransparent = NeedMotionVectorForTransparent(hdCamera.frameSettings); - RenderGraphMutableResource mrt1; + TextureHandle mrt1; if (renderMotionVecForTransparent) { mrt1 = motionVectorBuffer; @@ -490,7 +490,7 @@ void RenderForwardTransparent( RenderGraph renderGraph, } } - void RenderTransparentDepthPrepass(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource depthStencilBuffer, CullingResults cull) + void RenderTransparentDepthPrepass(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthStencilBuffer, CullingResults cull) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.TransparentPrepass)) return; @@ -511,7 +511,7 @@ void RenderTransparentDepthPrepass(RenderGraph renderGraph, HDCamera hdCamera, R } } - void RenderTransparentDepthPostpass(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource depthStencilBuffer, CullingResults cull) + void RenderTransparentDepthPostpass(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthStencilBuffer, CullingResults cull) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.TransparentPostpass)) return; @@ -534,12 +534,12 @@ void RenderTransparentDepthPostpass(RenderGraph renderGraph, HDCamera hdCamera, class DownsampleDepthForLowResPassData { - public Material downsampleDepthMaterial; - public RenderGraphResource depthTexture; - public RenderGraphMutableResource downsampledDepthBuffer; + public Material downsampleDepthMaterial; + public TextureHandle depthTexture; + public TextureHandle downsampledDepthBuffer; } - RenderGraphMutableResource DownsampleDepthForLowResTransparency(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphResource depthTexture) + TextureHandle DownsampleDepthForLowResTransparency(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthTexture) { using (var builder = renderGraph.AddRenderPass("Downsample Depth Buffer for Low Res Transparency", out var passData, ProfilingSampler.Get(HDProfileId.DownsampleDepth))) { @@ -569,13 +569,13 @@ RenderGraphMutableResource DownsampleDepthForLowResTransparency(RenderGraph rend class RenderLowResTransparentPassData { - public FrameSettings frameSettings; - public RenderGraphResource rendererList; - public RenderGraphMutableResource lowResBuffer; - public RenderGraphMutableResource downsampledDepthBuffer; + public FrameSettings frameSettings; + public RendererListHandle rendererList; + public TextureHandle lowResBuffer; + public TextureHandle downsampledDepthBuffer; } - RenderGraphResource RenderLowResTransparent(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource downsampledDepth, CullingResults cullingResults) + TextureHandle RenderLowResTransparent(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle downsampledDepth, CullingResults cullingResults) { using (var builder = renderGraph.AddRenderPass("Low Res Transparent", out var passData, ProfilingSampler.Get(HDProfileId.LowResTransparent))) { @@ -607,13 +607,13 @@ RenderGraphResource RenderLowResTransparent(RenderGraph renderGraph, HDCamera hd class UpsampleTransparentPassData { - public Material upsampleMaterial; - public RenderGraphMutableResource colorBuffer; - public RenderGraphResource lowResTransparentBuffer; - public RenderGraphResource downsampledDepthBuffer; + public Material upsampleMaterial; + public TextureHandle colorBuffer; + public TextureHandle lowResTransparentBuffer; + public TextureHandle downsampledDepthBuffer; } - void UpsampleTransparent(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource colorBuffer, RenderGraphResource lowResTransparentBuffer, RenderGraphResource downsampledDepthBuffer) + void UpsampleTransparent(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle colorBuffer, TextureHandle lowResTransparentBuffer, TextureHandle downsampledDepthBuffer) { using (var builder = renderGraph.AddRenderPass("Upsample Low Res Transparency", out var passData, ProfilingSampler.Get(HDProfileId.UpsampleLowResTransparent))) { @@ -643,15 +643,15 @@ void UpsampleTransparent(RenderGraph renderGraph, HDCamera hdCamera, RenderGraph } } - RenderGraphMutableResource RenderTransparency( RenderGraph renderGraph, - HDCamera hdCamera, - RenderGraphMutableResource colorBuffer, - RenderGraphMutableResource depthStencilBuffer, - RenderGraphMutableResource motionVectorsBuffer, - RenderGraphMutableResource currentColorPyramid, - RenderGraphResource depthPyramid, - ShadowResult shadowResult, - CullingResults cullingResults) + TextureHandle RenderTransparency( RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle depthStencilBuffer, + TextureHandle motionVectorsBuffer, + TextureHandle currentColorPyramid, + TextureHandle depthPyramid, + ShadowResult shadowResult, + CullingResults cullingResults) { RenderTransparentDepthPrepass(renderGraph, hdCamera, depthStencilBuffer, cullingResults); @@ -707,14 +707,14 @@ RenderGraphMutableResource RenderTransparency( RenderGraph rend class RenderForwardEmissivePassData { - public RenderGraphResource rendererList; + public RendererListHandle rendererList; } - void RenderForwardEmissive( RenderGraph renderGraph, - HDCamera hdCamera, - RenderGraphMutableResource colorBuffer, - RenderGraphMutableResource depthStencilBuffer, - CullingResults cullingResults) + void RenderForwardEmissive( RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle depthStencilBuffer, + CullingResults cullingResults) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.Decals)) return; @@ -737,11 +737,11 @@ void RenderForwardEmissive( RenderGraph renderGraph, // This is use to Display legacy shader with an error shader [System.Diagnostics.Conditional("DEVELOPMENT_BUILD"), System.Diagnostics.Conditional("UNITY_EDITOR")] - void RenderForwardError(RenderGraph renderGraph, - HDCamera hdCamera, - RenderGraphMutableResource colorBuffer, - RenderGraphMutableResource depthStencilBuffer, - CullingResults cullResults) + void RenderForwardError(RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle depthStencilBuffer, + CullingResults cullResults) { using (var builder = renderGraph.AddRenderPass("Forward Error", out var passData, ProfilingSampler.Get(HDProfileId.RenderForwardError))) { @@ -761,19 +761,19 @@ void RenderForwardError(RenderGraph renderGraph, class RenderSkyPassData { - public VisualEnvironment visualEnvironment; - public Light sunLight; - public HDCamera hdCamera; - public RenderGraphResource volumetricLighting; - public RenderGraphMutableResource colorBuffer; - public RenderGraphMutableResource depthStencilBuffer; - public RenderGraphMutableResource intermediateBuffer; - public DebugDisplaySettings debugDisplaySettings; - public SkyManager skyManager; - public int frameCount; + public VisualEnvironment visualEnvironment; + public Light sunLight; + public HDCamera hdCamera; + public TextureHandle volumetricLighting; + public TextureHandle colorBuffer; + public TextureHandle depthStencilBuffer; + public TextureHandle intermediateBuffer; + public DebugDisplaySettings debugDisplaySettings; + public SkyManager skyManager; + public int frameCount; } - void RenderSky(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource colorBuffer, RenderGraphResource volumetricLighting, RenderGraphMutableResource depthStencilBuffer, RenderGraphResource depthTexture) + void RenderSky(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle colorBuffer, TextureHandle volumetricLighting, TextureHandle depthStencilBuffer, TextureHandle depthTexture) { if (m_CurrentDebugDisplaySettings.IsMatcapViewEnabled(hdCamera)) { @@ -819,13 +819,13 @@ void RenderSky(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableRes class GenerateColorPyramidData { - public RenderGraphMutableResource colorPyramid; - public RenderGraphResource inputColor; + public TextureHandle colorPyramid; + public TextureHandle inputColor; public MipGenerator mipGenerator; public HDCamera hdCamera; } - void GenerateColorPyramid(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphResource inputColor, RenderGraphMutableResource output, bool isPreRefraction) + void GenerateColorPyramid(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle inputColor, TextureHandle output, bool isPreRefraction) { // Here we cannot rely on automatic pass pruning if the result is not read // because the output texture is imported from outside of render graph (as it is persistent) @@ -879,16 +879,16 @@ void GenerateColorPyramid(RenderGraph renderGraph, HDCamera hdCamera, RenderGrap class AccumulateDistortionPassData { - public RenderGraphMutableResource distortionBuffer; - public RenderGraphMutableResource depthStencilBuffer; - public RenderGraphResource distortionRendererList; - public FrameSettings frameSettings; + public TextureHandle distortionBuffer; + public TextureHandle depthStencilBuffer; + public RendererListHandle distortionRendererList; + public FrameSettings frameSettings; } - RenderGraphResource AccumulateDistortion( RenderGraph renderGraph, - HDCamera hdCamera, - RenderGraphMutableResource depthStencilBuffer, - CullingResults cullResults) + TextureHandle AccumulateDistortion( RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle depthStencilBuffer, + CullingResults cullResults) { using (var builder = renderGraph.AddRenderPass("Accumulate Distortion", out var passData, ProfilingSampler.Get(HDProfileId.Distortion))) { @@ -911,20 +911,20 @@ RenderGraphResource AccumulateDistortion( RenderGraph renderGr class RenderDistortionPassData { - public Material applyDistortionMaterial; - public RenderGraphResource colorPyramidBuffer; - public RenderGraphResource distortionBuffer; - public RenderGraphMutableResource colorBuffer; - public RenderGraphResource depthStencilBuffer; - public Vector4 size; + public Material applyDistortionMaterial; + public TextureHandle colorPyramidBuffer; + public TextureHandle distortionBuffer; + public TextureHandle colorBuffer; + public TextureHandle depthStencilBuffer; + public Vector4 size; } - void RenderDistortion( RenderGraph renderGraph, - HDCamera hdCamera, - RenderGraphMutableResource colorBuffer, - RenderGraphMutableResource depthStencilBuffer, - RenderGraphResource colorPyramidBuffer, - RenderGraphResource distortionBuffer) + void RenderDistortion( RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle depthStencilBuffer, + TextureHandle colorPyramidBuffer, + TextureHandle distortionBuffer) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.Distortion)) return; @@ -952,7 +952,7 @@ void RenderDistortion( RenderGraph renderGraph, } } - RenderGraphMutableResource CreateColorBuffer(RenderGraph renderGraph, HDCamera hdCamera, bool msaa) + TextureHandle CreateColorBuffer(RenderGraph renderGraph, HDCamera hdCamera, bool msaa) { return renderGraph.CreateTexture( new TextureDesc(Vector2.one, true, true) @@ -968,13 +968,13 @@ RenderGraphMutableResource CreateColorBuffer(RenderGraph renderGraph, HDCamera h class ResolveColorData { - public RenderGraphResource input; - public RenderGraphMutableResource output; - public Material resolveMaterial; - public int passIndex; + public TextureHandle input; + public TextureHandle output; + public Material resolveMaterial; + public int passIndex; } - RenderGraphMutableResource ResolveMSAAColor(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource input) + TextureHandle ResolveMSAAColor(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle input) { if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)) { @@ -1017,7 +1017,7 @@ class RenderGizmosPassData } #endif - void RenderGizmos(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource colorBuffer, GizmoSubset gizmoSubset) + void RenderGizmos(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle colorBuffer, GizmoSubset gizmoSubset) { #if UNITY_EDITOR if (UnityEditor.Handles.ShouldRenderGizmos() && diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs index fce18652309..6c743e789a5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs @@ -131,10 +131,10 @@ void EndCameraXR(RenderGraph renderGraph, HDCamera hdCamera) class RenderOcclusionMeshesPassData { public HDCamera hdCamera; - public RenderGraphMutableResource depthBuffer; + public TextureHandle depthBuffer; } - void RenderXROcclusionMeshes(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource depthBuffer) + void RenderXROcclusionMeshes(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthBuffer) { if (hdCamera.xr.enabled && m_Asset.currentPlatformRenderPipelineSettings.xrSettings.occlusionMesh) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs index 5754058c42e..aa48dd400e3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs @@ -7,7 +7,7 @@ public partial class HDRenderPipeline { // Albedo + SSS Profile and mask / Specular occlusion (when no SSS) // This will be used during GBuffer and/or forward passes. - RenderGraphMutableResource CreateSSSBuffer(RenderGraph renderGraph, bool msaa) + TextureHandle CreateSSSBuffer(RenderGraph renderGraph, bool msaa) { return renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) { @@ -24,16 +24,16 @@ RenderGraphMutableResource CreateSSSBuffer(RenderGraph renderGraph, bool msaa) class SubsurfaceScaterringPassData { public SubsurfaceScatteringParameters parameters; - public RenderGraphResource colorBuffer; - public RenderGraphResource diffuseBuffer; - public RenderGraphResource depthStencilBuffer; - public RenderGraphResource depthTexture; - public RenderGraphMutableResource cameraFilteringBuffer; - public RenderGraphResource sssBuffer; + public TextureHandle colorBuffer; + public TextureHandle diffuseBuffer; + public TextureHandle depthStencilBuffer; + public TextureHandle depthTexture; + public TextureHandle cameraFilteringBuffer; + public TextureHandle sssBuffer; } - void RenderSubsurfaceScattering(RenderGraph renderGraph, HDCamera hdCamera, RenderGraphMutableResource colorBuffer, - in LightingBuffers lightingBuffers, RenderGraphResource depthStencilBuffer, RenderGraphResource depthTexture) + void RenderSubsurfaceScattering(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle colorBuffer, + in LightingBuffers lightingBuffers, TextureHandle depthStencilBuffer, TextureHandle depthTexture) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering)) return; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequestData.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequestData.cs index c2e29e0ba08..3598d05c20b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequestData.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequestData.cs @@ -114,8 +114,8 @@ List targets class PushCameraTexturePassData { public int requestIndex; - public RenderGraphResource source; - // Not super clean to not use RenderGraphResources here. In practice it's ok because those texture are never passed back to any other render pass. + public TextureHandle source; + // Not super clean to not use TextureHandles here. In practice it's ok because those texture are never passed back to any other render pass. public List targets; } @@ -123,7 +123,7 @@ internal void PushCameraTexture( RenderGraph renderGraph, AOVBuffers aovBufferId, HDCamera camera, - RenderGraphResource source, + TextureHandle source, List targets ) { From d5696ff0f4320888aae7058d2cfcbdb105e1ef00 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 25 Feb 2020 13:36:15 +0100 Subject: [PATCH 15/92] Fixed decal normal patch pass --- .../HDRenderPipeline.Prepass.cs | 21 +++++++--- .../RenderPipeline/HDRenderPipeline.cs | 39 ++++++++++++------- 2 files changed, 40 insertions(+), 20 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index fbd32e1c005..c3bd804023c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -130,15 +130,23 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, TextureHandle sssBuffer, Cu //} //RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforeRendering); - bool renderMotionVectorAfterGBuffer = RenderDepthPrepass(renderGraph, cullingResults, hdCamera, ref result); + bool shouldRenderMotionVectorAfterGBuffer = RenderDepthPrepass(renderGraph, cullingResults, hdCamera, ref result); - if (!renderMotionVectorAfterGBuffer) + if (!shouldRenderMotionVectorAfterGBuffer) { // If objects motion vectors are enabled, this will render the objects with motion vector into the target buffers (in addition to the depth) // Note: An object with motion vector must not be render in the prepass otherwise we can have motion vector write that should have been rejected RenderObjectsMotionVectors(renderGraph, cullingResults, hdCamera, result); } + // If we have MSAA, we need to complete the motion vector buffer before buffer resolves, hence we need to run camera mv first. + // This is always fine since shouldRenderMotionVectorAfterGBuffer is always false for forward. + bool needCameraMVBeforeResolve = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); + if (needCameraMVBeforeResolve) + { + RenderCameraMotionVectors(renderGraph, hdCamera, result.depthPyramidTexture, result.resolvedMotionVectorsBuffer); + } + // TODO RENDERGRAPH //PreRenderSky(hdCamera, cmd); @@ -162,7 +170,7 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, TextureHandle sssBuffer, Cu //// Send all the geometry graphics buffer to client systems if required (must be done after the pyramid and before the transparent depth pre-pass) //SendGeometryGraphicsBuffers(cmd, hdCamera); - if (renderMotionVectorAfterGBuffer) + if (shouldRenderMotionVectorAfterGBuffer) { // See the call RenderObjectsMotionVectors() above and comment RenderObjectsMotionVectors(renderGraph, cullingResults, hdCamera, result); @@ -644,9 +652,12 @@ void DecalNormalPatch(RenderGraph renderGraph, HDCamera hdCamera, ref PrepassOut passData.depthStencilBuffer = builder.ReadTexture(output.resolvedDepthBuffer); builder.SetRenderFunc( - (DBufferNormalPatchData data, RenderGraphContext context) => + (DBufferNormalPatchData data, RenderGraphContext ctx) => { - DecalNormalPatch(hdCamera, context.cmd, context.renderContext); + DecalNormalPatch( data.parameters, + ctx.resources.GetTexture(data.depthStencilBuffer), + ctx.resources.GetTexture(data.normalBuffer), + ctx.cmd); }); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 63d7b4cf293..cad3ee5d898 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -1989,7 +1989,7 @@ AOVRequestData aovRequest RenderGBuffer(cullingResults, hdCamera, renderContext, cmd); - DecalNormalPatch(hdCamera, cmd, renderContext); + DecalNormalPatch(hdCamera, cmd); // We can now bind the normal buffer to be use by any effect m_SharedRTManager.BindNormalBuffer(cmd); @@ -3087,22 +3087,31 @@ void RenderDBuffer(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext } } - void DecalNormalPatch(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext) + void DecalNormalPatch( HDCamera hdCamera, + CommandBuffer cmd) { if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.Decals) && !hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)) // MSAA not supported { - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.DBufferNormal))) - { - var parameters = PrepareDBufferNormalPatchParameters(hdCamera); - parameters.decalNormalBufferMaterial.SetInt(HDShaderIDs._DecalNormalBufferStencilReadMask, parameters.stencilMask); - parameters.decalNormalBufferMaterial.SetInt(HDShaderIDs._DecalNormalBufferStencilRef, parameters.stencilRef); - - CoreUtils.SetRenderTarget(cmd, m_SharedRTManager.GetDepthStencilBuffer()); - cmd.SetRandomWriteTarget(1, m_SharedRTManager.GetNormalBuffer()); - cmd.DrawProcedural(Matrix4x4.identity, parameters.decalNormalBufferMaterial, 0, MeshTopology.Triangles, 3, 1); - cmd.ClearRandomWriteTargets(); - } + var parameters = PrepareDBufferNormalPatchParameters(hdCamera); + DecalNormalPatch(parameters, m_SharedRTManager.GetDepthStencilBuffer(), m_SharedRTManager.GetNormalBuffer(), cmd); + } + } + + static void DecalNormalPatch( DBufferNormalPatchParameters parameters, + RTHandle depthStencilBuffer, + RTHandle normalBuffer, + CommandBuffer cmd) + { + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.DBufferNormal))) + { + parameters.decalNormalBufferMaterial.SetInt(HDShaderIDs._DecalNormalBufferStencilReadMask, parameters.stencilMask); + parameters.decalNormalBufferMaterial.SetInt(HDShaderIDs._DecalNormalBufferStencilRef, parameters.stencilRef); + + CoreUtils.SetRenderTarget(cmd, depthStencilBuffer); + cmd.SetRandomWriteTarget(1, normalBuffer); + cmd.DrawProcedural(Matrix4x4.identity, parameters.decalNormalBufferMaterial, 0, MeshTopology.Triangles, 3, 1); + cmd.ClearRandomWriteTargets(); } } @@ -3870,7 +3879,7 @@ void RenderSSRTransparent(HDCamera hdCamera, CommandBuffer cmd, ScriptableRender var parameters = PrepareSSRParameters(hdCamera); RenderSSR(parameters, m_SharedRTManager.GetDepthTexture(), m_SsrHitPointTexture, m_SharedRTManager.GetStencilBuffer(), TextureXR.GetBlackTexture(), previousColorPyramid, m_SsrLightingTexture, cmd, renderContext); - // If color pyramid was not valid, we bind a black texture + // If color pyramid was not valid, we bind a black texture if (!hdCamera.colorPyramidHistoryIsValid) { cmd.SetGlobalTexture(HDShaderIDs._SsrLightingTexture, TextureXR.GetClearTexture()); @@ -3996,7 +4005,7 @@ void ApplyDebugDisplaySettings(HDCamera hdCamera, CommandBuffer cmd) CoreUtils.SetKeyword(cmd, "DEBUG_DISPLAY", debugDisplayEnabledOrSceneLightingDisabled); // Setting this all the time due to a strange bug that either reports a (globally) bound texture as not bound or where SetGlobalTexture doesn't behave as expected. - // As a workaround we bind it regardless of debug display. Eventually with + // As a workaround we bind it regardless of debug display. Eventually with cmd.SetGlobalTexture(HDShaderIDs._DebugMatCapTexture, defaultResources.textures.matcapTex); if (debugDisplayEnabledOrSceneLightingDisabled || From 6a15b4b9a871c4c099cdc25d33c9916ae8f703b8 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 25 Feb 2020 16:36:29 +0100 Subject: [PATCH 16/92] Fixed stencil resolve render pass --- .../HDRenderPipeline.Prepass.cs | 12 ++++-- .../RenderPipeline/HDRenderPipeline.cs | 42 +++++++++++++------ 2 files changed, 39 insertions(+), 15 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index c3bd804023c..43a67ed5a1d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -176,9 +176,13 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, TextureHandle sssBuffer, Cu RenderObjectsMotionVectors(renderGraph, cullingResults, hdCamera, result); } - RenderCameraMotionVectors(renderGraph, hdCamera, result.depthPyramidTexture, result.resolvedMotionVectorsBuffer); + // In case we don't have MSAA, we always run camera motion vectors when is safe to assume Object MV are rendered + if (!needCameraMVBeforeResolve) + { + RenderCameraMotionVectors(renderGraph, hdCamera, result.depthPyramidTexture, result.resolvedMotionVectorsBuffer); + } - // TODO RENDERGRAPH + // TODO RENDERGRAPH / Probably need to move this somewhere else. //RenderTransparencyOverdraw(cullingResults, hdCamera, renderContext, cmd); ResolveStencilBufferIfNeeded(renderGraph, hdCamera, ref result); @@ -500,6 +504,7 @@ void CopyDepthBufferIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, ref Pre class ResolveStencilPassData { + public BuildCoarseStencilAndResolveParameters parameters; public TextureHandle inputDepth; public TextureHandle resolvedStencil; public ComputeBuffer coarseStencilBuffer; @@ -509,6 +514,7 @@ void ResolveStencilBufferIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, re { using (var builder = renderGraph.AddRenderPass("Resolve Stencil", out var passData, ProfilingSampler.Get(HDProfileId.ResolveStencilBuffer))) { + passData.parameters = PrepareBuildCoarseStencilParameters(hdCamera); passData.inputDepth = output.depthBuffer; passData.coarseStencilBuffer = m_SharedRTManager.GetCoarseStencilBuffer(); passData.resolvedStencil = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R8G8_UInt, enableRandomWrite = true, name = "StencilBufferResolved" })); @@ -516,7 +522,7 @@ void ResolveStencilBufferIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, re (ResolveStencilPassData data, RenderGraphContext context) => { var res = context.resources; - BuildCoarseStencilAndResolveIfNeeded(hdCamera, + BuildCoarseStencilAndResolveIfNeeded(data.parameters, res.GetTexture(data.inputDepth), res.GetTexture(data.resolvedStencil), data.coarseStencilBuffer, diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index cad3ee5d898..c7aa1afcde9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -1048,10 +1048,35 @@ void CopyDepthBufferIfNeeded(HDCamera hdCamera, CommandBuffer cmd) } } - void BuildCoarseStencilAndResolveIfNeeded(HDCamera hdCamera, RTHandle depthStencilBuffer, RTHandle resolvedStencilBuffer, ComputeBuffer coarseStencilBuffer, CommandBuffer cmd) + struct BuildCoarseStencilAndResolveParameters + { + public HDCamera hdCamera; + public ComputeShader resolveStencilCS; + } + + BuildCoarseStencilAndResolveParameters PrepareBuildCoarseStencilParameters(HDCamera hdCamera) + { + var parameters = new BuildCoarseStencilAndResolveParameters(); + parameters.hdCamera = hdCamera; + parameters.resolveStencilCS = defaultResources.shaders.resolveStencilCS; + return parameters; + } + + void BuildCoarseStencilAndResolveIfNeeded(HDCamera hdCamera, CommandBuffer cmd) + { + var parameters = PrepareBuildCoarseStencilParameters(hdCamera); + bool msaaEnabled = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); + BuildCoarseStencilAndResolveIfNeeded(parameters, m_SharedRTManager.GetDepthStencilBuffer(msaaEnabled), + msaaEnabled ? m_SharedRTManager.GetStencilBuffer(msaaEnabled) : null, + m_SharedRTManager.GetCoarseStencilBuffer(), cmd); + + } + + static void BuildCoarseStencilAndResolveIfNeeded(BuildCoarseStencilAndResolveParameters parameters, RTHandle depthStencilBuffer, RTHandle resolvedStencilBuffer, ComputeBuffer coarseStencilBuffer, CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.CoarseStencilGeneration))) { + var hdCamera = parameters.hdCamera; bool MSAAEnabled = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); // The following features require a copy of the stencil, if none are active, no need to do the resolve. @@ -1062,7 +1087,7 @@ void BuildCoarseStencilAndResolveIfNeeded(HDCamera hdCamera, RTHandle depthStenc // We need the resolve only with msaa resolveIsNecessary = resolveIsNecessary && MSAAEnabled; - ComputeShader cs = defaultResources.shaders.resolveStencilCS; + ComputeShader cs = parameters.resolveStencilCS; int kernel = SampleCountToPassIndex(MSAAEnabled ? hdCamera.msaaSamples : MSAASamples.None); kernel = resolveIsNecessary ? kernel + 3 : kernel; // We have a different variant if we need to resolve to non-MSAA stencil int coarseStencilWidth = HDUtils.DivRoundUp(hdCamera.actualWidth, 8); @@ -2050,10 +2075,7 @@ AOVRequestData aovRequest CoreUtils.SetRenderTarget(cmd, m_ContactShadowBuffer, ClearFlag.Color, Color.clear); } - bool msaaEnabled = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); - BuildCoarseStencilAndResolveIfNeeded(hdCamera, m_SharedRTManager.GetDepthStencilBuffer(msaaEnabled), - msaaEnabled ? m_SharedRTManager.GetStencilBuffer(msaaEnabled) : null, - m_SharedRTManager.GetCoarseStencilBuffer(), cmd); + BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd); hdCamera.xr.StopSinglePass(cmd, camera, renderContext); @@ -2217,9 +2239,7 @@ void Callback(CommandBuffer c, HDCamera cam) if(hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering)) { // We need htile for SSS, but we don't need to resolve again - BuildCoarseStencilAndResolveIfNeeded(hdCamera, m_SharedRTManager.GetDepthStencilBuffer(msaaEnabled), - msaaEnabled ? m_SharedRTManager.GetStencilBuffer(msaaEnabled) : null, - m_SharedRTManager.GetCoarseStencilBuffer(), cmd); + BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd); } // SSS pass here handle both SSS material from deferred and forward @@ -2243,9 +2263,7 @@ void Callback(CommandBuffer c, HDCamera cam) if(hdCamera.frameSettings.IsEnabled(FrameSettingsField.TransparentSSR)) { // We need htile for SSS, but we don't need to resolve again - BuildCoarseStencilAndResolveIfNeeded(hdCamera, m_SharedRTManager.GetDepthStencilBuffer(msaaEnabled), - msaaEnabled ? m_SharedRTManager.GetStencilBuffer(msaaEnabled) : null, - m_SharedRTManager.GetCoarseStencilBuffer(), cmd); + BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd); } RenderSSRTransparent(hdCamera, cmd, renderContext); From 45ce8c0f45e108da4554d738132d60b3c3e00ef6 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 25 Feb 2020 17:02:51 +0100 Subject: [PATCH 17/92] Fixed RenderDBuffer render pass function capturing variables. --- .../HDRenderPipeline.Prepass.cs | 18 ++-- .../RenderPipeline/HDRenderPipeline.cs | 97 +++++++++++-------- 2 files changed, 63 insertions(+), 52 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index 43a67ed5a1d..dc03473d129 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -262,7 +262,7 @@ bool RenderDepthPrepass(RenderGraph renderGraph, CullingResults cull, HDCamera h if (data.msaaEnabled) mrt[1] = context.resources.GetTexture(data.depthAsColorBuffer); - bool useRayTracing = passData.frameSettings.IsEnabled(FrameSettingsField.RayTracing); + bool useRayTracing = data.frameSettings.IsEnabled(FrameSettingsField.RayTracing); RenderDepthPrepass(context.renderContext, context.cmd, data.frameSettings , mrt @@ -543,10 +543,11 @@ void ResolveStencilBufferIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, re class RenderDBufferPassData { - public TextureHandle[] mrt = new TextureHandle[Decal.GetMaterialDBufferCount()]; - public int dBufferCount; - public RendererListHandle meshDecalsRendererList; - public TextureHandle depthStencilBuffer; + public RenderDBufferParameters parameters; + public TextureHandle[] mrt = new TextureHandle[Decal.GetMaterialDBufferCount()]; + public int dBufferCount; + public RendererListHandle meshDecalsRendererList; + public TextureHandle depthStencilBuffer; } struct DBufferOutput @@ -610,6 +611,7 @@ void RenderDBuffer(RenderGraph renderGraph, HDCamera hdCamera, ref PrepassOutput using (var builder = renderGraph.AddRenderPass("DBufferRender", out var passData, ProfilingSampler.Get(HDProfileId.DBufferRender))) { + passData.parameters = PrepareRenderDBufferParameters(); passData.meshDecalsRendererList = builder.UseRendererList(renderGraph.CreateRendererList(PrepareMeshDecalsRendererList(cullingResults, hdCamera, use4RTs))); SetupDBufferTargets(renderGraph, passData, use4RTs, ref output, builder); @@ -629,14 +631,10 @@ void RenderDBuffer(RenderGraph renderGraph, HDCamera hdCamera, ref PrepassOutput rti[i] = rt[i]; } - RenderDBuffer(data.dBufferCount == 4, + RenderDBuffer( data.parameters, rti, rt, resources.GetTexture(data.depthStencilBuffer), - m_DbufferManager.propertyMaskBuffer, - m_DbufferManager.clearPropertyMaskBufferShader, - m_DbufferManager.clearPropertyMaskBufferKernel, - m_DbufferManager.propertyMaskBufferSize, resources.GetRendererList(data.meshDecalsRendererList), context.renderContext, context.cmd); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index c7aa1afcde9..58d9a86d004 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -3087,15 +3087,12 @@ void RenderDBuffer(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.DBufferRender))) { + var parameters = PrepareRenderDBufferParameters(); bool use4RTs = m_Asset.currentPlatformRenderPipelineSettings.decalSettings.perChannelMask; - RenderDBuffer( use4RTs, + RenderDBuffer( parameters, m_DbufferManager.GetBuffersRTI(), m_DbufferManager.GetRTHandles(), m_SharedRTManager.GetDepthStencilBuffer(), - m_DbufferManager.propertyMaskBuffer, - m_DbufferManager.clearPropertyMaskBufferShader, - m_DbufferManager.clearPropertyMaskBufferKernel, - m_DbufferManager.propertyMaskBufferSize, RendererList.Create(PrepareMeshDecalsRendererList(cullingResults, hdCamera, use4RTs)), renderContext, cmd); @@ -3116,6 +3113,34 @@ void DecalNormalPatch( HDCamera hdCamera, } } + struct DBufferNormalPatchParameters + { + public Material decalNormalBufferMaterial; + public int stencilRef; + public int stencilMask; + } + + DBufferNormalPatchParameters PrepareDBufferNormalPatchParameters(HDCamera hdCamera) + { + var parameters = new DBufferNormalPatchParameters(); + parameters.decalNormalBufferMaterial = m_DecalNormalBufferMaterial; + switch (hdCamera.frameSettings.litShaderMode) + { + case LitShaderMode.Forward: // in forward rendering all pixels that decals wrote into have to be composited + parameters.stencilMask = (int)StencilUsage.Decals; + parameters.stencilRef = (int)StencilUsage.Decals; + break; + case LitShaderMode.Deferred: // in deferred rendering only pixels affected by both forward materials and decals need to be composited + parameters.stencilMask = (int)StencilUsage.Decals | (int)StencilUsage.RequiresDeferredLighting; + parameters.stencilRef = (int)StencilUsage.Decals; + break; + default: + throw new ArgumentOutOfRangeException("Unknown ShaderLitMode"); + } + + return parameters; + } + static void DecalNormalPatch( DBufferNormalPatchParameters parameters, RTHandle depthStencilBuffer, RTHandle normalBuffer, @@ -3160,14 +3185,30 @@ static void PushDecalsGlobalParams(HDCamera hdCamera, CommandBuffer cmd) static RenderTargetIdentifier[] m_Dbuffer3RtIds = new RenderTargetIdentifier[3]; - static void RenderDBuffer( bool use4RTs, + struct RenderDBufferParameters + { + public bool use4RTs; + public ComputeBuffer propertyMaskBuffer; + public ComputeShader clearPropertyMaskBufferCS; + public int clearPropertyMaskBufferKernel; + public int propertyMaskBufferSize; + } + + RenderDBufferParameters PrepareRenderDBufferParameters() + { + var parameters = new RenderDBufferParameters(); + parameters.use4RTs = m_Asset.currentPlatformRenderPipelineSettings.decalSettings.perChannelMask; + parameters.propertyMaskBuffer = m_DbufferManager.propertyMaskBuffer; + parameters.clearPropertyMaskBufferCS = m_DbufferManager.clearPropertyMaskBufferShader; + parameters.clearPropertyMaskBufferKernel = m_DbufferManager.clearPropertyMaskBufferKernel; + parameters.propertyMaskBufferSize = m_DbufferManager.propertyMaskBufferSize; + return parameters; + } + + static void RenderDBuffer( in RenderDBufferParameters parameters, RenderTargetIdentifier[] mrt, RTHandle[] rtHandles, RTHandle depthStencilBuffer, - ComputeBuffer propertyMaskBuffer, - ComputeShader propertyMaskClearShader, - int propertyMaskClearShaderKernel, - int propertyMaskBufferSize, RendererList meshDecalsRendererList, ScriptableRenderContext renderContext, CommandBuffer cmd) @@ -3184,7 +3225,7 @@ static void RenderDBuffer( bool use4RTs, CoreUtils.SetRenderTarget(cmd, rtHandles[1], ClearFlag.Color, clearColorNormal); CoreUtils.SetRenderTarget(cmd, rtHandles[2], ClearFlag.Color, clearColor); - if (use4RTs) + if (parameters.use4RTs) { CoreUtils.SetRenderTarget(cmd, rtHandles[3], ClearFlag.Color, clearColorAOSBlend); // this actually sets the MRTs and HTile RWTexture, this is done separately because we do not have an api to clear MRTs to different colors @@ -3201,9 +3242,9 @@ static void RenderDBuffer( bool use4RTs, } // clear decal property mask buffer - cmd.SetComputeBufferParam(propertyMaskClearShader, propertyMaskClearShaderKernel, HDShaderIDs._DecalPropertyMaskBuffer, propertyMaskBuffer); - cmd.DispatchCompute(propertyMaskClearShader, propertyMaskClearShaderKernel, propertyMaskBufferSize / 64, 1, 1); - cmd.SetRandomWriteTarget(use4RTs ? 4 : 3, propertyMaskBuffer); + cmd.SetComputeBufferParam(parameters.clearPropertyMaskBufferCS, parameters.clearPropertyMaskBufferKernel, HDShaderIDs._DecalPropertyMaskBuffer, parameters.propertyMaskBuffer); + cmd.DispatchCompute(parameters.clearPropertyMaskBufferCS, parameters.clearPropertyMaskBufferKernel, parameters.propertyMaskBufferSize / 64, 1, 1); + cmd.SetRandomWriteTarget(parameters.use4RTs ? 4 : 3, parameters.propertyMaskBuffer); HDUtils.DrawRendererList(renderContext, cmd, meshDecalsRendererList); DecalSystem.instance.RenderIntoDBuffer(cmd); @@ -3211,34 +3252,6 @@ static void RenderDBuffer( bool use4RTs, cmd.ClearRandomWriteTargets(); } - struct DBufferNormalPatchParameters - { - public Material decalNormalBufferMaterial; - public int stencilRef; - public int stencilMask; - } - - DBufferNormalPatchParameters PrepareDBufferNormalPatchParameters(HDCamera hdCamera) - { - var parameters = new DBufferNormalPatchParameters(); - parameters.decalNormalBufferMaterial = m_DecalNormalBufferMaterial; - switch (hdCamera.frameSettings.litShaderMode) - { - case LitShaderMode.Forward: // in forward rendering all pixels that decals wrote into have to be composited - parameters.stencilMask = (int)StencilUsage.Decals; - parameters.stencilRef = (int)StencilUsage.Decals; - break; - case LitShaderMode.Deferred: // in deferred rendering only pixels affected by both forward materials and decals need to be composited - parameters.stencilMask = (int)StencilUsage.Decals | (int)StencilUsage.RequiresDeferredLighting; - parameters.stencilRef = (int)StencilUsage.Decals; - break; - default: - throw new ArgumentOutOfRangeException("Unknown ShaderLitMode"); - } - - return parameters; - } - RendererListDesc PrepareForwardEmissiveRendererList(CullingResults cullResults, HDCamera hdCamera) { var result = new RendererListDesc(m_DecalsEmissivePassNames, cullResults, hdCamera.camera) From 346618c2a354ff44bfdf0ee028cb281322239591 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 25 Feb 2020 17:44:02 +0100 Subject: [PATCH 18/92] Fixed wrong variable capture and restored ClearLightList to the render graph implementation of BuildGPULightList --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 70 +++++++++++-------- .../HDRenderPipeline.LightLoop.cs | 5 +- 2 files changed, 43 insertions(+), 32 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index f969fa4d690..f86fa3e7718 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -2678,6 +2678,10 @@ struct BuildGPULightListParameters public Vector4 screenSize; public int msaaSamples; + // Clear Light lists + public ComputeShader clearLightListCS; + public int clearLightListKernel; + // Screen Space AABBs public ComputeShader screenSpaceAABBShader; public int screenSpaceAABBKernel; @@ -2732,6 +2736,37 @@ BuildGPULightListResources PrepareBuildGPULightListResources(TileAndClusterData return resources; } + static void ClearLightList(in BuildGPULightListParameters parameters, CommandBuffer cmd, ComputeBuffer bufferToClear) + { + cmd.SetComputeBufferParam(parameters.clearLightListCS, parameters.clearLightListKernel, HDShaderIDs._LightListToClear, bufferToClear); + cmd.SetComputeIntParam(parameters.clearLightListCS, HDShaderIDs._LightListEntries, bufferToClear.count); + + int groupSize = 64; + cmd.DispatchCompute(parameters.clearLightListCS, parameters.clearLightListKernel, (bufferToClear.count + groupSize - 1) / groupSize, 1, 1); + } + + static void ClearLightLists( in BuildGPULightListParameters parameters, + in BuildGPULightListResources resources, + CommandBuffer cmd) + { + if (parameters.clearLightLists && !parameters.runLightList) + { + // Note we clear the whole content and not just the header since it is fast enough, happens only in one frame and is a bit more robust + // to changes to the inner workings of the lists. + // Also, we clear all the lists and to be resilient to changes in pipeline. + ClearLightList(parameters, cmd, resources.tileAndClusterData.bigTileLightList); + ClearLightList(parameters, cmd, resources.tileAndClusterData.lightList); + ClearLightList(parameters, cmd, resources.tileAndClusterData.perVoxelOffset); + + // No need to clear it anymore until we start and stop running light list building. + resources.tileAndClusterData.listsAreClear = true; + } + else if (parameters.runLightList) + { + resources.tileAndClusterData.listsAreClear = false; + } + } + // generate screen-space AABBs (used for both fptl and clustered). static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { @@ -3031,6 +3066,10 @@ BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera hdCamera bool isProjectionOblique = GeometryUtils.IsProjectionMatrixOblique(m_LightListProjMatrices[0]); + // Clear light lsts + parameters.clearLightListCS = defaultResources.shaders.clearLightListsCS; + parameters.clearLightListKernel = parameters.clearLightListCS.FindKernel("ClearList"); + // Screen space AABB parameters.screenSpaceAABBShader = buildScreenAABBShader; parameters.screenSpaceAABBKernel = isProjectionOblique ? s_GenAABBKernel_Oblique : s_GenAABBKernel; @@ -3083,19 +3122,6 @@ BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera hdCamera return parameters; } - void ClearLightList(HDCamera camera, CommandBuffer cmd, ComputeBuffer bufferToClear) - { - // We clear them all to be on the safe side when switching pipes. - var cs = defaultResources.shaders.clearLightListsCS; - var kernel = cs.FindKernel("ClearList"); - - cmd.SetComputeBufferParam(cs, kernel, HDShaderIDs._LightListToClear, bufferToClear); - cmd.SetComputeIntParam(cs, HDShaderIDs._LightListEntries, bufferToClear.count); - - int groupSize = 64; - cmd.DispatchCompute(cs, kernel, (bufferToClear.count + groupSize - 1) / groupSize, 1, 1); - } - void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BuildLightList))) @@ -3109,23 +3135,7 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) bool tileFlagsWritten = false; - if(parameters.clearLightLists && !parameters.runLightList) - { - // Note we clear the whole content and not just the header since it is fast enough, happens only in one frame and is a bit more robust - // to changes to the inner workings of the lists. - // Also, we clear all the lists and to be resilient to changes in pipeline. - ClearLightList(hdCamera, cmd, resources.tileAndClusterData.bigTileLightList); - ClearLightList(hdCamera, cmd, resources.tileAndClusterData.lightList); - ClearLightList(hdCamera, cmd, resources.tileAndClusterData.perVoxelOffset); - - // No need to clear it anymore until we start and stop running light list building. - m_TileAndClusterData.listsAreClear = true; - } - else if(parameters.runLightList) - { - m_TileAndClusterData.listsAreClear = false; - } - + ClearLightLists(parameters, resources, cmd); GenerateLightsScreenSpaceAABBs(parameters, resources, cmd); BigTilePrepass(parameters, resources, cmd); BuildPerTileLightList(parameters, resources, ref tileFlagsWritten, cmd); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 6330fc20cf7..d694c20afbc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -67,13 +67,14 @@ void BuildGPULightList(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle data.buildGPULightListResources.depthBuffer = context.resources.GetTexture(data.depthBuffer); data.buildGPULightListResources.stencilTexture = context.resources.GetTexture(data.stencilTexture); - if (passData.buildGPULightListParameters.computeMaterialVariants && passData.buildGPULightListParameters.enableFeatureVariants) + if (data.buildGPULightListParameters.computeMaterialVariants && data.buildGPULightListParameters.enableFeatureVariants) { data.buildGPULightListResources.gBuffer = context.renderGraphPool.GetTempArray(data.gBufferCount); for (int i = 0; i < data.gBufferCount; ++i) data.buildGPULightListResources.gBuffer[i] = context.resources.GetTexture(data.gBuffer[i]); } + ClearLightLists(data.buildGPULightListParameters, data.buildGPULightListResources, context.cmd); GenerateLightsScreenSpaceAABBs(data.buildGPULightListParameters, data.buildGPULightListResources, context.cmd); BigTilePrepass(data.buildGPULightListParameters, data.buildGPULightListResources, context.cmd); BuildPerTileLightList(data.buildGPULightListParameters, data.buildGPULightListResources, ref tileFlagsWritten, context.cmd); @@ -81,7 +82,7 @@ void BuildGPULightList(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle BuildDispatchIndirectArguments(data.buildGPULightListParameters, data.buildGPULightListResources, tileFlagsWritten, context.cmd); - // WARNING: Note that the three set of variables are bound here, but it should be handled differently. + // WARNING: Note that the three sets of variables are bound here, but it should be handled differently. PushLightDataGlobalParams(data.lightDataGlobalParameters, context.cmd); PushShadowGlobalParams(data.shadowGlobalParameters, context.cmd); PushLightLoopGlobalParams(data.lightLoopGlobalParameters, context.cmd); From e7461e63e381c0c5eb8194a0df906f0dc060ffea Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 3 Mar 2020 14:25:35 +0100 Subject: [PATCH 19/92] Various fixes of things that diverged compared to regular path. --- .../SubsurfaceScatteringManager.cs | 2 + .../HDRenderPipeline.LightLoop.cs | 12 ++++-- .../HDRenderPipeline.Prepass.cs | 4 +- .../HDRenderPipeline.RenderGraph.cs | 41 ++++++++++++++----- .../HDRenderPipeline.SubsurfaceScattering.cs | 7 +++- .../RenderPipeline/HDRenderPipeline.cs | 32 +++++---------- 6 files changed, 60 insertions(+), 38 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index b0289ca69c3..ba52e95a4ef 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -300,6 +300,8 @@ void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle c if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering)) return; + BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd); + var settings = hdCamera.volumeStack.GetComponent(); // If ray tracing is enabled for the camera, if the volume override is active and if the RAS is built, we want to do ray traced SSS diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index d694c20afbc..6354f3e1af4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -82,7 +82,7 @@ void BuildGPULightList(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle BuildDispatchIndirectArguments(data.buildGPULightListParameters, data.buildGPULightListResources, tileFlagsWritten, context.cmd); - // WARNING: Note that the three sets of variables are bound here, but it should be handled differently. + // TODO RENDERGRAPH WARNING: Note that the three sets of variables are bound here, but it should be handled differently. PushLightDataGlobalParams(data.lightDataGlobalParameters, context.cmd); PushShadowGlobalParams(data.shadowGlobalParameters, context.cmd); PushLightLoopGlobalParams(data.lightLoopGlobalParameters, context.cmd); @@ -267,7 +267,8 @@ TextureHandle RenderSSR( RenderGraph renderGraph, // TODO RENDERGRAPH //var settings = hdCamera.volumeStack.GetComponent(); - //if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value) + //bool usesRaytracedReflections = hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value; + //if (usesRaytracedReflections) //{ // hdCamera.xr.StartSinglePass(cmd, hdCamera.camera, renderContext); // RenderRayTracedReflections(hdCamera, cmd, m_SsrLightingTexture, renderContext, m_FrameCount); @@ -303,7 +304,7 @@ TextureHandle RenderSSR( RenderGraph renderGraph, (RenderSSRPassData data, RenderGraphContext context) => { var res = context.resources; - RenderSSR(data.parameters, + RenderSSR( data.parameters, res.GetTexture(data.depthPyramid), res.GetTexture(data.hitPointsTexture), res.GetTexture(data.stencilBuffer), @@ -323,6 +324,9 @@ TextureHandle RenderSSR( RenderGraph renderGraph, } } + // TODO RENDERGRAPH + //cmd.SetGlobalInt(HDShaderIDs._UseRayTracedReflections, usesRaytracedReflections ? 1 : 0); + PushFullScreenDebugTexture(renderGraph, result, FullScreenDebugMode.ScreenSpaceReflections); return result; } @@ -412,7 +416,7 @@ TextureHandle VolumeVoxelizationPass( RenderGraph renderGraph, builder.SetRenderFunc( (VolumeVoxelizationPassData data, RenderGraphContext ctx) => { - VolumeVoxelizationPass(data.parameters, + VolumeVoxelizationPass( data.parameters, ctx.resources.GetTexture(data.densityBuffer), data.visibleVolumeBoundsBuffer, data.visibleVolumeDataBuffer, diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index dc03473d129..fa17e7c70c2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -185,7 +185,7 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, TextureHandle sssBuffer, Cu // TODO RENDERGRAPH / Probably need to move this somewhere else. //RenderTransparencyOverdraw(cullingResults, hdCamera, renderContext, cmd); - ResolveStencilBufferIfNeeded(renderGraph, hdCamera, ref result); + BuildCoarseStencilAndResolveIfNeeded(renderGraph, hdCamera, ref result); } return result; @@ -510,7 +510,7 @@ class ResolveStencilPassData public ComputeBuffer coarseStencilBuffer; } - void ResolveStencilBufferIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, ref PrepassOutput output) + void BuildCoarseStencilAndResolveIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, ref PrepassOutput output) { using (var builder = renderGraph.AddRenderPass("Resolve Stencil", out var passData, ProfilingSampler.Get(HDProfileId.ResolveStencilBuffer))) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index 3233e811c8e..79cd4ed02aa 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -127,15 +127,23 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, lightingBuffers.diffuseLightingBuffer = ResolveMSAAColor(m_RenderGraph, hdCamera, lightingBuffers.diffuseLightingBuffer); lightingBuffers.sssBuffer = ResolveMSAAColor(m_RenderGraph, hdCamera, lightingBuffers.sssBuffer); - RenderSubsurfaceScattering(m_RenderGraph, hdCamera, colorBuffer, lightingBuffers, prepassOutput.depthBuffer, prepassOutput.depthPyramidTexture); + RenderSubsurfaceScattering(m_RenderGraph, hdCamera, colorBuffer, lightingBuffers, ref prepassOutput); RenderForwardEmissive(m_RenderGraph, hdCamera, colorBuffer, prepassOutput.depthBuffer, cullingResults); RenderSky(m_RenderGraph, hdCamera, colorBuffer, volumetricLighting, prepassOutput.depthBuffer, prepassOutput.depthPyramidTexture); + // TODO RENDERGRAPH + // Send all the geometry graphics buffer to client systems if required (must be done after the pyramid and before the transparent depth pre-pass) + //SendGeometryGraphicsBuffers(cmd, hdCamera); + // TODO RENDERGRAPH //m_PostProcessSystem.DoUserAfterOpaqueAndSky(cmd, hdCamera, m_CameraColorBuffer); + // TODO RENDERGRAPH + // No need for old stencil values here since from transparent on different features are tagged + //ClearStencilBuffer(hdCamera, cmd); + colorBuffer = RenderTransparency(m_RenderGraph, hdCamera, colorBuffer, prepassOutput.depthBuffer, prepassOutput.motionVectorsBuffer, currentColorPyramid, prepassOutput.depthPyramidTexture, shadowResult, cullingResults); // TODO RENDERGRAPH : Move this to the end after we do move semantic and graph pruning to avoid doing the rest of the frame for nothing @@ -168,11 +176,14 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, TextureHandle postProcessDest = RenderPostProcess(m_RenderGraph, colorBuffer, prepassOutput.depthBuffer, backBuffer, cullingResults, hdCamera); + // TODO RENDERGRAPH + // RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterPostProcess); + // TODO RENDERGRAPH //// Copy and rescale depth buffer for XR devices //if (hdCamera.xr.enabled && hdCamera.xr.copyDepth) //{ - // using (new ProfilingSample(cmd, "XR depth copy")) + // using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.XRDepthCopy))) // { // var depthBuffer = m_SharedRTManager.GetDepthStencilBuffer(); // var rtScale = depthBuffer.rtHandleProperties.rtHandleScale / DynamicResolutionHandler.instance.GetCurrentScale(); @@ -211,8 +222,9 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, // XR mirror view and blit do device EndCameraXR(m_RenderGraph, hdCamera); - //// Send all required graphics buffer to client systems. - //SendGraphicsBuffers(cmd, hdCamera); + // TODO RENDERGRAPH + // Send all the color graphics buffer to client systems if required. + //SendColorGraphicsBuffer(cmd, hdCamera); SetFinalTarget(m_RenderGraph, hdCamera, prepassOutput.resolvedDepthBuffer, target.id); @@ -445,6 +457,7 @@ void RenderForwardTransparent( RenderGraph renderGraph, if (renderMotionVecForTransparent) { mrt1 = motionVectorBuffer; + // TODO RENDERGRAPH // WORKAROUND VELOCITY-MSAA // This is a workaround for velocity with MSAA. Currently motion vector resolve is not implemented with MSAA // It means that the msaa motion vector target is never read and such released as soon as it's created. In such a case, trying to write it here will generate a render graph error. @@ -653,10 +666,11 @@ TextureHandle RenderTransparency( RenderGraph renderGraph, ShadowResult shadowResult, CullingResults cullingResults) { - RenderTransparentDepthPrepass(renderGraph, hdCamera, depthStencilBuffer, cullingResults); // TODO RENDERGRAPH + //RenderSSRTransparent(hdCamera, cmd, renderContext); + //if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) //{ // RaytracingRecursiveRender(hdCamera, cmd, renderContext, cullingResults); @@ -707,6 +721,7 @@ TextureHandle RenderTransparency( RenderGraph renderGraph, class RenderForwardEmissivePassData { + public bool enableDecals; public RendererListHandle rendererList; } @@ -716,21 +731,20 @@ void RenderForwardEmissive( RenderGraph renderGraph, TextureHandle depthStencilBuffer, CullingResults cullingResults) { - if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.Decals)) - return; - using (var builder = renderGraph.AddRenderPass("ForwardEmissive", out var passData, ProfilingSampler.Get(HDProfileId.ForwardEmissive))) { builder.UseColorBuffer(colorBuffer, 0); builder.UseDepthBuffer(depthStencilBuffer, DepthAccess.ReadWrite); + passData.enableDecals = hdCamera.frameSettings.IsEnabled(FrameSettingsField.Decals); passData.rendererList = builder.UseRendererList(renderGraph.CreateRendererList(PrepareForwardEmissiveRendererList(cullingResults, hdCamera))); builder.SetRenderFunc( (RenderForwardEmissivePassData data, RenderGraphContext context) => { HDUtils.DrawRendererList(context.renderContext, context.cmd, context.resources.GetRendererList(data.rendererList)); - DecalSystem.instance.RenderForwardEmissive(context.cmd); + if (data.enableDecals) + DecalSystem.instance.RenderForwardEmissive(context.cmd); }); } } @@ -946,6 +960,8 @@ void RenderDistortion( RenderGraph renderGraph, data.applyDistortionMaterial.SetTexture(HDShaderIDs._DistortionTexture, res.GetTexture(data.distortionBuffer)); data.applyDistortionMaterial.SetTexture(HDShaderIDs._ColorPyramidTexture, res.GetTexture(data.colorPyramidBuffer)); data.applyDistortionMaterial.SetVector(HDShaderIDs._Size, data.size); + data.applyDistortionMaterial.SetInt(HDShaderIDs._StencilMask, (int)StencilUsage.DistortionVectors); + data.applyDistortionMaterial.SetInt(HDShaderIDs._StencilRef, (int)StencilUsage.DistortionVectors); HDUtils.DrawFullScreen(context.cmd, data.applyDistortionMaterial, res.GetTexture(data.colorBuffer), res.GetTexture(data.depthStencilBuffer), null, 0); }); @@ -1014,6 +1030,7 @@ class RenderGizmosPassData { public GizmoSubset gizmoSubset; public Camera camera; + public Texture exposureTexture; } #endif @@ -1023,17 +1040,21 @@ void RenderGizmos(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle colo if (UnityEditor.Handles.ShouldRenderGizmos() && (hdCamera.camera.cameraType == CameraType.Game || hdCamera.camera.cameraType == CameraType.SceneView)) { - Gizmos.exposure = m_PostProcessSystem.GetExposureTexture(hdCamera).rt; bool renderPrePostprocessGizmos = (gizmoSubset == GizmoSubset.PreImageEffects); using (var builder = renderGraph.AddRenderPass(renderPrePostprocessGizmos ? "PrePostprocessGizmos" : "Gizmos", out var passData)) { + bool isMatCapView = m_CurrentDebugDisplaySettings.GetDebugLightingMode() == DebugLightingMode.MatcapView; + builder.WriteTexture(colorBuffer); passData.gizmoSubset = gizmoSubset; passData.camera = hdCamera.camera; + passData.exposureTexture = isMatCapView ? (Texture)Texture2D.blackTexture : m_PostProcessSystem.GetExposureTexture(hdCamera).rt; builder.SetRenderFunc( (RenderGizmosPassData data, RenderGraphContext ctx) => { + Gizmos.exposure = data.exposureTexture; + ctx.renderContext.ExecuteCommandBuffer(ctx.cmd); ctx.cmd.Clear(); ctx.renderContext.DrawGizmos(data.camera, data.gizmoSubset); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs index aa48dd400e3..1830c6829c9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs @@ -33,11 +33,16 @@ class SubsurfaceScaterringPassData } void RenderSubsurfaceScattering(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle colorBuffer, - in LightingBuffers lightingBuffers, TextureHandle depthStencilBuffer, TextureHandle depthTexture) + in LightingBuffers lightingBuffers, ref PrepassOutput prepassOutput) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering)) return; + BuildCoarseStencilAndResolveIfNeeded(renderGraph, hdCamera, ref prepassOutput); + + TextureHandle depthStencilBuffer = prepassOutput.depthBuffer; + TextureHandle depthTexture = prepassOutput.depthPyramidTexture; + using (var builder = renderGraph.AddRenderPass("Subsurface Scattering", out var passData, ProfilingSampler.Get(HDProfileId.SubsurfaceScattering))) { passData.parameters = PrepareSubsurfaceScatteringParameters(hdCamera); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 58d9a86d004..dce0e9b3028 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -2120,8 +2120,8 @@ void Callback(CommandBuffer c, HDGPUAsyncTaskParams a) haveAsyncTaskWithShadows = true; - void Callback(CommandBuffer c, HDGPUAsyncTaskParams a) - => RenderSSR(a.hdCamera, c, a.renderContext); + void Callback(CommandBuffer c, HDGPUAsyncTaskParams a) + => RenderSSR(a.hdCamera, c, a.renderContext); } if (hdCamera.frameSettings.SSAORunsAsync()) @@ -2186,14 +2186,14 @@ void Callback(CommandBuffer c, HDCamera cam) if (!hdCamera.frameSettings.SSAORunsAsync()) m_AmbientOcclusionSystem.Render(cmd, hdCamera, renderContext, m_FrameCount); - // Run the contact shadows here as they the light list - HDUtils.CheckRTCreated(m_ContactShadowBuffer); - RenderContactShadows(hdCamera, cmd); - PushFullScreenDebugTexture(hdCamera, cmd, m_ContactShadowBuffer, FullScreenDebugMode.ContactShadows); + // Run the contact shadows here as they need the light list + HDUtils.CheckRTCreated(m_ContactShadowBuffer); + RenderContactShadows(hdCamera, cmd); + PushFullScreenDebugTexture(hdCamera, cmd, m_ContactShadowBuffer, FullScreenDebugMode.ContactShadows); - hdCamera.xr.StartSinglePass(cmd, camera, renderContext); - RenderScreenSpaceShadows(hdCamera, cmd); - hdCamera.xr.StopSinglePass(cmd, camera, renderContext); + hdCamera.xr.StartSinglePass(cmd, camera, renderContext); + RenderScreenSpaceShadows(hdCamera, cmd); + hdCamera.xr.StopSinglePass(cmd, camera, renderContext); if (hdCamera.frameSettings.VolumeVoxelizationRunsAsync()) { @@ -2236,12 +2236,6 @@ void Callback(CommandBuffer c, HDCamera cam) m_SharedRTManager.ResolveMSAAColor(cmd, hdCamera, m_CameraSssDiffuseLightingMSAABuffer, m_CameraSssDiffuseLightingBuffer); m_SharedRTManager.ResolveMSAAColor(cmd, hdCamera, GetSSSBufferMSAA(), GetSSSBuffer()); - if(hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering)) - { - // We need htile for SSS, but we don't need to resolve again - BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd); - } - // SSS pass here handle both SSS material from deferred and forward RenderSubsurfaceScattering(hdCamera, cmd, hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA) ? m_CameraColorMSAABuffer : m_CameraColorBuffer, m_CameraSssDiffuseLightingBuffer, m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), m_SharedRTManager.GetDepthTexture()); @@ -2260,12 +2254,6 @@ void Callback(CommandBuffer c, HDCamera cam) RenderTransparentDepthPrepass(cullingResults, hdCamera, renderContext, cmd); - if(hdCamera.frameSettings.IsEnabled(FrameSettingsField.TransparentSSR)) - { - // We need htile for SSS, but we don't need to resolve again - BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd); - } - RenderSSRTransparent(hdCamera, cmd, renderContext); if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) @@ -3892,6 +3880,8 @@ void RenderSSRTransparent(HDCamera hdCamera, CommandBuffer cmd, ScriptableRender if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.TransparentSSR)) return; + BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd); + // Before doing anything, we need to clear the target buffers and rebuild the depth pyramid for tracing // NOTE: This is probably something we can avoid if we read from the depth buffer and traced on the pyramid without the transparent objects using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PrepareForTransparentSsr))) From 9960b20c858a583d4ed584a1a7eeb02e6afbb770 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 3 Mar 2020 15:11:14 +0100 Subject: [PATCH 20/92] Unified renderer list and texture invalid handle error. --- .../Runtime/RenderGraph/RenderGraphResourceRegistry.cs | 7 +++++++ .../Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs | 6 +++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs index e26172c669a..3e0f4566c07 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs @@ -321,6 +321,9 @@ internal RendererListResource(in RendererListDesc desc) public RTHandle GetTexture(in TextureHandle handle) { #if DEVELOPMENT_BUILD || UNITY_EDITOR + if (!handle.IsValid()) + throw new InvalidOperationException("Trying to access a texture with an invalid handle."); + var res = m_TextureResources[handle]; if (res.rt == null && !res.wasReleased) @@ -339,6 +342,10 @@ public RTHandle GetTexture(in TextureHandle handle) /// The Renderer List associated with the provided resource handle. public RendererList GetRendererList(in RendererListHandle handle) { +#if DEVELOPMENT_BUILD || UNITY_EDITOR + if (!handle.IsValid()) + throw new InvalidOperationException("Trying to access a Renderer List with an invalid handle."); +#endif return m_RendererListResources[handle].rendererList; } #endregion diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index 6627ba087bc..a5234b1efba 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -267,11 +267,11 @@ bool RenderDepthPrepass(RenderGraph renderGraph, CullingResults cull, HDCamera h RenderDepthPrepass(context.renderContext, context.cmd, data.frameSettings , mrt , context.resources.GetTexture(data.depthBuffer) - , data.hasDepthOnlyPrepass ? context.resources.GetRendererList(data.rendererListDepthOnly) : RendererList.nullRendererList + , context.resources.GetRendererList(data.rendererListDepthOnly) , context.resources.GetRendererList(data.rendererListMRT) , data.hasDepthOnlyPrepass - , useRayTracing ? context.resources.GetRendererList(data.renderListRayTracingOpaque) : new RendererList() - , useRayTracing ? context.resources.GetRendererList(data.renderListRayTracingTransparent) : new RendererList() + , context.resources.GetRendererList(data.renderListRayTracingOpaque) + , context.resources.GetRendererList(data.renderListRayTracingTransparent) , data.renderRayTracingPrepass ); }); From ea729c303ed9dd165d305da01d6a2ee5a3317c63 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 4 Mar 2020 10:38:33 +0100 Subject: [PATCH 21/92] Revert wrong change --- .../RenderGraph/RenderGraphResourceRegistry.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs index 3e0f4566c07..c5623a92c14 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs @@ -317,12 +317,13 @@ internal RendererListResource(in RendererListDesc desc) /// Returns the RTHandle associated with the provided resource handle. /// /// Handle to a texture resource. - /// The RTHandle associated with the provided resource handle. + /// The RTHandle associated with the provided resource handle or null if the handle is invalid. public RTHandle GetTexture(in TextureHandle handle) { -#if DEVELOPMENT_BUILD || UNITY_EDITOR if (!handle.IsValid()) - throw new InvalidOperationException("Trying to access a texture with an invalid handle."); + return null; + +#if DEVELOPMENT_BUILD || UNITY_EDITOR var res = m_TextureResources[handle]; @@ -339,13 +340,12 @@ public RTHandle GetTexture(in TextureHandle handle) /// Returns the RendererList associated with the provided resource handle. /// /// Handle to a Renderer List resource. - /// The Renderer List associated with the provided resource handle. + /// The Renderer List associated with the provided resource handle or a null renderer list if the handle is invalid. public RendererList GetRendererList(in RendererListHandle handle) { -#if DEVELOPMENT_BUILD || UNITY_EDITOR if (!handle.IsValid()) - throw new InvalidOperationException("Trying to access a Renderer List with an invalid handle."); -#endif + return RendererList.nullRendererList; + return m_RendererListResources[handle].rendererList; } #endregion From afa9870da0b6a1b32b4657b9a16b87245b48591c Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 4 Mar 2020 13:46:25 +0100 Subject: [PATCH 22/92] Added constant buffer hlsl generation --- .../Editor/ShaderGenerator/ShaderTypeGeneration.cs | 10 ++++++++-- .../ShaderGenerator/ShaderGeneratorAttributes.cs | 9 +++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs index 9351dad4f1e..bab785441d3 100644 --- a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs +++ b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs @@ -407,7 +407,13 @@ public string EmitTypeDecl() shaderText += "// Generated from " + type.FullName + "\n"; shaderText += "// PackingRules = " + attr.packingRules.ToString() + "\n"; - if (!attr.omitStructDeclaration) + + if (attr.generateCBuffer) + { + shaderText += "cbuffer " + type.Name + "\n"; + shaderText += "{\n"; + } + else if (!attr.omitStructDeclaration) { shaderText += "struct " + type.Name + "\n"; shaderText += "{\n"; @@ -418,7 +424,7 @@ public string EmitTypeDecl() shaderText += " " + shaderFieldInfo.ToString() + "\n"; } - if (!attr.omitStructDeclaration) + if (attr.generateCBuffer || !attr.omitStructDeclaration) { shaderText += "};\n"; } diff --git a/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs b/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs index 249ccc7a46b..18ed9096130 100644 --- a/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs +++ b/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs @@ -94,6 +94,10 @@ public class GenerateHLSL : System.Attribute /// Generate structure declaration or not. /// public bool omitStructDeclaration; + /// + /// Generate constant buffer declaration or not. + /// + public bool generateCBuffer; /// /// GenerateHLSL attribute constructor. @@ -105,7 +109,7 @@ public class GenerateHLSL : System.Attribute /// Start value of debug defines. /// Omit structure declaration. /// Contains packed fields. - public GenerateHLSL(PackingRules rules = PackingRules.Exact, bool needAccessors = true, bool needSetters = false, bool needParamDebug = false, int paramDefinesStart = 1, bool omitStructDeclaration = false, bool containsPackedFields = false) + public GenerateHLSL(PackingRules rules = PackingRules.Exact, bool needAccessors = true, bool needSetters = false, bool needParamDebug = false, int paramDefinesStart = 1, bool omitStructDeclaration = false, bool containsPackedFields = false, bool generateCBuffer = false) { packingRules = rules; this.needAccessors = needAccessors; @@ -114,6 +118,7 @@ public GenerateHLSL(PackingRules rules = PackingRules.Exact, bool needAccessors this.paramDefinesStart = paramDefinesStart; this.omitStructDeclaration = omitStructDeclaration; this.containsPackedFields = containsPackedFields; + this.generateCBuffer = generateCBuffer; } } @@ -183,7 +188,7 @@ public class HLSLArray : System.Attribute /// /// Size of the array. /// - public int arraySize; + public int arraySize; /// /// Type of the array elements. /// From 7410584f45cf02ff1b9fe3061a7e0f0d60a0e698 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 4 Mar 2020 18:06:32 +0100 Subject: [PATCH 23/92] Changed UnityGlobal constant buffers to ShaderVariablesGlobals and generate it from C# --- .../Runtime/Debug/DebugDisplay.hlsl | 1 + .../Runtime/Debug/LightingDebug.cs.hlsl | 13 + .../ShaderVariablesAtmosphericScattering.cs | 20 -- ...aderVariablesAtmosphericScattering.cs.hlsl | 20 -- ...ariablesAtmosphericScattering.cs.hlsl.meta | 9 - ...aderVariablesAtmosphericScattering.cs.meta | 11 - .../ShaderVariablesAtmosphericScattering.hlsl | 16 +- .../LightLoop/ShaderVariablesLightLoop.cs | 72 ------ .../ShaderVariablesLightLoop.cs.hlsl | 48 ---- .../ShaderVariablesLightLoop.cs.meta | 11 - .../LightLoop/ShaderVariablesLightLoop.hlsl | 53 ++-- .../ShaderVariablesScreenSpaceLighting.cs | 21 -- ...ShaderVariablesScreenSpaceLighting.cs.hlsl | 18 -- ...rVariablesScreenSpaceLighting.cs.hlsl.meta | 9 - .../ShaderVariablesScreenSpaceLighting.hlsl | 10 +- .../Material/Decal/ShaderVariablesDecal.cs | 11 - .../Decal/ShaderVariablesDecal.cs.hlsl | 14 -- .../Decal/ShaderVariablesDecal.cs.hlsl.meta | 9 - .../Decal/ShaderVariablesDecal.cs.meta | 11 - .../Material/Decal/ShaderVariablesDecal.hlsl | 6 - .../ShaderVariablesSubsurfaceScattering.cs | 25 -- ...haderVariablesSubsurfaceScattering.cs.hlsl | 20 -- ...VariablesSubsurfaceScattering.cs.hlsl.meta | 9 - ...haderVariablesSubsurfaceScattering.cs.meta | 11 - .../ShaderVariablesSubsurfaceScattering.hlsl | 6 - ...derVariablesSubsurfaceScattering.hlsl.meta | 9 - .../RenderPipeline/HDStringConstants.cs | 7 +- .../ShaderLibrary/ShaderVariables.hlsl | 156 ++---------- .../ShaderLibrary/ShaderVariablesGlobal.cs | 237 ++++++++++++++++++ .../ShaderVariablesGlobal.cs.hlsl | 133 ++++++++++ .../ShaderVariablesGlobal.cs.hlsl.meta} | 2 +- .../ShaderVariablesGlobal.cs.meta} | 2 +- 32 files changed, 436 insertions(+), 564 deletions(-) delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.hlsl delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.hlsl.meta delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.meta delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs.hlsl delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs.meta delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.hlsl delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.hlsl.meta delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.hlsl delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.hlsl.meta delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.meta delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.hlsl delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.hlsl.meta delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.meta delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl.meta create mode 100644 com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs create mode 100644 com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl rename com.unity.render-pipelines.high-definition/Runtime/{Lighting/LightLoop/ShaderVariablesLightLoop.cs.hlsl.meta => ShaderLibrary/ShaderVariablesGlobal.cs.hlsl.meta} (80%) rename com.unity.render-pipelines.high-definition/Runtime/{Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.meta => ShaderLibrary/ShaderVariablesGlobal.cs.meta} (83%) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.hlsl index 58bc884a49d..d89e89f18a8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.hlsl @@ -38,6 +38,7 @@ float _DebugExposure; int _MatcapMixAlbedo; int _MatcapViewScale; uint _DebugContactShadowLightIndex; +int _DebugSingleShadowIndex; CBUFFER_END // Local shader variables diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs.hlsl index 03c4e919259..a2206be2f19 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs.hlsl @@ -32,6 +32,19 @@ #define DEBUGLIGHTFILTERMODE_INDIRECT_REFLECTION_PROBE (128) #define DEBUGLIGHTFILTERMODE_INDIRECT_PLANAR_PROBE (256) +// +// UnityEngine.Rendering.HighDefinition.DebugLightLayersMask: static fields +// +#define DEBUGLIGHTLAYERSMASK_NONE (0) +#define DEBUGLIGHTLAYERSMASK_LIGHT_LAYER1 (1) +#define DEBUGLIGHTLAYERSMASK_LIGHT_LAYER2 (2) +#define DEBUGLIGHTLAYERSMASK_LIGHT_LAYER3 (4) +#define DEBUGLIGHTLAYERSMASK_LIGHT_LAYER4 (8) +#define DEBUGLIGHTLAYERSMASK_LIGHT_LAYER5 (16) +#define DEBUGLIGHTLAYERSMASK_LIGHT_LAYER6 (32) +#define DEBUGLIGHTLAYERSMASK_LIGHT_LAYER7 (64) +#define DEBUGLIGHTLAYERSMASK_LIGHT_LAYER8 (128) + // // UnityEngine.Rendering.HighDefinition.ShadowMapDebugMode: static fields // diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs deleted file mode 100644 index eaf67941303..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace UnityEngine.Rendering.HighDefinition -{ - [GenerateHLSL(needAccessors = false, omitStructDeclaration = true)] - struct ShaderVariablesAtmosphericScattering - { - // Common - public int _FogEnabled; - public int _PBRFogEnabled; - public float _MaxFogDistance; - public float _FogColorMode; - public float _SkyTextureMipCount; - public Vector4 _FogColor; // color in rgb - public Vector4 _MipFogParameters; - - // Volumetrics - public float _VBufferLastSliceDist; // The distance to the middle of the last slice - public int _EnableVolumetricFog; // bool... - } -} - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.hlsl deleted file mode 100644 index 93f89991373..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.hlsl +++ /dev/null @@ -1,20 +0,0 @@ -// -// This file was automatically generated. Please don't edit by hand. -// - -#ifndef SHADERVARIABLESATMOSPHERICSCATTERING_CS_HLSL -#define SHADERVARIABLESATMOSPHERICSCATTERING_CS_HLSL -// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesAtmosphericScattering -// PackingRules = Exact - int _FogEnabled; - int _PBRFogEnabled; - float _MaxFogDistance; - float _FogColorMode; - float _SkyTextureMipCount; - float4 _FogColor; - float4 _MipFogParameters; - float _VBufferLastSliceDist; - int _EnableVolumetricFog; - - -#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.hlsl.meta deleted file mode 100644 index 96aaad3f1ab..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.hlsl.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: b4e0553b2e5013d46a82348a2003ea6c -ShaderImporter: - externalObjects: {} - defaultTextures: [] - nonModifiableTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.meta deleted file mode 100644 index 2a4b723cbcf..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7d34807f201b3e64fabe8bb67a7696d1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.hlsl index bc67f69e7c3..a7a59afb9b5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.hlsl @@ -1,13 +1,9 @@ -#ifdef SHADER_VARIABLES_INCLUDE_CB - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.cs.hlsl" -#else - TEXTURE3D(_VBufferLighting); - TEXTURECUBE_ARRAY(_SkyTexture); +TEXTURE3D(_VBufferLighting); +TEXTURECUBE_ARRAY(_SkyTexture); - #define _MipFogNear _MipFogParameters.x - #define _MipFogFar _MipFogParameters.y - #define _MipFogMaxMip _MipFogParameters.z +#define _MipFogNear _MipFogParameters.x +#define _MipFogFar _MipFogParameters.y +#define _MipFogMaxMip _MipFogParameters.z - #define _FogColor _FogColor -#endif +#define _FogColor _FogColor diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs deleted file mode 100644 index b5b853c73fb..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs +++ /dev/null @@ -1,72 +0,0 @@ -namespace UnityEngine.Rendering.HighDefinition -{ - [GenerateHLSL(needAccessors = false, omitStructDeclaration = true)] - unsafe struct ShaderVariablesLightLoop - { - public const int s_MaxEnv2DLight = 32; - - [HLSLArray(0, typeof(Vector4))] - public fixed float _ShadowAtlasSize[4]; - [HLSLArray(0, typeof(Vector4))] - public fixed float _CascadeShadowAtlasSize[4]; - [HLSLArray(0, typeof(Vector4))] - public fixed float _AreaShadowAtlasSize[4]; - - [HLSLArray(s_MaxEnv2DLight, typeof(Matrix4x4))] - public fixed float _Env2DCaptureVP[s_MaxEnv2DLight * 4 * 4]; - [HLSLArray(s_MaxEnv2DLight * 3, typeof(float))] - public fixed float _Env2DCaptureForward[s_MaxEnv2DLight * 3]; - [HLSLArray(s_MaxEnv2DLight, typeof(Vector4))] - public fixed float _Env2DAtlasScaleOffset[s_MaxEnv2DLight * 3]; - - public uint _DirectionalLightCount; - - public uint _PunctualLightCount; - public uint _AreaLightCount; - public uint _EnvLightCount; - public uint _EnvProxyCount; - public int _EnvLightSkyEnabled; // TODO: make it a bool - public int _DirectionalShadowIndex; - - public Vector4 _CookieAtlasSize; - public Vector4 _CookieAtlasData; - - public Vector4 _PlanarAtlasData; - - public float _MicroShadowOpacity; - - public float _DirectionalTransmissionMultiplier; - - public uint _NumTileFtplX; - public 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 -// float4x4 g_mInvScrProjection; // TODO: remove, unused in HDRP - - public float g_fClustScale; - public float g_fClustBase; - public float g_fNearPlane; - public float g_fFarPlane; - public int g_iLog2NumClusters; // We need to always define these to keep constant buffer layouts compatible - - public uint g_isLogBaseBufferEnabled; - //#endif - - //#ifdef USE_CLUSTERED_LIGHTLIST - public uint _NumTileClusteredX; - public uint _NumTileClusteredY; - - public uint _CascadeShadowCount; - - // TODO: move this elsewhere - public int _DebugSingleShadowIndex; - - public int _EnvSliceSize; - - // Uniform variables that defines if we shall be using the raytraced indirect diffuse - public int _RaytracedIndirectDiffuse; - } -} - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs.hlsl deleted file mode 100644 index 9d5b6659d91..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs.hlsl +++ /dev/null @@ -1,48 +0,0 @@ -// -// This file was automatically generated. Please don't edit by hand. -// - -#ifndef SHADERVARIABLESLIGHTLOOP_CS_HLSL -#define SHADERVARIABLESLIGHTLOOP_CS_HLSL -// -// UnityEngine.Rendering.HighDefinition.ShaderVariablesLightLoop: static fields -// -#define MAX_ENV2DLIGHT (32) - -// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesLightLoop -// PackingRules = Exact - float4 _ShadowAtlasSize; - float4 _CascadeShadowAtlasSize; - float4 _AreaShadowAtlasSize; - float4x4 _Env2DCaptureVP[32]; - float _Env2DCaptureForward[96]; - float4 _Env2DAtlasScaleOffset[32]; - uint _DirectionalLightCount; - uint _PunctualLightCount; - uint _AreaLightCount; - uint _EnvLightCount; - uint _EnvProxyCount; - int _EnvLightSkyEnabled; - int _DirectionalShadowIndex; - float4 _CookieAtlasSize; - float4 _CookieAtlasData; - float4 _PlanarAtlasData; - float _MicroShadowOpacity; - float _DirectionalTransmissionMultiplier; - uint _NumTileFtplX; - uint _NumTileFtplY; - float g_fClustScale; - float g_fClustBase; - float g_fNearPlane; - float g_fFarPlane; - int g_iLog2NumClusters; - uint g_isLogBaseBufferEnabled; - uint _NumTileClusteredX; - uint _NumTileClusteredY; - uint _CascadeShadowCount; - int _DebugSingleShadowIndex; - int _EnvSliceSize; - int _RaytracedIndirectDiffuse; - - -#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs.meta deleted file mode 100644 index 52d6ece4cff..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a2f504e2dfa01d445b1e6ca5bc0233ba -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl index 78b93dea48a..73f2fce48bd 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl @@ -1,44 +1,37 @@ -#ifdef SHADER_VARIABLES_INCLUDE_CB +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs.hlsl" +// don't support Buffer yet in unity +StructuredBuffer g_vBigTileLightList; +StructuredBuffer g_vLightListGlobal; +StructuredBuffer g_vLayeredOffsetsBuffer; +StructuredBuffer g_logBaseBuffer; -#else - - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl" - - // don't support Buffer yet in unity - StructuredBuffer g_vBigTileLightList; - StructuredBuffer g_vLightListGlobal; - StructuredBuffer g_vLayeredOffsetsBuffer; - StructuredBuffer g_logBaseBuffer; - - #ifdef USE_INDIRECT - StructuredBuffer g_TileFeatureFlags; - #endif +#ifdef USE_INDIRECT + StructuredBuffer g_TileFeatureFlags; +#endif - StructuredBuffer _DirectionalLightDatas; - StructuredBuffer _LightDatas; - StructuredBuffer _EnvLightDatas; +StructuredBuffer _DirectionalLightDatas; +StructuredBuffer _LightDatas; +StructuredBuffer _EnvLightDatas; - // Used by directional and spot lights - TEXTURE2D(_CookieAtlas); +// Used by directional and spot lights +TEXTURE2D(_CookieAtlas); - // Used by point lights - TEXTURECUBE_ARRAY_ABSTRACT(_CookieCubeTextures); +// Used by point lights +TEXTURECUBE_ARRAY_ABSTRACT(_CookieCubeTextures); - // Use texture array for reflection (or LatLong 2D array for mobile) - TEXTURECUBE_ARRAY_ABSTRACT(_EnvCubemapTextures); - TEXTURE2D(_Env2DTextures); +// Use texture array for reflection (or LatLong 2D array for mobile) +TEXTURECUBE_ARRAY_ABSTRACT(_EnvCubemapTextures); +TEXTURE2D(_Env2DTextures); - // Contact shadows - TEXTURE2D_X_UINT(_ContactShadowTexture); +// Contact shadows +TEXTURE2D_X_UINT(_ContactShadowTexture); - // Screen space shadows - TEXTURE2D_ARRAY(_ScreenSpaceShadowsTexture); +// Screen space shadows +TEXTURE2D_ARRAY(_ScreenSpaceShadowsTexture); #if RAYTRACING_ENABLED // Indirect Diffuse Texture TEXTURE2D_X(_IndirectDiffuseTexture); #endif -#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs deleted file mode 100644 index 8a9f1498c50..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace UnityEngine.Rendering.HighDefinition -{ - [GenerateHLSL(needAccessors = false, omitStructDeclaration = true)] - struct ShaderVariablesScreenSpaceLighting - { - // Buffer pyramid - public Vector4 _CameraMotionVectorsSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size - public Vector4 _ColorPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused - public Vector4 _DepthPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused - public Vector4 _CameraMotionVectorsScale; // (x,y) = Screen Scale, z = lod count, w = unused - - // Ambient occlusion - public Vector4 _AmbientOcclusionParam; // xyz occlusion color, w directLightStrenght - - public Vector4 _IndirectLightingMultiplier; // .x indirect diffuse multiplier (use with indirect lighting volume controler) - - // Screen space refraction - public float _SSRefractionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback - } -} - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.hlsl deleted file mode 100644 index 7e004dbb0d3..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.hlsl +++ /dev/null @@ -1,18 +0,0 @@ -// -// This file was automatically generated. Please don't edit by hand. -// - -#ifndef SHADERVARIABLESSCREENSPACELIGHTING_CS_HLSL -#define SHADERVARIABLESSCREENSPACELIGHTING_CS_HLSL -// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesScreenSpaceLighting -// PackingRules = Exact - float4 _CameraMotionVectorsSize; - float4 _ColorPyramidScale; - float4 _DepthPyramidScale; - float4 _CameraMotionVectorsScale; - float4 _AmbientOcclusionParam; - float4 _IndirectLightingMultiplier; - float _SSRefractionInvScreenWeightDistance; - - -#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.hlsl.meta deleted file mode 100644 index 1633647b844..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.hlsl.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 79b2a5f70312a3545bdaa66eadb3ab4c -ShaderImporter: - externalObjects: {} - defaultTextures: [] - nonModifiableTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.hlsl index 30b5aab8c26..f167e3cfbab 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.hlsl @@ -1,7 +1,3 @@ -#ifdef SHADER_VARIABLES_INCLUDE_CB - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.hlsl" -#else - TEXTURE2D_X(_AmbientOcclusionTexture); - TEXTURE2D_X(_CameraMotionVectorsTexture); - TEXTURE2D_X(_SsrLightingTexture); -#endif +TEXTURE2D_X(_AmbientOcclusionTexture); +TEXTURE2D_X(_CameraMotionVectorsTexture); +TEXTURE2D_X(_SsrLightingTexture); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs deleted file mode 100644 index 86f394eefd7..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace UnityEngine.Rendering.HighDefinition -{ - [GenerateHLSL(needAccessors = false, omitStructDeclaration = true)] - struct ShaderVariablesDecal - { - public Vector2 _DecalAtlasResolution; - public uint _EnableDecals; - public uint _DecalCount; - } -} - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.hlsl deleted file mode 100644 index ece7c5a7b8b..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.hlsl +++ /dev/null @@ -1,14 +0,0 @@ -// -// This file was automatically generated. Please don't edit by hand. -// - -#ifndef SHADERVARIABLESDECAL_CS_HLSL -#define SHADERVARIABLESDECAL_CS_HLSL -// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesDecal -// PackingRules = Exact - float2 _DecalAtlasResolution; - uint _EnableDecals; - uint _DecalCount; - - -#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.hlsl.meta deleted file mode 100644 index abba3539d5f..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.hlsl.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 0027c6174eecc5d47a411907371ba277 -ShaderImporter: - externalObjects: {} - defaultTextures: [] - nonModifiableTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.meta b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.meta deleted file mode 100644 index 1603b7c6207..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 28b67e39f46c36840a5704a78b276553 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.hlsl index d5210169a42..d80236c1d94 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.hlsl @@ -1,7 +1,3 @@ -#ifdef SHADER_VARIABLES_INCLUDE_CB - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.cs.hlsl" -#else - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.cs.hlsl" StructuredBuffer _DecalDatas; @@ -17,5 +13,3 @@ StructuredBuffer _DecalPropertyMaskBufferSRV; UNITY_INSTANCING_BUFFER_START(Decal) UNITY_DEFINE_INSTANCED_PROP(float4x4, _NormalToWorld) UNITY_INSTANCING_BUFFER_END(Decal) - -#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs deleted file mode 100644 index a94d61ea808..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace UnityEngine.Rendering.HighDefinition -{ - [GenerateHLSL(needAccessors = false, omitStructDeclaration = true)] - unsafe struct ShaderVariablesSubsurfaceScattering - { - // Use float4 to avoid any packing issue between compute and pixel shaders - [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(Vector4))] - public fixed float _ThicknessRemaps[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // R: start, G = end - start, BA unused - [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(Vector4))] - public fixed float _ShapeParams[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // RGB = S = 1 / D, A = filter radius - [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(Vector4))] - public fixed float _TransmissionTintsAndFresnel0[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // RGB = 1/4 * color, A = fresnel0 - [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(Vector4))] - public fixed float _WorldScales[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // X = meters per world unit; Y = world units per meter - [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(float))] - public fixed uint _DiffusionProfileHashTable[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT]; // TODO: constant - - // Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system. - // Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader. - public uint _EnableSubsurfaceScattering; // Globally toggles subsurface and transmission scattering on/off - public float _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter - public float _TransmissionFlags; // 1 bit/profile; 0 = regular, 1 = thin - public uint _DiffusionProfileCount; - } -} diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.hlsl deleted file mode 100644 index 572d6d58162..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.hlsl +++ /dev/null @@ -1,20 +0,0 @@ -// -// This file was automatically generated. Please don't edit by hand. -// - -#ifndef SHADERVARIABLESSUBSURFACESCATTERING_CS_HLSL -#define SHADERVARIABLESSUBSURFACESCATTERING_CS_HLSL -// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesSubsurfaceScattering -// PackingRules = Exact - float4 _ThicknessRemaps[16]; - float4 _ShapeParams[16]; - float4 _TransmissionTintsAndFresnel0[16]; - float4 _WorldScales[16]; - float _DiffusionProfileHashTable[16]; - uint _EnableSubsurfaceScattering; - float _TexturingModeFlags; - float _TransmissionFlags; - uint _DiffusionProfileCount; - - -#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.hlsl.meta deleted file mode 100644 index 0fb8e54b5ab..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.hlsl.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: f07376079a27a844e8aadc32955c9085 -ShaderImporter: - externalObjects: {} - defaultTextures: [] - nonModifiableTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.meta b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.meta deleted file mode 100644 index 8621aada0f9..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5565dc9dd41c17540afb8e8df50b74f9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl deleted file mode 100644 index 3c998dc3090..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl +++ /dev/null @@ -1,6 +0,0 @@ -#ifdef SHADER_VARIABLES_INCLUDE_CB - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.cs.hlsl" - - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.cs.hlsl" -#else -#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl.meta deleted file mode 100644 index 30bd591b1c7..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 63af6347132378d43b75aa5e4efeb029 -ShaderImporter: - externalObjects: {} - defaultTextures: [] - nonModifiableTextures: [] - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 15fc01ddb08..4ebbdae112c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -158,7 +158,6 @@ static class HDShaderIDs public static readonly int _AreaLightCount = Shader.PropertyToID("_AreaLightCount"); public static readonly int _EnvLightDatas = Shader.PropertyToID("_EnvLightDatas"); public static readonly int _EnvLightCount = Shader.PropertyToID("_EnvLightCount"); - public static readonly int _EnvProxyCount = Shader.PropertyToID("_EnvProxyCount"); public static readonly int _NumTileBigTileX = Shader.PropertyToID("_NumTileBigTileX"); public static readonly int _NumTileBigTileY = Shader.PropertyToID("_NumTileBigTileY"); public static readonly int _NumTileFtplX = Shader.PropertyToID("_NumTileFtplX"); @@ -287,8 +286,8 @@ static class HDShaderIDs public static readonly int _DecalPropertyMaskBufferSRV = Shader.PropertyToID("_DecalPropertyMaskBufferSRV"); - public static readonly int _WorldSpaceCameraPos = Shader.PropertyToID("_WorldSpaceCameraPos"); - public static readonly int _PrevCamPosRWS = Shader.PropertyToID("_PrevCamPosRWS"); + public static readonly int _WorldSpaceCameraPos = Shader.PropertyToID("_WorldSpaceCameraPos_Internal"); + public static readonly int _PrevCamPosRWS = Shader.PropertyToID("_PrevCamPosRWS_Internal"); public static readonly int _ViewMatrix = Shader.PropertyToID("_ViewMatrix"); public static readonly int _InvViewMatrix = Shader.PropertyToID("_InvViewMatrix"); public static readonly int _ProjMatrix = Shader.PropertyToID("_ProjMatrix"); @@ -716,7 +715,7 @@ static class HDShaderIDs public static readonly int _NormalTextureRW = Shader.PropertyToID("_NormalTextureRW"); public static readonly int _PositionTextureRW = Shader.PropertyToID("_PositionTextureRW"); public static readonly int _DiffuseLightingTextureRW = Shader.PropertyToID("_DiffuseLightingTextureRW"); - + // Preintegrated texture name public static readonly int _PreIntegratedFGD_GGXDisneyDiffuse = Shader.PropertyToID("_PreIntegratedFGD_GGXDisneyDiffuse"); public static readonly int _PreIntegratedFGD_CharlieAndFabric = Shader.PropertyToID("_PreIntegratedFGD_CharlieAndFabric"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl index f2de209be44..37be22343c3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl @@ -17,6 +17,9 @@ #define _WorldSpaceCameraPos _XRWorldSpaceCameraPos[unity_StereoEyeIndex].xyz #define _WorldSpaceCameraPosViewOffset _XRWorldSpaceCameraPosViewOffset[unity_StereoEyeIndex].xyz #define _PrevCamPosRWS _XRPrevWorldSpaceCameraPos[unity_StereoEyeIndex].xyz +#else + #define _WorldSpaceCameraPos _WorldSpaceCameraPos_Internal + #define _PrevCamPosRWS _PrevCamPosRWS_Internal #endif #define UNITY_LIGHTMODEL_AMBIENT (glstate_lightmodel_ambient * 2) @@ -32,7 +35,7 @@ #if defined(SHADER_STAGE_RAY_TRACING) // FXC Supports the naïve "recursive" concatenation, while DXC and C do not https://github.com/pfultz2/Cloak/wiki/C-Preprocessor-tricks,-tips,-and-idioms -// However, FXC does not support the proper pattern (the one bellow), so we only override it in the case of ray tracing subshaders for the moment. +// However, FXC does not support the proper pattern (the one bellow), so we only override it in the case of ray tracing subshaders for the moment. // Note that this should be used for all shaders when DX12 used DXC for vert/frag shaders (which it does not for the moment) #undef MERGE_NAME #define MERGE_NAME_CONCAT(Name, ...) Name ## __VA_ARGS__ @@ -145,145 +148,19 @@ TEXTURE2D(_ExposureTexture); TEXTURE2D(_PrevExposureTexture); // ---------------------------------------------------------------------------- +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl" -// Define that before including all the sub systems ShaderVariablesXXX.hlsl files in order to include constant buffer properties. -#define SHADER_VARIABLES_INCLUDE_CB - -// Important: please use macros or functions to access the CBuffer data. -// The member names and data layout can (and will) change! -CBUFFER_START(UnityGlobal) - // ================================ - // PER VIEW CONSTANTS - // ================================ - // TODO: all affine matrices should be 3x4. - float4x4 _ViewMatrix; - float4x4 _InvViewMatrix; - float4x4 _ProjMatrix; - float4x4 _InvProjMatrix; - float4x4 _ViewProjMatrix; - float4x4 _CameraViewProjMatrix; - float4x4 _InvViewProjMatrix; - float4x4 _NonJitteredViewProjMatrix; - float4x4 _PrevViewProjMatrix; // non-jittered - float4x4 _PrevInvViewProjMatrix; // non-jittered - - // TODO: put commonly used vars together (below), and then sort them by the frequency of use (descending). - // Note: a matrix is 4 * 4 * 4 = 64 bytes (1x cache line), so no need to sort those. -#ifndef USING_STEREO_MATRICES - float3 _WorldSpaceCameraPos; - float _Pad0; - float3 _PrevCamPosRWS; - float _Pad1; -#endif - float4 _ScreenSize; // { w, h, 1 / w, 1 / h } - - // Those two uniforms are specific to the RTHandle system - float4 _RTHandleScale; // { w / RTHandle.maxWidth, h / RTHandle.maxHeight } : xy = currFrame, zw = prevFrame - float4 _RTHandleScaleHistory; // Same as above but the RTHandle handle size is that of the history buffer - - // Values used to linearize the Z buffer (http://www.humus.name/temp/Linearize%20depth.txt) - // x = 1 - f/n - // y = f/n - // z = 1/f - 1/n - // w = 1/n - // or in case of a reversed depth buffer (UNITY_REVERSED_Z is 1) - // x = -1 + f/n - // y = 1 - // z = -1/n + -1/f - // w = 1/f - float4 _ZBufferParams; - - // x = 1 or -1 (-1 if projection is flipped) - // y = near plane - // z = far plane - // w = 1/far plane - float4 _ProjectionParams; - - // x = orthographic camera's width - // y = orthographic camera's height - // z = unused - // w = 1.0 if camera is ortho, 0.0 if perspective - float4 unity_OrthoParams; - - // x = width - // y = height - // z = 1 + 1.0/width - // w = 1 + 1.0/height - float4 _ScreenParams; - - float4 _FrustumPlanes[6]; // { (a, b, c) = N, d = -dot(N, P) } [L, R, T, B, N, F] - float4 _ShadowFrustumPlanes[6]; // { (a, b, c) = N, d = -dot(N, P) } [L, R, T, B, N, F] - - // TAA Frame Index ranges from 0 to 7. - float4 _TaaFrameInfo; // { taaSharpenStrength, unused, taaFrameIndex, taaEnabled ? 1 : 0 } - - // Current jitter strength (0 if TAA is disabled) - float4 _TaaJitterStrength; // { x, y, x/width, y/height } - - // t = animateMaterials ? Time.realtimeSinceStartup : 0. - // We keep all those time value for compatibility with legacy unity but prefer _TimeParameters instead. - float4 _Time; // { t/20, t, t*2, t*3 } - float4 _SinTime; // { sin(t/8), sin(t/4), sin(t/2), sin(t) } - float4 _CosTime; // { cos(t/8), cos(t/4), cos(t/2), cos(t) } - float4 unity_DeltaTime; // { dt, 1/dt, smoothdt, 1/smoothdt } - float4 _TimeParameters; // { t, sin(t), cos(t) } - float4 _LastTimeParameters; // { t, sin(t), cos(t) } - - // Volumetric lighting. - float4 _AmbientProbeCoeffs[7]; // 3 bands of SH, packed, rescaled and convolved with the phase function - - float3 _HeightFogBaseScattering; - float _HeightFogBaseExtinction; - - float2 _HeightFogExponents; // { 1/H, H } - float _HeightFogBaseHeight; - float _GlobalFogAnisotropy; - - float4 _VBufferViewportSize; // { w, h, 1/w, 1/h } - uint _VBufferSliceCount; - float _VBufferRcpSliceCount; - float _VBufferRcpInstancedViewCount; // Used to remap VBuffer coordinates for XR - - float _ContactShadowOpacity; - float4 _VBufferSharedUvScaleAndLimit; // Necessary us to work with sub-allocation (resource aliasing) in the RTHandle system - - float4 _VBufferDistanceEncodingParams; // See the call site for description - float4 _VBufferDistanceDecodingParams; // See the call site for description - - // TODO: these are only used for reprojection. - // Once reprojection is performed in a separate pass, we should probably - // move these to a dedicated CBuffer to avoid polluting the global one. - float4 _VBufferPrevViewportSize; - float4 _VBufferHistoryPrevUvScaleAndLimit; - float4 _VBufferPrevDepthEncodingParams; - float4 _VBufferPrevDepthDecodingParams; - - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.hlsl" - - #define DEFAULT_LIGHT_LAYERS 0xFF - uint _EnableLightLayers; - float _ReplaceDiffuseForIndirect; - uint _EnableSkyReflection; - - uint _EnableSSRefraction; - - uint _OffScreenRendering; - uint _OffScreenDownsampleFactor; - - uint _XRViewCount; - int _FrameCount; - - float _ProbeExposureScale; - int _UseRayTracedReflections; - int _RaytracingFrameIndex; - - float4 _CoarseStencilBufferSize; +// TODO: these are only used for reprojection. +// Once reprojection is performed in a separate pass, we should probably +// move these to a dedicated CBuffer to avoid polluting the global one. +// $$$ Volumetric only? +float4 _AmbientProbeCoeffs[7]; // 3 bands of SH, packed, rescaled and convolved with the phase function +float _GlobalFogAnisotropy; -CBUFFER_END +float4 _VBufferPrevViewportSize; +float4 _VBufferHistoryPrevUvScaleAndLimit; +float4 _VBufferPrevDepthEncodingParams; +float4 _VBufferPrevDepthDecodingParams; // Custom generated by HDRP, not from Unity Engine (passed in via HDCamera) #if defined(USING_STEREO_MATRICES) @@ -491,13 +368,10 @@ float4x4 GetRawUnityWorldToObject() { return unity_WorldToObject; } #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl" // This is located after the include of UnityInstancing.hlsl so it can be used for declaration -// Undef in order to include all textures and buffers declarations -#undef SHADER_VARIABLES_INCLUDE_CB #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/ShaderVariablesSubsurfaceScattering.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesFunctions.hlsl" diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs new file mode 100644 index 00000000000..d17da4bb620 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -0,0 +1,237 @@ +namespace UnityEngine.Rendering.HighDefinition +{ + // We need to keep the number of different constant buffers low. + // Indeed, those are bound for every single drawcall so if we split things in various CB (lightloop, SSS, Fog, etc) + // We multiply the number of CB we have to bind per drawcall. + // This is why this CB is big. + // It should only contain 2 sorts of things: + // - Global data for a camera (view matrices, RTHandle stuff, etc) + // - Things that are needed per draw call (like fog or lighting info for forward rendering) + // Anything else (such as engine passes) can have their own constant buffers (and still use this one as well). + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + unsafe struct ShaderVariablesGlobal + { + public const int defaultLightLayers = 0xFF; + + // TODO: put commonly used vars together (below), and then sort them by the frequency of use (descending). + // Note: a matrix is 4 * 4 * 4 = 64 bytes (1x cache line), so no need to sort those. + + // ================================ + // PER VIEW CONSTANTS + // ================================ + // TODO: all affine matrices should be 3x4. + public Matrix4x4 _ViewMatrix; + public Matrix4x4 _InvViewMatrix; + public Matrix4x4 _ProjMatrix; + public Matrix4x4 _InvProjMatrix; + public Matrix4x4 _ViewProjMatrix; + public Matrix4x4 _CameraViewProjMatrix; + public Matrix4x4 _InvViewProjMatrix; + public Matrix4x4 _NonJitteredViewProjMatrix; + public Matrix4x4 _PrevViewProjMatrix; // non-jittered + public Matrix4x4 _PrevInvViewProjMatrix; // non-jittered + +#if !USING_STEREO_MATRICES + public Vector3 _WorldSpaceCameraPos; + public float _Pad0; + public Vector3 _PrevCamPosRWS; // $$$ + public float _Pad1; +#endif + public Vector4 _ScreenSize; // { w, h, 1 / w, 1 / h } + + // Those two uniforms are specific to the RTHandle system + public Vector4 _RTHandleScale; // { w / RTHandle.maxWidth, h / RTHandle.maxHeight } : xy = currFrame, zw = prevFrame + public Vector4 _RTHandleScaleHistory; // Same as above but the RTHandle handle size is that of the history buffer + + // Values used to linearize the Z buffer (http://www.humus.name/temp/Linearize%20depth.txt) + // x = 1 - f/n + // y = f/n + // z = 1/f - 1/n + // w = 1/n + // or in case of a reversed depth buffer (UNITY_REVERSED_Z is 1) + // x = -1 + f/n + // y = 1 + // z = -1/n + -1/f + // w = 1/f + public Vector4 _ZBufferParams; + + // x = 1 or -1 (-1 if projection is flipped) + // y = near plane + // z = far plane + // w = 1/far plane + public Vector4 _ProjectionParams; + + // x = orthographic camera's width + // y = orthographic camera's height + // z = unused + // w = 1.0 if camera is ortho, 0.0 if perspective + public Vector4 unity_OrthoParams; + + // x = width + // y = height + // z = 1 + 1.0/width + // w = 1 + 1.0/height + public Vector4 _ScreenParams; // $$$ used only by vfx? + + [HLSLArray(6, typeof(Vector4))] + public fixed float _FrustumPlanes[6 * 4]; // { (a, b, c) = N, d = -dot(N, P) } [L, R, T, B, N, F] + + [HLSLArray(6, typeof(Vector4))] + public fixed float _ShadowFrustumPlanes[6 * 4]; // { (a, b, c) = N, d = -dot(N, P) } [L, R, T, B, N, F] + + // TAA Frame Index ranges from 0 to 7. + public Vector4 _TaaFrameInfo; // { taaSharpenStrength, unused, taaFrameIndex, taaEnabled ? 1 : 0 } + + // Current jitter strength (0 if TAA is disabled) + public Vector4 _TaaJitterStrength; // { x, y, x/width, y/height } + + // t = animateMaterials ? Time.realtimeSinceStartup : 0. + // We keep all those time value for compatibility with legacy unity but prefer _TimeParameters instead. + public Vector4 _Time; // { t/20, t, t*2, t*3 } + public Vector4 _SinTime; // { sin(t/8), sin(t/4), sin(t/2), sin(t) } + public Vector4 _CosTime; // { cos(t/8), cos(t/4), cos(t/2), cos(t) } + public Vector4 unity_DeltaTime; // { dt, 1/dt, smoothdt, 1/smoothdt } + public Vector4 _TimeParameters; // { t, sin(t), cos(t) } + public Vector4 _LastTimeParameters; // { t, sin(t), cos(t) } + + // Volumetric lighting. + public Vector3 _HeightFogBaseScattering; + public float _HeightFogBaseExtinction; + + public Vector2 _HeightFogExponents; // { 1/H, H } + public float _HeightFogBaseHeight; + + public Vector4 _VBufferViewportSize; // { w, h, 1/w, 1/h } + + public uint _VBufferSliceCount; + public float _VBufferRcpSliceCount; + public float _VBufferRcpInstancedViewCount; // Used to remap VBuffer coordinates for XR + public float _ContactShadowOpacity; + + public Vector4 _VBufferSharedUvScaleAndLimit; // Necessary us to work with sub-allocation (resource aliasing) in the RTHandle system + + public Vector4 _VBufferDistanceEncodingParams; // See the call site for description + public Vector4 _VBufferDistanceDecodingParams; // See the call site for description + + public float _VBufferLastSliceDist; // The distance to the middle of the last slice + public int _EnableVolumetricFog; // bool... + + + + // Light Loop + public const int s_MaxEnv2DLight = 32; + + [HLSLArray(0, typeof(Vector4))] + public fixed float _ShadowAtlasSize[4]; + [HLSLArray(0, typeof(Vector4))] + public fixed float _CascadeShadowAtlasSize[4]; + [HLSLArray(0, typeof(Vector4))] + public fixed float _AreaShadowAtlasSize[4]; + + [HLSLArray(s_MaxEnv2DLight, typeof(Matrix4x4))] + public fixed float _Env2DCaptureVP[s_MaxEnv2DLight * 4 * 4]; + [HLSLArray(s_MaxEnv2DLight * 3, typeof(float))] + public fixed float _Env2DCaptureForward[s_MaxEnv2DLight * 3]; + [HLSLArray(s_MaxEnv2DLight, typeof(Vector4))] + public fixed float _Env2DAtlasScaleOffset[s_MaxEnv2DLight * 3]; + + public uint _DirectionalLightCount; + public uint _PunctualLightCount; + public uint _AreaLightCount; + public uint _EnvLightCount; + + public int _EnvLightSkyEnabled; // TODO: make it a bool + public uint _CascadeShadowCount; + public int _DirectionalShadowIndex; + public uint _EnableLightLayers; + + public float _ReplaceDiffuseForIndirect; + public uint _EnableSkyReflection; + public uint _EnableSSRefraction; + public float _MicroShadowOpacity; + + public float _DirectionalTransmissionMultiplier; + + public Vector4 _CookieAtlasSize; + public Vector4 _CookieAtlasData; + public Vector4 _PlanarAtlasData; + + // Tile/Cluster + public uint _NumTileFtplX; + public uint _NumTileFtplY; + public float g_fClustScale; + public float g_fClustBase; + + public float g_fNearPlane; + public float g_fFarPlane; + public int g_iLog2NumClusters; // We need to always define these to keep constant buffer layouts compatible + public uint g_isLogBaseBufferEnabled; + + public uint _NumTileClusteredX; + public uint _NumTileClusteredY; + public int _EnvSliceSize; + + // Uniform variables that defines if we should be using the raytraced indirect diffuse + public int _RaytracedIndirectDiffuse; + + // Buffer pyramid + public Vector4 _CameraMotionVectorsSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size + public Vector4 _ColorPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused + public Vector4 _DepthPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused + public Vector4 _CameraMotionVectorsScale; // (x,y) = Screen Scale, z = lod count, w = unused + + // Ambient occlusion + public Vector4 _AmbientOcclusionParam; // xyz occlusion color, w directLightStrenght + + public Vector4 _IndirectLightingMultiplier; // .x indirect diffuse multiplier (use with indirect lighting volume controler) + + // Screen space refraction + public float _SSRefractionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback + + // Atmospheric scattering + // Common + public int _FogEnabled; + public int _PBRFogEnabled; + public float _MaxFogDistance; + public float _FogColorMode; + public float _SkyTextureMipCount; + public Vector4 _FogColor; // color in rgb + public Vector4 _MipFogParameters; + + // Subsurface scattering + // Use float4 to avoid any packing issue between compute and pixel shaders + [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(Vector4))] + public fixed float _ThicknessRemaps[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // R: start, G = end - start, BA unused + [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(Vector4))] + public fixed float _ShapeParams[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // RGB = S = 1 / D, A = filter radius + [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(Vector4))] + public fixed float _TransmissionTintsAndFresnel0[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // RGB = 1/4 * color, A = fresnel0 + [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(Vector4))] + public fixed float _WorldScales[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // X = meters per world unit; Y = world units per meter + [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(float))] + public fixed uint _DiffusionProfileHashTable[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT]; // TODO: constant + + // Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system. + // Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader. + public uint _EnableSubsurfaceScattering; // Globally toggles subsurface and transmission scattering on/off + public float _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter + public float _TransmissionFlags; // 1 bit/profile; 0 = regular, 1 = thin + public uint _DiffusionProfileCount; + + // Decals + public Vector2 _DecalAtlasResolution; + public uint _EnableDecals; + public uint _DecalCount; + + public uint _OffScreenRendering; + public uint _OffScreenDownsampleFactor; + public uint _XRViewCount; + public int _FrameCount; + + public float _ProbeExposureScale; + public int _UseRayTracedReflections; + public int _RaytracingFrameIndex; + + public Vector4 _CoarseStencilBufferSize; + } +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl new file mode 100644 index 00000000000..3b90cfd1487 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -0,0 +1,133 @@ +// +// This file was automatically generated. Please don't edit by hand. +// + +#ifndef SHADERVARIABLESGLOBAL_CS_HLSL +#define SHADERVARIABLESGLOBAL_CS_HLSL +// +// UnityEngine.Rendering.HighDefinition.ShaderVariablesGlobal: static fields +// +#define DEFAULT_LIGHT_LAYERS (255) +#define MAX_ENV2DLIGHT (32) + +// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesGlobal +// PackingRules = Exact +cbuffer ShaderVariablesGlobal +{ + float4x4 _ViewMatrix; + float4x4 _InvViewMatrix; + float4x4 _ProjMatrix; + float4x4 _InvProjMatrix; + float4x4 _ViewProjMatrix; + float4x4 _CameraViewProjMatrix; + float4x4 _InvViewProjMatrix; + float4x4 _NonJitteredViewProjMatrix; + float4x4 _PrevViewProjMatrix; + float4x4 _PrevInvViewProjMatrix; + float3 _WorldSpaceCameraPos_Internal; + float _Pad0; + float3 _PrevCamPosRWS_Internal; + float _Pad1; + float4 _ScreenSize; + float4 _RTHandleScale; + float4 _RTHandleScaleHistory; + float4 _ZBufferParams; + float4 _ProjectionParams; + float4 unity_OrthoParams; + float4 _ScreenParams; + float4 _FrustumPlanes[6]; + float4 _ShadowFrustumPlanes[6]; + float4 _TaaFrameInfo; + float4 _TaaJitterStrength; + float4 _Time; + float4 _SinTime; + float4 _CosTime; + float4 unity_DeltaTime; + float4 _TimeParameters; + float4 _LastTimeParameters; + float3 _HeightFogBaseScattering; + float _HeightFogBaseExtinction; + float2 _HeightFogExponents; + float _HeightFogBaseHeight; + float4 _VBufferViewportSize; + uint _VBufferSliceCount; + float _VBufferRcpSliceCount; + float _VBufferRcpInstancedViewCount; + float _ContactShadowOpacity; + float4 _VBufferSharedUvScaleAndLimit; + float4 _VBufferDistanceEncodingParams; + float4 _VBufferDistanceDecodingParams; + float _VBufferLastSliceDist; + int _EnableVolumetricFog; + float4 _ShadowAtlasSize; + float4 _CascadeShadowAtlasSize; + float4 _AreaShadowAtlasSize; + float4x4 _Env2DCaptureVP[32]; + float _Env2DCaptureForward[96]; + float4 _Env2DAtlasScaleOffset[32]; + uint _DirectionalLightCount; + uint _PunctualLightCount; + uint _AreaLightCount; + uint _EnvLightCount; + int _EnvLightSkyEnabled; + uint _CascadeShadowCount; + int _DirectionalShadowIndex; + uint _EnableLightLayers; + float _ReplaceDiffuseForIndirect; + uint _EnableSkyReflection; + uint _EnableSSRefraction; + float _MicroShadowOpacity; + float _DirectionalTransmissionMultiplier; + float4 _CookieAtlasSize; + float4 _CookieAtlasData; + float4 _PlanarAtlasData; + uint _NumTileFtplX; + uint _NumTileFtplY; + float g_fClustScale; + float g_fClustBase; + float g_fNearPlane; + float g_fFarPlane; + int g_iLog2NumClusters; + uint g_isLogBaseBufferEnabled; + uint _NumTileClusteredX; + uint _NumTileClusteredY; + int _EnvSliceSize; + int _RaytracedIndirectDiffuse; + float4 _CameraMotionVectorsSize; + float4 _ColorPyramidScale; + float4 _DepthPyramidScale; + float4 _CameraMotionVectorsScale; + float4 _AmbientOcclusionParam; + float4 _IndirectLightingMultiplier; + float _SSRefractionInvScreenWeightDistance; + int _FogEnabled; + int _PBRFogEnabled; + float _MaxFogDistance; + float _FogColorMode; + float _SkyTextureMipCount; + float4 _FogColor; + float4 _MipFogParameters; + float4 _ThicknessRemaps[16]; + float4 _ShapeParams[16]; + float4 _TransmissionTintsAndFresnel0[16]; + float4 _WorldScales[16]; + float _DiffusionProfileHashTable[16]; + uint _EnableSubsurfaceScattering; + float _TexturingModeFlags; + float _TransmissionFlags; + uint _DiffusionProfileCount; + float2 _DecalAtlasResolution; + uint _EnableDecals; + uint _DecalCount; + uint _OffScreenRendering; + uint _OffScreenDownsampleFactor; + uint _XRViewCount; + int _FrameCount; + float _ProbeExposureScale; + int _UseRayTracedReflections; + int _RaytracingFrameIndex; + float4 _CoarseStencilBufferSize; +}; + + +#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl.meta similarity index 80% rename from com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs.hlsl.meta rename to com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl.meta index 4327d62aa02..b7628864641 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.cs.hlsl.meta +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c032094ad53399f47b6f7ab8720b929a +guid: 6e0fdcd3c439283408fa825c454499a2 ShaderImporter: externalObjects: {} defaultTextures: [] diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.meta b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.meta similarity index 83% rename from com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.meta rename to com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.meta index aa199a0f7a9..08e41050789 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceLighting.cs.meta +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: b827749bf59c7434dbff1195f5945ea5 +guid: 8924b92541d1e61408dd8ef938e7453c MonoImporter: externalObjects: {} serializedVersion: 2 From 7129c814543df28ed0844cd80b65011d0a389b5f Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 5 Mar 2020 10:12:13 +0100 Subject: [PATCH 24/92] post merge fix --- .../Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs index 94a8e84195c..498cd19d8fb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs @@ -255,11 +255,7 @@ public void Render( RenderGraph renderGraph, class FinalPassData { - public FinalPassParameters parameters; - public RenderGraphResource source; - public RenderGraphResource afterPostProcessTexture; - public RenderGraphResource alphaTexture; - public RenderGraphMutableResource destination; + public FinalPassParameters parameters; public TextureHandle source; public TextureHandle afterPostProcessTexture; public TextureHandle alphaTexture; From 502b3a776b176f8d7d4382357616c733a1cef137 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 5 Mar 2020 10:17:53 +0100 Subject: [PATCH 25/92] Removed useless comment. --- .../Runtime/PostProcessing/PostProcessSystem.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs index 733ad41232b..7c6520f7f84 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs @@ -834,7 +834,6 @@ void PrepareExposureCurveData(AnimationCurve curve, out float min, out float max m_ExposureCurveTexture.Apply(); } - // TODO: Handle light buffer as a source for average luminance void DoDynamicExposure(CommandBuffer cmd, HDCamera camera, RTHandle colorBuffer) { var cs = m_Resources.shaders.exposureCS; From 49fd96fb5ad8b852c79b5429a3de95d668ae0c35 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 5 Mar 2020 11:04:57 +0100 Subject: [PATCH 26/92] Missing doc --- .../Runtime/RenderGraph/RenderGraph.cs | 5 +++++ .../RenderGraph/RenderGraphResourceRegistry.cs | 18 ++++++++++++++++++ .../Runtime/Textures/RTHandleSystem.cs | 5 +++++ .../Runtime/Textures/RTHandles.cs | 5 +++++ .../Runtime/Debug/LightingDebug.cs | 9 +++++++++ 5 files changed, 42 insertions(+) diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs index 1106e7c0604..57421b3576e 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs @@ -247,6 +247,11 @@ public TextureHandle ImportTexture(RTHandle rt, int shaderProperty = 0) return m_Resources.ImportTexture(rt, shaderProperty); } + /// + /// Import the final backbuffer to render graph. + /// + /// Backbuffer render target identifier. + /// A new TextureHandle for the backbuffer. public TextureHandle ImportBackbuffer(RenderTargetIdentifier rt) { return m_Resources.ImportBackbuffer(rt); diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs index c5623a92c14..0f37805eed2 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs @@ -19,7 +19,16 @@ public struct TextureHandle bool m_IsValid; internal int handle { get; private set; } internal TextureHandle(int handle) { this.handle = handle; m_IsValid = true; } + /// + /// Conversion to int. + /// + /// Texture handle to convert. + /// The integer representation of the handle. public static implicit operator int(TextureHandle handle) { return handle.handle; } + /// + /// Return true if the handle is valid. + /// + /// True if the handle is valid. public bool IsValid() => m_IsValid; } @@ -32,7 +41,16 @@ public struct RendererListHandle bool m_IsValid; internal int handle { get; private set; } internal RendererListHandle(int handle) { this.handle = handle; m_IsValid = true; } + /// + /// Conversion to int. + /// + /// Renderer List handle to convert. + /// The integer representation of the handle. public static implicit operator int(RendererListHandle handle) { return handle.handle; } + /// + /// Return true if the handle is valid. + /// + /// True if the handle is valid. public bool IsValid() => m_IsValid; } diff --git a/com.unity.render-pipelines.core/Runtime/Textures/RTHandleSystem.cs b/com.unity.render-pipelines.core/Runtime/Textures/RTHandleSystem.cs index 16f9c35ab5f..e5ce6686619 100644 --- a/com.unity.render-pipelines.core/Runtime/Textures/RTHandleSystem.cs +++ b/com.unity.render-pipelines.core/Runtime/Textures/RTHandleSystem.cs @@ -767,6 +767,11 @@ public RTHandle Alloc(Texture texture) return rth; } + /// + /// Allocate a RTHandle from a regular render target identifier. + /// + /// Input render target identifier. + /// A new RTHandle referencing the input render target identifier. public RTHandle Alloc(RenderTargetIdentifier texture) { var rth = new RTHandle(this); diff --git a/com.unity.render-pipelines.core/Runtime/Textures/RTHandles.cs b/com.unity.render-pipelines.core/Runtime/Textures/RTHandles.cs index d4de4a4022c..a2d7c95c04b 100644 --- a/com.unity.render-pipelines.core/Runtime/Textures/RTHandles.cs +++ b/com.unity.render-pipelines.core/Runtime/Textures/RTHandles.cs @@ -230,6 +230,11 @@ public static RTHandle Alloc(Texture tex) return s_DefaultInstance.Alloc(tex); } + /// + /// Allocate a RTHandle from a regular render target identifier for the default RTHandle system. + /// + /// Input render target identifier. + /// A new RTHandle referencing the input render target identifier. public static RTHandle Alloc(RenderTargetIdentifier tex) { return s_DefaultInstance.Alloc(tex); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs index 6c1f2632a46..efae113c0ad 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs @@ -66,14 +66,23 @@ public enum DebugLightFilterMode [Flags] public enum DebugLightLayersMask { + /// No light layer debug. None = 0, + /// Debug light layer 1. LightLayer1 = 1 << 0, + /// Debug light layer 2. LightLayer2 = 1 << 1, + /// Debug light layer 3. LightLayer3 = 1 << 2, + /// Debug light layer 4. LightLayer4 = 1 << 3, + /// Debug light layer 5. LightLayer5 = 1 << 4, + /// Debug light layer 6. LightLayer6 = 1 << 5, + /// Debug light layer 7. LightLayer7 = 1 << 6, + /// Debug light layer 8. LightLayer8 = 1 << 7, } From 4aec3b9465560c50b91f02e09f1432a4c0ba2801 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 5 Mar 2020 17:09:11 +0100 Subject: [PATCH 27/92] Started moving cmd.SetGlobalXXX to update the global CB (WIP) --- .../Runtime/Common/ConstantBuffer.cs | 27 ++++++ .../Runtime/Common/ConstantBuffer.cs.meta | 11 +++ .../Lighting/AtmosphericScattering/Fog.cs | 60 ++++++------ .../ScreenSpaceLighting/AmbientOcclusion.cs | 8 +- .../ScreenSpaceRefraction.cs | 36 ------- .../VolumetricLighting/VolumetricLighting.cs | 7 -- .../SubsurfaceScattering.hlsl | 6 +- .../SubsurfaceScatteringManager.cs | 42 ++++---- .../Runtime/RenderPipeline/Camera/HDCamera.cs | 69 ++++++------- .../RenderPipeline/HDRenderPipeline.cs | 96 +++++++++++-------- .../ShaderLibrary/ShaderVariables.hlsl | 1 - .../ShaderLibrary/ShaderVariablesGlobal.cs | 31 +++--- 12 files changed, 198 insertions(+), 196 deletions(-) create mode 100644 com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs create mode 100644 com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs.meta diff --git a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs new file mode 100644 index 00000000000..3c1f5f15ea7 --- /dev/null +++ b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs @@ -0,0 +1,27 @@ +using Unity.Collections.LowLevel.Unsafe; + +namespace UnityEngine.Rendering +{ + public class ConstantBuffer where CBType : struct + { + CBType[] m_Data = new CBType[1]; // Array is required by the ComputeBuffer SetData API + ComputeBuffer m_GPUConstantBuffer = null; + + public ref CBType data => ref m_Data[0]; + + public ConstantBuffer() + { + m_GPUConstantBuffer = new ComputeBuffer(1, UnsafeUtility.SizeOf(), ComputeBufferType.Constant); + } + + public void Commit(CommandBuffer cmd) + { + cmd.SetComputeBufferData(m_GPUConstantBuffer, m_Data); + } + + public void Release() + { + CoreUtils.SafeRelease(m_GPUConstantBuffer); + } + } +} diff --git a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs.meta b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs.meta new file mode 100644 index 00000000000..647bc354cee --- /dev/null +++ b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6d9f50d0a621c534987e1e47d723d06e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs index 733c81fa19b..7d97328d88a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs @@ -9,11 +9,6 @@ namespace UnityEngine.Rendering.HighDefinition [Serializable, VolumeComponentMenu("Fog/Fog")] public class Fog : VolumeComponent { - // Fog Color - static readonly int m_ColorModeParam = Shader.PropertyToID("_FogColorMode"); - static readonly int m_FogColorParam = Shader.PropertyToID("_FogColor"); - static readonly int m_MipFogParam = Shader.PropertyToID("_MipFogParameters"); - /// Enable fog. [Tooltip("Enables the fog.")] public BoolParameter enabled = new BoolParameter(false); @@ -102,49 +97,48 @@ static float ScaleHeightFromLayerDepth(float d) return d * 0.144765f; } - internal static void PushNeutralShaderParameters(CommandBuffer cmd) + static void UpdateShaderVariablesGlobalCBNeutralParameters(ConstantBuffer cb) { - cmd.SetGlobalInt(HDShaderIDs._FogEnabled, 0); - cmd.SetGlobalInt(HDShaderIDs._EnableVolumetricFog, 0); - cmd.SetGlobalVector(HDShaderIDs._HeightFogBaseScattering, Vector3.zero); - cmd.SetGlobalFloat(HDShaderIDs._HeightFogBaseExtinction, 0.0f); - cmd.SetGlobalVector(HDShaderIDs._HeightFogExponents, Vector2.one); - cmd.SetGlobalFloat(HDShaderIDs._HeightFogBaseHeight, 0.0f); - cmd.SetGlobalFloat(HDShaderIDs._GlobalFogAnisotropy, 0.0f); + cb.data._FogEnabled = 0; + cb.data._EnableVolumetricFog = 0; + cb.data._HeightFogBaseScattering = Vector3.zero; + cb.data._HeightFogBaseExtinction = 0.0f; + cb.data._HeightFogExponents = Vector2.one; + cb.data._HeightFogBaseHeight = 0.0f; + cb.data._GlobalFogAnisotropy = 0.0f; } - internal static void PushFogShaderParameters(HDCamera hdCamera, CommandBuffer cmd) + internal static void UpdateShaderVariablesGlobalCB(ConstantBuffer cb, HDCamera hdCamera) { // TODO Handle user override var fogSettings = hdCamera.volumeStack.GetComponent(); if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.AtmosphericScattering) || !fogSettings.enabled.value) { - PushNeutralShaderParameters(cmd); - return; + UpdateShaderVariablesGlobalCBNeutralParameters(cb); + } + else + { + fogSettings.UpdateShaderVariablesGlobalCBFogParameters(cb, hdCamera); } - - fogSettings.PushShaderParameters(hdCamera, cmd); - - cmd.SetGlobalInt(HDShaderIDs._PBRFogEnabled, IsPBRFogEnabled(hdCamera) ? 1 : 0); } - internal virtual void PushShaderParameters(HDCamera hdCamera, CommandBuffer cmd) + void UpdateShaderVariablesGlobalCBFogParameters(ConstantBuffer cb, HDCamera hdCamera) { - cmd.SetGlobalInt(HDShaderIDs._FogEnabled, 1); - cmd.SetGlobalFloat(HDShaderIDs._MaxFogDistance, maxFogDistance.value); + cb.data._FogEnabled = 1; + cb.data._MaxFogDistance = maxFogDistance.value; // Fog Color Color fogColor = (colorMode.value == FogColorMode.ConstantColor) ? color.value : tint.value; - cmd.SetGlobalFloat(m_ColorModeParam, (float)colorMode.value); - cmd.SetGlobalColor(m_FogColorParam, new Color(fogColor.r, fogColor.g, fogColor.b, 0.0f)); - cmd.SetGlobalVector(m_MipFogParam, new Vector4(mipFogNear.value, mipFogFar.value, mipFogMaxMip.value, 0.0f)); + cb.data._FogColorMode = (float)colorMode.value; + cb.data._FogColor = new Color(fogColor.r, fogColor.g, fogColor.b, 0.0f); + cb.data._MipFogParameters = new Vector4(mipFogNear.value, mipFogFar.value, mipFogMaxMip.value, 0.0f); DensityVolumeArtistParameters param = new DensityVolumeArtistParameters(albedo.value, meanFreePath.value, anisotropy.value); DensityVolumeEngineData data = param.ConvertToEngineData(); - cmd.SetGlobalVector(HDShaderIDs._HeightFogBaseScattering, data.scattering); - cmd.SetGlobalFloat(HDShaderIDs._HeightFogBaseExtinction, data.extinction); + cb.data._HeightFogBaseScattering = data.scattering; + cb.data._HeightFogBaseExtinction = data.extinction; float crBaseHeight = baseHeight.value; @@ -155,12 +149,14 @@ internal virtual void PushShaderParameters(HDCamera hdCamera, CommandBuffer cmd) float layerDepth = Mathf.Max(0.01f, maximumHeight.value - baseHeight.value); float H = ScaleHeightFromLayerDepth(layerDepth); - cmd.SetGlobalVector(HDShaderIDs._HeightFogExponents, new Vector2(1.0f / H, H)); - cmd.SetGlobalFloat(HDShaderIDs._HeightFogBaseHeight, crBaseHeight); + cb.data._HeightFogExponents = new Vector2(1.0f / H, H); + cb.data._HeightFogBaseHeight = crBaseHeight; bool enableVolumetrics = enableVolumetricFog.value && hdCamera.frameSettings.IsEnabled(FrameSettingsField.Volumetrics); - cmd.SetGlobalFloat(HDShaderIDs._GlobalFogAnisotropy, anisotropy.value); - cmd.SetGlobalInt(HDShaderIDs._EnableVolumetricFog, enableVolumetrics ? 1 : 0); + cb.data._GlobalFogAnisotropy = anisotropy.value; + cb.data._EnableVolumetricFog = enableVolumetrics ? 1 : 0; + + cb.data._PBRFogEnabled = IsPBRFogEnabled(hdCamera) ? 1 : 0; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs index 3ec51949f46..d2e913e8dcc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs @@ -344,7 +344,7 @@ RenderAOParameters PrepareRenderAOParameters(HDCamera camera, RTHandleProperties float scaleFactor = (parameters.runningRes.x * parameters.runningRes.y) / (540.0f * 960.0f); float radInPixels = Mathf.Max(16, settings.maximumRadiusInPixels * Mathf.Sqrt(scaleFactor)); - + parameters.aoParams2 = new Vector4( historySize.x, @@ -592,13 +592,13 @@ internal void Dispatch(CommandBuffer cmd, HDCamera camera, int frameCount) } } - internal void PushGlobalParameters(HDCamera hdCamera, CommandBuffer cmd) + internal void UpdateShaderVariableGlobalCB(ConstantBuffer cb, HDCamera hdCamera) { var settings = hdCamera.volumeStack.GetComponent(); if (IsActive(hdCamera, settings)) - cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, new Vector4(0f, 0f, 0f, settings.directLightingStrength.value)); + cb.data._AmbientOcclusionParam = new Vector4(0f, 0f, 0f, settings.directLightingStrength.value); else - cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, Vector4.zero); + cb.data._AmbientOcclusionParam = Vector4.zero; } internal void PostDispatchWork(CommandBuffer cmd, HDCamera camera) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceRefraction.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceRefraction.cs index e3bc5a5144c..b129781252c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceRefraction.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceRefraction.cs @@ -16,46 +16,10 @@ internal enum RefractionModel Thin = 3 }; - int m_InvScreenFadeDistanceID; - /// /// Controls the distance at which HDRP fades out Screen Space Refraction near the edge of the screen. A value near 0 indicates a small fade distance at the edges, /// while increasing the value towards one will start the fade closer to the center of the screen. /// public ClampedFloatParameter screenFadeDistance = new ClampedFloatParameter(0.1f, 0.001f, 1.0f); - - static ScreenSpaceRefraction s_Default = null; - - internal static ScreenSpaceRefraction defaultInstance - { - get - { - if (s_Default == null) - { - s_Default = ScriptableObject.CreateInstance(); - s_Default.hideFlags = HideFlags.HideAndDontSave; - } - return s_Default; - } - } - - internal virtual void PushShaderParameters(CommandBuffer cmd) - { - cmd.SetGlobalFloat(m_InvScreenFadeDistanceID, 1.0f / screenFadeDistance.value); - } - - void FetchIDs( - out int invScreenWeightDistanceID) - { - invScreenWeightDistanceID = HDShaderIDs._SSRefractionInvScreenWeightDistance; - } - - void Awake() - { - FetchIDs( - out m_InvScreenFadeDistanceID - ); - } - } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 9223982671b..33092267cd9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -474,14 +474,7 @@ void PushVolumetricLightingGlobalParams(HDCamera hdCamera, CommandBuffer cmd, in if (hdCamera.IsVolumetricReprojectionEnabled()) { var historyRT = hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.VolumetricLighting); - historyBufferSize = new Vector2Int(historyRT.rt.width, historyRT.rt.height); - - // Handle case of first frame. When we are on the first frame, we reuse the value of original frame. - if (historyBufferSize.x == 0.0f && historyBufferSize.y == 0.0f) - { - historyBufferSize = sharedBufferSize; - } } var cvp = currFrameParams.viewportSize; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl index 86c3f476025..84ddd85cd79 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl @@ -224,14 +224,14 @@ uint FindDiffusionProfileIndex(uint diffusionProfileHash) { if (diffusionProfileHash == 0) return 0; - + uint diffusionProfileIndex = 0; uint i = 0; - + // Fetch the 4 bit index number by looking for the diffusion profile unique ID: for (i = 0; i < _DiffusionProfileCount; i++) { - if (asuint(_DiffusionProfileHashTable[i]) == diffusionProfileHash) + if (DiffusionProfileHashTable[i] == diffusionProfileHash) { diffusionProfileIndex = i; break; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index 30990c05cf2..44ea6b714dd 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -29,7 +29,7 @@ public partial class HDRenderPipeline Vector4[] m_SSSDisabledTransmissionTintsAndFresnel0; Vector4[] m_SSSWorldScales; Vector4[] m_SSSFilterKernels; - float[] m_SSSDiffusionProfileHashes; + uint[] m_SSSDiffusionProfileHashes; int[] m_SSSDiffusionProfileUpdate; DiffusionProfileSettings[] m_SSSSetDiffusionProfiles; DiffusionProfileSettings m_SSSDefaultDiffusionProfile; @@ -79,7 +79,7 @@ void InitSSSBuffers() m_SSSDisabledTransmissionTintsAndFresnel0 = new Vector4[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT]; m_SSSWorldScales = new Vector4[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT]; m_SSSFilterKernels = new Vector4[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * DiffusionProfileConstants.SSS_N_SAMPLES_NEAR_FIELD]; - m_SSSDiffusionProfileHashes = new float[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT]; + m_SSSDiffusionProfileHashes = new uint[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT]; m_SSSDiffusionProfileUpdate = new int[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT]; m_SSSSetDiffusionProfiles = new DiffusionProfileSettings[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT]; } @@ -178,7 +178,7 @@ void SetDiffusionProfileAtIndex(DiffusionProfileSettings settings, int index) m_SSSFilterKernels[n * index + j].w = settings.profile.filterKernelFarField[j].y; } } - m_SSSDiffusionProfileHashes[index] = HDShadowUtils.Asfloat(settings.profile.hash); + m_SSSDiffusionProfileHashes[index] = settings.profile.hash; // Erase previous value (This need to be done here individually as in the SSS editor we edit individual component) uint mask = 1u << index; @@ -192,32 +192,30 @@ void SetDiffusionProfileAtIndex(DiffusionProfileSettings settings, int index) m_SSSDiffusionProfileUpdate[index] = settings.updateCount; } - void PushSubsurfaceScatteringGlobalParams(HDCamera hdCamera, CommandBuffer cmd) + unsafe void UpdateShaderVariablesGlobalSubsurface(ConstantBuffer cb, HDCamera hdCamera) { UpdateCurrentDiffusionProfileSettings(hdCamera); - cmd.SetGlobalInt(HDShaderIDs._DiffusionProfileCount, m_SSSActiveDiffusionProfileCount); - - if (m_SSSActiveDiffusionProfileCount == 0) - return ; + cb.data._DiffusionProfileCount = (uint)m_SSSActiveDiffusionProfileCount; // Broadcast SSS parameters to all shaders. - cmd.SetGlobalInt(HDShaderIDs._EnableSubsurfaceScattering, hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering) ? 1 : 0); - unsafe + cb.data._EnableSubsurfaceScattering = hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering) ? 1u : 0u; + cb.data._TexturingModeFlags = m_SSSTexturingModeFlags; + cb.data._TransmissionFlags = m_SSSTransmissionFlags; + + for (int i = 0; i < m_SSSActiveDiffusionProfileCount; ++i) { - // Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system. - // Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader. - uint texturingModeFlags = this.m_SSSTexturingModeFlags; - uint transmissionFlags = this.m_SSSTransmissionFlags; - cmd.SetGlobalFloat(HDShaderIDs._TexturingModeFlags, *(float*)&texturingModeFlags); - cmd.SetGlobalFloat(HDShaderIDs._TransmissionFlags, *(float*)&transmissionFlags); + for (int c = 0; c < 4; ++c) // Vector4 component + { + cb.data._ThicknessRemaps[i * 4 + c] = m_SSSThicknessRemaps[i][c]; + cb.data._ShapeParams[i * 4 + c] = m_SSSShapeParams[i][c]; + // To disable transmission, we simply nullify the transmissionTint + cb.data._TransmissionTintsAndFresnel0[i * 4 + c] = hdCamera.frameSettings.IsEnabled(FrameSettingsField.Transmission) ? m_SSSTransmissionTintsAndFresnel0[i][c] : m_SSSDisabledTransmissionTintsAndFresnel0[i][c]; + cb.data._WorldScales[i * 4 + c] = m_SSSWorldScales[i][c]; + } + + cb.data._DiffusionProfileHashTable[i] = m_SSSDiffusionProfileHashes[i]; } - cmd.SetGlobalVectorArray(HDShaderIDs._ThicknessRemaps, m_SSSThicknessRemaps); - cmd.SetGlobalVectorArray(HDShaderIDs._ShapeParams, m_SSSShapeParams); - // To disable transmission, we simply nullify the transmissionTint - cmd.SetGlobalVectorArray(HDShaderIDs._TransmissionTintsAndFresnel0, hdCamera.frameSettings.IsEnabled(FrameSettingsField.Transmission) ? m_SSSTransmissionTintsAndFresnel0 : m_SSSDisabledTransmissionTintsAndFresnel0); - cmd.SetGlobalVectorArray(HDShaderIDs._WorldScales, m_SSSWorldScales); - cmd.SetGlobalFloatArray(HDShaderIDs._DiffusionProfileHashTable, m_SSSDiffusionProfileHashes); } static bool NeedTemporarySubsurfaceBuffer() diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs index 13d7ac933ca..8d21ef9df6e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs @@ -561,52 +561,57 @@ internal static void CleanUnused() s_Cleanup.Clear(); } - // Set up UnityPerView CBuffer. - internal void SetupGlobalParams(CommandBuffer cmd, int frameCount) + unsafe internal void UpdateShaderVariableGlobalCB(ConstantBuffer cb, int frameCount) { bool taaEnabled = frameSettings.IsEnabled(FrameSettingsField.Postprocess) && antialiasing == AntialiasingMode.TemporalAntialiasing && camera.cameraType == CameraType.Game; - cmd.SetGlobalMatrix(HDShaderIDs._ViewMatrix, mainViewConstants.viewMatrix); - cmd.SetGlobalMatrix(HDShaderIDs._InvViewMatrix, mainViewConstants.invViewMatrix); - cmd.SetGlobalMatrix(HDShaderIDs._ProjMatrix, mainViewConstants.projMatrix); - cmd.SetGlobalMatrix(HDShaderIDs._InvProjMatrix, mainViewConstants.invProjMatrix); - cmd.SetGlobalMatrix(HDShaderIDs._ViewProjMatrix, mainViewConstants.viewProjMatrix); - cmd.SetGlobalMatrix(HDShaderIDs._InvViewProjMatrix, mainViewConstants.invViewProjMatrix); - cmd.SetGlobalMatrix(HDShaderIDs._NonJitteredViewProjMatrix, mainViewConstants.nonJitteredViewProjMatrix); - cmd.SetGlobalMatrix(HDShaderIDs._PrevViewProjMatrix, mainViewConstants.prevViewProjMatrix); - cmd.SetGlobalMatrix(HDShaderIDs._PrevInvViewProjMatrix, mainViewConstants.prevInvViewProjMatrix); - cmd.SetGlobalMatrix(HDShaderIDs._CameraViewProjMatrix, mainViewConstants.viewProjMatrix); - cmd.SetGlobalVector(HDShaderIDs._WorldSpaceCameraPos, mainViewConstants.worldSpaceCameraPos); - cmd.SetGlobalVector(HDShaderIDs._PrevCamPosRWS, mainViewConstants.prevWorldSpaceCameraPos); - cmd.SetGlobalVector(HDShaderIDs._ScreenSize, screenSize); - cmd.SetGlobalVector(HDShaderIDs._RTHandleScale, RTHandles.rtHandleProperties.rtHandleScale); - cmd.SetGlobalVector(HDShaderIDs._RTHandleScaleHistory, m_HistoryRTSystem.rtHandleProperties.rtHandleScale); - cmd.SetGlobalVector(HDShaderIDs._ZBufferParams, zBufferParams); - cmd.SetGlobalVector(HDShaderIDs._ProjectionParams, projectionParams); - cmd.SetGlobalVector(HDShaderIDs.unity_OrthoParams, unity_OrthoParams); - cmd.SetGlobalVector(HDShaderIDs._ScreenParams, screenParams); - cmd.SetGlobalVector(HDShaderIDs._TaaFrameInfo, new Vector4(taaSharpenStrength, 0, taaFrameIndex, taaEnabled ? 1 : 0)); - cmd.SetGlobalVector(HDShaderIDs._TaaJitterStrength, taaJitter); - cmd.SetGlobalInt(HDShaderIDs._FrameCount, frameCount); - cmd.SetGlobalVectorArray(HDShaderIDs._FrustumPlanes, frustumPlaneEquations); + cb.data._ViewMatrix = mainViewConstants.viewMatrix; + cb.data._InvViewMatrix = mainViewConstants.invViewMatrix; + cb.data._ProjMatrix = mainViewConstants.projMatrix; + cb.data._InvProjMatrix = mainViewConstants.invProjMatrix; + cb.data._ViewProjMatrix = mainViewConstants.viewProjMatrix; + cb.data._CameraViewProjMatrix = mainViewConstants.viewProjMatrix; + cb.data._InvViewProjMatrix = mainViewConstants.invViewProjMatrix; + cb.data._NonJitteredViewProjMatrix = mainViewConstants.nonJitteredViewProjMatrix; + cb.data._PrevViewProjMatrix = mainViewConstants.prevViewProjMatrix; + cb.data._PrevInvViewProjMatrix = mainViewConstants.prevInvViewProjMatrix; + cb.data._WorldSpaceCameraPos = mainViewConstants.worldSpaceCameraPos; + cb.data._PrevCamPosRWS = mainViewConstants.prevWorldSpaceCameraPos; + cb.data._ScreenSize = screenSize; + cb.data._RTHandleScale = RTHandles.rtHandleProperties.rtHandleScale; + cb.data._RTHandleScaleHistory = m_HistoryRTSystem.rtHandleProperties.rtHandleScale; + cb.data._ZBufferParams = zBufferParams; + cb.data._ProjectionParams = projectionParams; + cb.data.unity_OrthoParams = unity_OrthoParams; + cb.data._ScreenParams = screenParams; + for (int i = 0; i < 6; ++i) + for (int j = 0; j < 4; ++j) + cb.data._FrustumPlanes[i * 4 + j] = frustumPlaneEquations[i][j]; + cb.data._TaaFrameInfo = new Vector4(taaSharpenStrength, 0, taaFrameIndex, taaEnabled ? 1 : 0); + cb.data._TaaJitterStrength = taaJitter; float ct = time; float pt = lastTime; float dt = Time.deltaTime; float sdt = Time.smoothDeltaTime; - cmd.SetGlobalVector(HDShaderIDs._Time, new Vector4(ct * 0.05f, ct, ct * 2.0f, ct * 3.0f)); - cmd.SetGlobalVector(HDShaderIDs._SinTime, new Vector4(Mathf.Sin(ct * 0.125f), Mathf.Sin(ct * 0.25f), Mathf.Sin(ct * 0.5f), Mathf.Sin(ct))); - cmd.SetGlobalVector(HDShaderIDs._CosTime, new Vector4(Mathf.Cos(ct * 0.125f), Mathf.Cos(ct * 0.25f), Mathf.Cos(ct * 0.5f), Mathf.Cos(ct))); - cmd.SetGlobalVector(HDShaderIDs.unity_DeltaTime, new Vector4(dt, 1.0f / dt, sdt, 1.0f / sdt)); - cmd.SetGlobalVector(HDShaderIDs._TimeParameters, new Vector4(ct, Mathf.Sin(ct), Mathf.Cos(ct), 0.0f)); - cmd.SetGlobalVector(HDShaderIDs._LastTimeParameters, new Vector4(pt, Mathf.Sin(pt), Mathf.Cos(pt), 0.0f)); + cb.data._Time = new Vector4(ct * 0.05f, ct, ct * 2.0f, ct * 3.0f); + cb.data._SinTime = new Vector4(Mathf.Sin(ct * 0.125f), Mathf.Sin(ct * 0.25f), Mathf.Sin(ct * 0.5f), Mathf.Sin(ct)); + cb.data._CosTime = new Vector4(Mathf.Cos(ct * 0.125f), Mathf.Cos(ct * 0.25f), Mathf.Cos(ct * 0.5f), Mathf.Cos(ct)); + cb.data.unity_DeltaTime = new Vector4(dt, 1.0f / dt, sdt, 1.0f / sdt); + cb.data._TimeParameters = new Vector4(ct, Mathf.Sin(ct), Mathf.Cos(ct), 0.0f); + cb.data._LastTimeParameters = new Vector4(pt, Mathf.Sin(pt), Mathf.Cos(pt), 0.0f); + cb.data._FrameCount = frameCount; float exposureMultiplierForProbes = 1.0f / Mathf.Max(probeRangeCompressionFactor, 1e-6f); - cmd.SetGlobalFloat(HDShaderIDs._ProbeExposureScale, exposureMultiplierForProbes); + cb.data._ProbeExposureScale = exposureMultiplierForProbes; + } + // Set up UnityPerView CBuffer. + internal void SetupGlobalParams(CommandBuffer cmd, int frameCount) + { // TODO: qualify this code with xr.singlePassEnabled when compute shaders can use keywords if (true) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 6245b3765cd..73a3f67e548 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -142,7 +142,6 @@ internal static Volume GetOrCreateDefaultVolume() Material m_BlitTexArraySingleSlice; MaterialPropertyBlock m_BlitPropertyBlock = new MaterialPropertyBlock(); - RenderTargetIdentifier[] m_MRTCache2 = new RenderTargetIdentifier[2]; // 'm_CameraColorBuffer' does not contain diffuse lighting of SSS materials until the SSS pass. It is stored within 'm_CameraSssDiffuseLightingBuffer'. @@ -168,6 +167,9 @@ internal static Volume GetOrCreateDefaultVolume() Lazy m_CustomPassColorBuffer; Lazy m_CustomPassDepthBuffer; + // Constant Buffers + ConstantBuffer m_ShaderVariablesGlobalCB; + // The current MSAA count MSAASamples m_MSAASamples; @@ -482,6 +484,8 @@ public HDRenderPipeline(HDRenderPipelineAsset asset, HDRenderPipelineAsset defau InitializePrepass(m_Asset); m_ColorResolveMaterial = CoreUtils.CreateEngineMaterial(asset.renderPipelineResources.shaders.colorResolvePS); + + InitializeConstantBuffers(); } #if UNITY_EDITOR @@ -796,6 +800,16 @@ void InitializeRenderStateBlocks() }; } + void InitializeConstantBuffers() + { + m_ShaderVariablesGlobalCB = new ConstantBuffer(); + } + + void DestroyConstantBuffers() + { + m_ShaderVariablesGlobalCB.Release(); + } + /// /// Disposable pattern implementation. /// @@ -886,6 +900,7 @@ protected override void Dispose(bool disposing) CleanupPrepass(); CoreUtils.Destroy(m_ColorResolveMaterial); + DestroyConstantBuffers(); #if UNITY_EDITOR SceneViewDrawMode.ResetDrawMode(); @@ -950,35 +965,55 @@ void Resize(HDCamera hdCamera) } } + void UpdateShaderVariablesGlobalCB(HDCamera hdCamera) + { + /* + _ShadowFrustumPlanes + */ + + hdCamera.UpdateShaderVariableGlobalCB(m_ShaderVariablesGlobalCB, m_FrameCount); + Fog.UpdateShaderVariablesGlobalCB(m_ShaderVariablesGlobalCB, hdCamera); + UpdateShaderVariablesGlobalSubsurface(m_ShaderVariablesGlobalCB, hdCamera); + UpdateShaderVariablesGlobalDecal(m_ShaderVariablesGlobalCB, hdCamera); + + // Misc + MicroShadowing microShadowingSettings = hdCamera.volumeStack.GetComponent(); + m_ShaderVariablesGlobalCB.data._MicroShadowOpacity = microShadowingSettings.enable.value ? microShadowingSettings.opacity.value : 0.0f; + + HDShadowSettings shadowSettings = hdCamera.volumeStack.GetComponent(); + m_ShaderVariablesGlobalCB.data._DirectionalTransmissionMultiplier = shadowSettings.directionalTransmissionMultiplier.value; + + ScreenSpaceRefraction ssRefraction = hdCamera.volumeStack.GetComponent(); + m_ShaderVariablesGlobalCB.data._SSRefractionInvScreenWeightDistance = 1.0f / ssRefraction.screenFadeDistance.value; + + m_ShaderVariablesGlobalCB.data._IndirectLightingMultiplier = new Vector4(hdCamera.volumeStack.GetComponent().indirectDiffuseIntensity.value, 0, 0, 0); + m_ShaderVariablesGlobalCB.data._OffScreenRendering = 0; + m_ShaderVariablesGlobalCB.data._ReplaceDiffuseForIndirect = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ReplaceDiffuseForIndirect) ? 1.0f : 0.0f; + m_ShaderVariablesGlobalCB.data._EnableSkyReflection = hdCamera.frameSettings.IsEnabled(FrameSettingsField.SkyReflection) ? 1u : 0u; + m_ShaderVariablesGlobalCB.data._ContactShadowOpacity = m_ContactShadows.opacity.value; + + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) + { + m_ShaderVariablesGlobalCB.data._RaytracedIndirectDiffuse = ValidIndirectDiffuseState(hdCamera) ? 1 : 0; + m_ShaderVariablesGlobalCB.data._RaytracingFrameIndex = RayTracingFrameIndex(hdCamera); + } + } + void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PushGlobalParameters))) { - // Set up UnityPerFrame CBuffer. - PushSubsurfaceScatteringGlobalParams(hdCamera, cmd); + UpdateShaderVariablesGlobalCB(hdCamera); - PushDecalsGlobalParams(hdCamera, cmd); - Fog.PushFogShaderParameters(hdCamera, cmd); - - PushVolumetricLightingGlobalParams(hdCamera, cmd, m_FrameCount); - SetMicroShadowingSettings(hdCamera, cmd); - HDShadowSettings shadowSettings = hdCamera.volumeStack.GetComponent(); - cmd.SetGlobalFloat(HDShaderIDs._DirectionalTransmissionMultiplier, shadowSettings.directionalTransmissionMultiplier.value); - m_AmbientOcclusionSystem.PushGlobalParameters(hdCamera, cmd); - - var ssRefraction = hdCamera.volumeStack.GetComponent() - ?? ScreenSpaceRefraction.defaultInstance; - ssRefraction.PushShaderParameters(cmd); + PushVolumetricLightingGlobalParams(hdCamera, cmd, m_FrameCount); // Set up UnityPerView CBuffer. hdCamera.SetupGlobalParams(cmd, m_FrameCount); - cmd.SetGlobalVector(HDShaderIDs._IndirectLightingMultiplier, new Vector4(hdCamera.volumeStack.GetComponent().indirectDiffuseIntensity.value, 0, 0, 0)); - // It will be overridden for transparent pass. cmd.SetGlobalInt(HDShaderIDs._ColorMaskTransparentVel, (int)UnityEngine.Rendering.ColorWriteMask.All); @@ -1005,22 +1040,9 @@ void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd) else cmd.SetGlobalTexture(HDShaderIDs._SsrLightingTexture, TextureXR.GetClearTexture()); - // Off screen rendering is disabled for most of the frame by default. - cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 0); - cmd.SetGlobalFloat(HDShaderIDs._ReplaceDiffuseForIndirect, hdCamera.frameSettings.IsEnabled(FrameSettingsField.ReplaceDiffuseForIndirect) ? 1.0f : 0.0f); - cmd.SetGlobalInt(HDShaderIDs._EnableSkyReflection, hdCamera.frameSettings.IsEnabled(FrameSettingsField.SkyReflection) ? 1 : 0); m_SkyManager.SetGlobalSkyData(cmd, hdCamera); - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) - { - bool validIndirectDiffuse = ValidIndirectDiffuseState(hdCamera); - cmd.SetGlobalInt(HDShaderIDs._RaytracedIndirectDiffuse, validIndirectDiffuse ? 1 : 0); - - // Bind the camera's ray tracing frame index - cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, RayTracingFrameIndex(hdCamera)); - } - cmd.SetGlobalFloat(HDShaderIDs._ContactShadowOpacity, m_ContactShadows.opacity.value); } } @@ -1103,12 +1125,6 @@ static void BuildCoarseStencilAndResolveIfNeeded(BuildCoarseStencilAndResolvePar } } - void SetMicroShadowingSettings(HDCamera hdCamera, CommandBuffer cmd) - { - MicroShadowing microShadowingSettings = hdCamera.volumeStack.GetComponent(); - cmd.SetGlobalFloat(HDShaderIDs._MicroShadowOpacity, microShadowingSettings.enable.value ? microShadowingSettings.opacity.value : 0.0f); - } - void ConfigureKeywords(bool enableBakeShadowMask, HDCamera hdCamera, CommandBuffer cmd) { // Globally enable (for GBuffer shader and forward lit (opaque and transparent) the keyword SHADOWS_SHADOWMASK @@ -3156,16 +3172,16 @@ RendererListDesc PrepareMeshDecalsRendererList(CullingResults cullingResults, HD return desc; } - static void PushDecalsGlobalParams(HDCamera hdCamera, CommandBuffer cmd) + void UpdateShaderVariablesGlobalDecal(ConstantBuffer cb, HDCamera hdCamera) { if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.Decals)) { - cmd.SetGlobalInt(HDShaderIDs._EnableDecals, 1); - cmd.SetGlobalVector(HDShaderIDs._DecalAtlasResolution, new Vector2(HDUtils.hdrpSettings.decalSettings.atlasWidth, HDUtils.hdrpSettings.decalSettings.atlasHeight)); + cb.data._EnableDecals = 1; + cb.data._DecalAtlasResolution = new Vector2(HDUtils.hdrpSettings.decalSettings.atlasWidth, HDUtils.hdrpSettings.decalSettings.atlasHeight); } else { - cmd.SetGlobalInt(HDShaderIDs._EnableDecals, 0); + cb.data._EnableDecals = 0; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl index 37be22343c3..e1de95826cc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl @@ -155,7 +155,6 @@ TEXTURE2D(_PrevExposureTexture); // move these to a dedicated CBuffer to avoid polluting the global one. // $$$ Volumetric only? float4 _AmbientProbeCoeffs[7]; // 3 bands of SH, packed, rescaled and convolved with the phase function -float _GlobalFogAnisotropy; float4 _VBufferPrevViewportSize; float4 _VBufferHistoryPrevUvScaleAndLimit; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index d17da4bb620..ec0cce7bab1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -95,11 +95,18 @@ unsafe struct ShaderVariablesGlobal public Vector4 _LastTimeParameters; // { t, sin(t), cos(t) } // Volumetric lighting. + public Vector4 _FogColor; // color in rgb + public Vector4 _MipFogParameters; public Vector3 _HeightFogBaseScattering; public float _HeightFogBaseExtinction; - - public Vector2 _HeightFogExponents; // { 1/H, H } + public int _FogEnabled; + public int _PBRFogEnabled; + public float _MaxFogDistance; + public float _FogColorMode; + public float _SkyTextureMipCount; + public Vector2 _HeightFogExponents; // { 1/H, H } public float _HeightFogBaseHeight; + public float _GlobalFogAnisotropy; public Vector4 _VBufferViewportSize; // { w, h, 1/w, 1/h } @@ -116,8 +123,6 @@ unsafe struct ShaderVariablesGlobal public float _VBufferLastSliceDist; // The distance to the middle of the last slice public int _EnableVolumetricFog; // bool... - - // Light Loop public const int s_MaxEnv2DLight = 32; @@ -188,16 +193,6 @@ unsafe struct ShaderVariablesGlobal // Screen space refraction public float _SSRefractionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback - // Atmospheric scattering - // Common - public int _FogEnabled; - public int _PBRFogEnabled; - public float _MaxFogDistance; - public float _FogColorMode; - public float _SkyTextureMipCount; - public Vector4 _FogColor; // color in rgb - public Vector4 _MipFogParameters; - // Subsurface scattering // Use float4 to avoid any packing issue between compute and pixel shaders [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(Vector4))] @@ -208,14 +203,12 @@ unsafe struct ShaderVariablesGlobal public fixed float _TransmissionTintsAndFresnel0[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // RGB = 1/4 * color, A = fresnel0 [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(Vector4))] public fixed float _WorldScales[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // X = meters per world unit; Y = world units per meter - [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(float))] + [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(uint))] public fixed uint _DiffusionProfileHashTable[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT]; // TODO: constant - // Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system. - // Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader. public uint _EnableSubsurfaceScattering; // Globally toggles subsurface and transmission scattering on/off - public float _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter - public float _TransmissionFlags; // 1 bit/profile; 0 = regular, 1 = thin + public uint _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter + public uint _TransmissionFlags; // 1 bit/profile; 0 = regular, 1 = thin public uint _DiffusionProfileCount; // Decals From 8006917e8f8fb2c383fccd722325704b776736d2 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 6 Mar 2020 11:35:07 +0100 Subject: [PATCH 28/92] Implemented Volumetrics global CB and various fixes. --- .../VolumetricLighting/VolumetricLighting.cs | 44 +++++++++---------- .../SubsurfaceScattering.hlsl | 2 +- .../SubsurfaceScatteringManager.cs | 6 +-- .../Runtime/RenderPipeline/Camera/HDCamera.cs | 4 +- .../RenderPipeline/HDRenderPipeline.cs | 11 +---- .../RenderPipeline/HDStringConstants.cs | 3 -- .../ShaderLibrary/ShaderVariablesGlobal.cs | 7 +-- .../ShaderVariablesGlobal.cs.hlsl | 22 +++++----- .../Runtime/Sky/SkyManager.cs | 1 - 9 files changed, 42 insertions(+), 58 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 33092267cd9..532fd4dacfc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -440,6 +440,27 @@ static float CornetteShanksPhasePartConstant(float anisotropy) return (3.0f / (8.0f * Mathf.PI)) * (1.0f - g * g) / (2.0f + g * g); } + void UpdateShaderVariablesGlobalVolumetrics(ConstantBuffer cb, in RTHandleProperties sharedRTHandleProperties, HDCamera hdCamera) + { + var currFrameParams = hdCamera.vBufferParams[0]; + + Vector2Int sharedBufferSize = sharedRTHandleProperties.currentRenderTargetSize; + + var cvp = currFrameParams.viewportSize; + + // Adjust slices for XR rendering: VBuffer is shared for all single-pass views + int sliceCount = cvp.z / hdCamera.viewCount; + + cb.data._VBufferViewportSize = new Vector4(cvp.x, cvp.y, 1.0f / cvp.x, 1.0f / cvp.y); + cb.data._VBufferSliceCount = (uint)sliceCount; + cb.data._VBufferRcpSliceCount = 1.0f / sliceCount; + cb.data._VBufferSharedUvScaleAndLimit = currFrameParams.ComputeUvScaleAndLimit(sharedBufferSize); + cb.data._VBufferDistanceEncodingParams = currFrameParams.depthEncodingParams; + cb.data._VBufferDistanceDecodingParams = currFrameParams.depthDecodingParams; + cb.data._VBufferLastSliceDist = currFrameParams.ComputeLastSliceDistance(sliceCount); + cb.data._VBufferRcpInstancedViewCount = 1.0f / hdCamera.viewCount; + } + void PushVolumetricLightingGlobalParams(HDCamera hdCamera, CommandBuffer cmd, int frameIndex) { if (!Fog.IsVolumetricFogEnabled(hdCamera)) @@ -450,10 +471,8 @@ void PushVolumetricLightingGlobalParams(HDCamera hdCamera, CommandBuffer cmd, in // Get the interpolated anisotropy value. var fog = hdCamera.volumeStack.GetComponent(); - SetPreconvolvedAmbientLightProbe(hdCamera, cmd, fog.globalLightProbeDimmer.value, fog.anisotropy.value); - var currFrameParams = hdCamera.vBufferParams[0]; var prevFrameParams = hdCamera.vBufferParams[1]; // The lighting & density buffers are shared by all cameras. @@ -464,34 +483,15 @@ void PushVolumetricLightingGlobalParams(HDCamera hdCamera, CommandBuffer cmd, in // The viewport size is the same for all of these buffers. // All of these buffers may have sub-native-resolution viewports. // The 3rd dimension (number of slices) is the same for all of these buffers. - Vector2Int sharedBufferSize = new Vector2Int(m_LightingBufferHandle.rt.width, m_LightingBufferHandle.rt.height); - - Debug.Assert(m_LightingBufferHandle.rt.width == m_DensityBufferHandle.rt.width); - Debug.Assert(m_LightingBufferHandle.rt.height == m_DensityBufferHandle.rt.height); - Vector2Int historyBufferSize = Vector2Int.zero; if (hdCamera.IsVolumetricReprojectionEnabled()) { - var historyRT = hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.VolumetricLighting); - historyBufferSize = new Vector2Int(historyRT.rt.width, historyRT.rt.height); + historyBufferSize = ComputeVBufferResolutionXY(hdCamera.historyRTHandleProperties.currentRenderTargetSize); } - var cvp = currFrameParams.viewportSize; var pvp = prevFrameParams.viewportSize; - // Adjust slices for XR rendering: VBuffer is shared for all single-pass views - int sliceCount = cvp.z / hdCamera.viewCount; - - cmd.SetGlobalVector(HDShaderIDs._VBufferViewportSize, new Vector4(cvp.x, cvp.y, 1.0f / cvp.x, 1.0f / cvp.y)); - cmd.SetGlobalInt( HDShaderIDs._VBufferSliceCount, sliceCount); - cmd.SetGlobalFloat( HDShaderIDs._VBufferRcpSliceCount, 1.0f / sliceCount); - cmd.SetGlobalVector(HDShaderIDs._VBufferSharedUvScaleAndLimit, currFrameParams.ComputeUvScaleAndLimit(sharedBufferSize)); - cmd.SetGlobalVector(HDShaderIDs._VBufferDistanceEncodingParams, currFrameParams.depthEncodingParams); - cmd.SetGlobalVector(HDShaderIDs._VBufferDistanceDecodingParams, currFrameParams.depthDecodingParams); - cmd.SetGlobalFloat( HDShaderIDs._VBufferLastSliceDist, currFrameParams.ComputeLastSliceDistance(sliceCount)); - cmd.SetGlobalFloat( HDShaderIDs._VBufferRcpInstancedViewCount, 1.0f / hdCamera.viewCount); - cmd.SetGlobalVector(HDShaderIDs._VBufferPrevViewportSize, new Vector4(pvp.x, pvp.y, 1.0f / pvp.x, 1.0f / pvp.y)); cmd.SetGlobalVector(HDShaderIDs._VBufferHistoryPrevUvScaleAndLimit, prevFrameParams.ComputeUvScaleAndLimit(historyBufferSize)); cmd.SetGlobalVector(HDShaderIDs._VBufferPrevDepthEncodingParams, prevFrameParams.depthEncodingParams); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl index 84ddd85cd79..cff46fed307 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl @@ -231,7 +231,7 @@ uint FindDiffusionProfileIndex(uint diffusionProfileHash) // Fetch the 4 bit index number by looking for the diffusion profile unique ID: for (i = 0; i < _DiffusionProfileCount; i++) { - if (DiffusionProfileHashTable[i] == diffusionProfileHash) + if (_DiffusionProfileHashTable[i] == diffusionProfileHash) { diffusionProfileIndex = i; break; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index 44ea6b714dd..4b866be554d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -243,7 +243,7 @@ struct SubsurfaceScatteringParameters public Vector4[] worldScales; public Vector4[] filterKernels; public Vector4[] shapeParams; - public float[] diffusionProfileHashes; + //public float[] diffusionProfileHashes; public ComputeBuffer coarseStencilBuffer; } @@ -277,7 +277,7 @@ SubsurfaceScatteringParameters PrepareSubsurfaceScatteringParameters(HDCamera hd parameters.worldScales = m_SSSWorldScales; parameters.filterKernels = m_SSSFilterKernels; parameters.shapeParams = m_SSSShapeParams; - parameters.diffusionProfileHashes = m_SSSDiffusionProfileHashes; + //parameters.diffusionProfileHashes = m_SSSDiffusionProfileHashes; parameters.coarseStencilBuffer = m_SharedRTManager.GetCoarseStencilBuffer(); @@ -463,7 +463,7 @@ static void RenderSubsurfaceScattering(in SubsurfaceScatteringParameters paramet cmd.SetComputeVectorArrayParam(parameters.subsurfaceScatteringCS, HDShaderIDs._WorldScales, parameters.worldScales); cmd.SetComputeVectorArrayParam(parameters.subsurfaceScatteringCS, HDShaderIDs._FilterKernels, parameters.filterKernels); cmd.SetComputeVectorArrayParam(parameters.subsurfaceScatteringCS, HDShaderIDs._ShapeParams, parameters.shapeParams); - cmd.SetComputeFloatParams(parameters.subsurfaceScatteringCS, HDShaderIDs._DiffusionProfileHashTable, parameters.diffusionProfileHashes); + //cmd.SetComputeFloatParams(parameters.subsurfaceScatteringCS, HDShaderIDs._DiffusionProfileHashTable, parameters.diffusionProfileHashes); cmd.SetComputeTextureParam(parameters.subsurfaceScatteringCS, parameters.subsurfaceScatteringCSKernel, HDShaderIDs._DepthTexture, resources.depthTexture); cmd.SetComputeTextureParam(parameters.subsurfaceScatteringCS, parameters.subsurfaceScatteringCSKernel, HDShaderIDs._IrradianceSource, resources.diffuseBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs index 8d21ef9df6e..5774b97199b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs @@ -577,8 +577,8 @@ unsafe internal void UpdateShaderVariableGlobalCB(ConstantBuffer(); @@ -1019,15 +1020,7 @@ void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd) if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.MotionVectors)) { - var buf = m_SharedRTManager.GetMotionVectorsBuffer(); - - cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, buf); - cmd.SetGlobalVector( HDShaderIDs._CameraMotionVectorsSize, new Vector4(buf.referenceSize.x, - buf.referenceSize.y, - 1.0f / buf.referenceSize.x, - 1.0f / buf.referenceSize.y)); - cmd.SetGlobalVector(HDShaderIDs._CameraMotionVectorsScale, new Vector4(buf.referenceSize.x / (float)buf.rt.width, - buf.referenceSize.y / (float)buf.rt.height)); + cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, m_SharedRTManager.GetMotionVectorsBuffer()); } else { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 4ebbdae112c..60942977885 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -219,7 +219,6 @@ static class HDShaderIDs public static readonly int _EnvLightSkyEnabled = Shader.PropertyToID("_EnvLightSkyEnabled"); public static readonly int _AmbientOcclusionParam = Shader.PropertyToID("_AmbientOcclusionParam"); public static readonly int _SkyTexture = Shader.PropertyToID("_SkyTexture"); - public static readonly int _SkyTextureMipCount = Shader.PropertyToID("_SkyTextureMipCount"); public static readonly int _EnableSubsurfaceScattering = Shader.PropertyToID("_EnableSubsurfaceScattering"); public static readonly int _TransmittanceMultiplier = Shader.PropertyToID("_TransmittanceMultiplier"); @@ -441,8 +440,6 @@ static class HDShaderIDs public static readonly int _CameraDepthTexture = Shader.PropertyToID("_CameraDepthTexture"); public static readonly int _CameraMotionVectorsTexture = Shader.PropertyToID("_CameraMotionVectorsTexture"); - public static readonly int _CameraMotionVectorsSize = Shader.PropertyToID("_CameraMotionVectorsSize"); - public static readonly int _CameraMotionVectorsScale = Shader.PropertyToID("_CameraMotionVectorsScale"); public static readonly int _FullScreenDebugMode = Shader.PropertyToID("_FullScreenDebugMode"); public static readonly int _TransparencyOverdrawMaxPixelCost = Shader.PropertyToID("_TransparencyOverdrawMaxPixelCost"); public static readonly int _CustomDepthTexture = Shader.PropertyToID("_CustomDepthTexture"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index ec0cce7bab1..e6d5f421a2b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -32,9 +32,9 @@ unsafe struct ShaderVariablesGlobal public Matrix4x4 _PrevInvViewProjMatrix; // non-jittered #if !USING_STEREO_MATRICES - public Vector3 _WorldSpaceCameraPos; + public Vector3 _WorldSpaceCameraPos_Internal; public float _Pad0; - public Vector3 _PrevCamPosRWS; // $$$ + public Vector3 _PrevCamPosRWS_Internal; // $$$ public float _Pad1; #endif public Vector4 _ScreenSize; // { w, h, 1 / w, 1 / h } @@ -103,7 +103,6 @@ unsafe struct ShaderVariablesGlobal public int _PBRFogEnabled; public float _MaxFogDistance; public float _FogColorMode; - public float _SkyTextureMipCount; public Vector2 _HeightFogExponents; // { 1/H, H } public float _HeightFogBaseHeight; public float _GlobalFogAnisotropy; @@ -180,10 +179,8 @@ unsafe struct ShaderVariablesGlobal public int _RaytracedIndirectDiffuse; // Buffer pyramid - public Vector4 _CameraMotionVectorsSize; // (x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size public Vector4 _ColorPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused public Vector4 _DepthPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused - public Vector4 _CameraMotionVectorsScale; // (x,y) = Screen Scale, z = lod count, w = unused // Ambient occlusion public Vector4 _AmbientOcclusionParam; // xyz occlusion color, w directLightStrenght diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 3b90cfd1487..5f927d3598b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -45,10 +45,17 @@ cbuffer ShaderVariablesGlobal float4 unity_DeltaTime; float4 _TimeParameters; float4 _LastTimeParameters; + float4 _FogColor; + float4 _MipFogParameters; float3 _HeightFogBaseScattering; float _HeightFogBaseExtinction; + int _FogEnabled; + int _PBRFogEnabled; + float _MaxFogDistance; + float _FogColorMode; float2 _HeightFogExponents; float _HeightFogBaseHeight; + float _GlobalFogAnisotropy; float4 _VBufferViewportSize; uint _VBufferSliceCount; float _VBufferRcpSliceCount; @@ -93,28 +100,19 @@ cbuffer ShaderVariablesGlobal uint _NumTileClusteredY; int _EnvSliceSize; int _RaytracedIndirectDiffuse; - float4 _CameraMotionVectorsSize; float4 _ColorPyramidScale; float4 _DepthPyramidScale; - float4 _CameraMotionVectorsScale; float4 _AmbientOcclusionParam; float4 _IndirectLightingMultiplier; float _SSRefractionInvScreenWeightDistance; - int _FogEnabled; - int _PBRFogEnabled; - float _MaxFogDistance; - float _FogColorMode; - float _SkyTextureMipCount; - float4 _FogColor; - float4 _MipFogParameters; float4 _ThicknessRemaps[16]; float4 _ShapeParams[16]; float4 _TransmissionTintsAndFresnel0[16]; float4 _WorldScales[16]; - float _DiffusionProfileHashTable[16]; + uint _DiffusionProfileHashTable[16]; uint _EnableSubsurfaceScattering; - float _TexturingModeFlags; - float _TransmissionFlags; + uint _TexturingModeFlags; + uint _TransmissionFlags; uint _DiffusionProfileCount; float2 _DecalAtlasResolution; uint _EnableDecals; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs index 5aa39eeccc7..b4aaa8474ec 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs @@ -798,7 +798,6 @@ public void UpdateEnvironment(HDCamera hdCamera, ScriptableRenderContext renderC var reflectionTexture = GetReflectionTexture(hdCamera.lightingSky); cmd.SetGlobalTexture(HDShaderIDs._SkyTexture, reflectionTexture); float mipCount = Mathf.Clamp(Mathf.Log((float)reflectionTexture.width, 2.0f) + 1, 0.0f, 6.0f); - cmd.SetGlobalFloat(HDShaderIDs._SkyTextureMipCount, mipCount); if (IsLightingSkyValid(hdCamera)) { From 8939e9f4d498f6b26e572a4682330c4795dfe63f Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 6 Mar 2020 13:18:17 +0100 Subject: [PATCH 29/92] Implemented shadow global CB update. --- .../Runtime/Lighting/Shadow/HDShadowAtlas.cs | 7 +------ .../Runtime/Lighting/Shadow/HDShadowManager.cs | 14 +++++++++++--- .../Runtime/RenderPipeline/HDRenderPipeline.cs | 2 ++ .../Runtime/ShaderLibrary/ShaderVariablesGlobal.cs | 9 +++------ 4 files changed, 17 insertions(+), 15 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs index e919cd56215..2bbb3121574 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs @@ -30,7 +30,6 @@ public enum BlurAlgorithm DepthBits m_DepthBufferBits; RenderTextureFormat m_Format; string m_Name; - int m_AtlasSizeShaderID; int m_AtlasShaderID; int m_MomentAtlasShaderID; RenderPipelineResources m_RenderPipelineResources; @@ -53,7 +52,7 @@ public enum BlurAlgorithm bool m_HasResizedAtlas = false; int frameCounter = 0; - public HDShadowAtlas(RenderPipelineResources renderPipelineResources, int width, int height, int atlasShaderID, int atlasSizeShaderID, Material clearMaterial, int maxShadowRequests, BlurAlgorithm blurAlgorithm = BlurAlgorithm.None, FilterMode filterMode = FilterMode.Bilinear, DepthBits depthBufferBits = DepthBits.Depth16, RenderTextureFormat format = RenderTextureFormat.Shadowmap, string name = "", int momentAtlasShaderID = 0) + public HDShadowAtlas(RenderPipelineResources renderPipelineResources, int width, int height, int atlasShaderID, Material clearMaterial, int maxShadowRequests, BlurAlgorithm blurAlgorithm = BlurAlgorithm.None, FilterMode filterMode = FilterMode.Bilinear, DepthBits depthBufferBits = DepthBits.Depth16, RenderTextureFormat format = RenderTextureFormat.Shadowmap, string name = "", int momentAtlasShaderID = 0) { this.width = width; this.height = height; @@ -63,7 +62,6 @@ public HDShadowAtlas(RenderPipelineResources renderPipelineResources, int width, m_Name = name; m_AtlasShaderID = atlasShaderID; m_MomentAtlasShaderID = momentAtlasShaderID; - m_AtlasSizeShaderID = atlasSizeShaderID; m_ClearMaterial = clearMaterial; m_BlurAlgorithm = blurAlgorithm; m_RenderPipelineResources = renderPipelineResources; @@ -468,7 +466,6 @@ struct RenderShadowsParameters public Material clearMaterial; public bool debugClearAtlas; public int atlasShaderID; - public int atlasSizeShaderID; public BlurAlgorithm blurAlgorithm; // EVSM @@ -486,7 +483,6 @@ RenderShadowsParameters PrepareRenderShadowsParameters() parameters.clearMaterial = m_ClearMaterial; parameters.debugClearAtlas = m_LightingDebugSettings.clearShadowAtlas; parameters.atlasShaderID = m_AtlasShaderID; - parameters.atlasSizeShaderID = m_AtlasSizeShaderID; parameters.blurAlgorithm = m_BlurAlgorithm; // EVSM @@ -506,7 +502,6 @@ static void RenderShadows( RenderShadowsParameters parameters, CommandBuffer cmd) { cmd.SetRenderTarget(atlasRenderTexture, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store); - cmd.SetGlobalVector(parameters.atlasSizeShaderID, new Vector4(atlasRenderTexture.rt.width, atlasRenderTexture.rt.height, 1.0f / atlasRenderTexture.rt.width, 1.0f / atlasRenderTexture.rt.height)); // Clear the whole atlas to avoid garbage outside of current request when viewing it. if (parameters.debugClearAtlas) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs index 159ac9e7d04..0cb797000f2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs @@ -282,13 +282,13 @@ public void InitShadowManager(RenderPipelineResources renderPipelineResources, D } // The cascade atlas will be allocated only if there is a directional light - m_Atlas = new HDShadowAtlas(renderPipelineResources, punctualLightAtlasInfo.shadowAtlasResolution, punctualLightAtlasInfo.shadowAtlasResolution, HDShaderIDs._ShadowmapAtlas, HDShaderIDs._ShadowAtlasSize, clearMaterial, maxShadowRequests, depthBufferBits: punctualLightAtlasInfo.shadowAtlasDepthBits, name: "Shadow Map Atlas"); + m_Atlas = new HDShadowAtlas(renderPipelineResources, punctualLightAtlasInfo.shadowAtlasResolution, punctualLightAtlasInfo.shadowAtlasResolution, HDShaderIDs._ShadowmapAtlas, clearMaterial, maxShadowRequests, depthBufferBits: punctualLightAtlasInfo.shadowAtlasDepthBits, name: "Shadow Map Atlas"); // Cascade atlas render texture will only be allocated if there is a shadow casting directional light HDShadowAtlas.BlurAlgorithm cascadeBlur = GetDirectionalShadowAlgorithm() == DirectionalShadowAlgorithm.IMS ? HDShadowAtlas.BlurAlgorithm.IM : HDShadowAtlas.BlurAlgorithm.None; - m_CascadeAtlas = new HDShadowAtlas(renderPipelineResources, 1, 1, HDShaderIDs._ShadowmapCascadeAtlas, HDShaderIDs._CascadeShadowAtlasSize, clearMaterial, maxShadowRequests, cascadeBlur, depthBufferBits: directionalShadowDepthBits, name: "Cascade Shadow Map Atlas"); + m_CascadeAtlas = new HDShadowAtlas(renderPipelineResources, 1, 1, HDShaderIDs._ShadowmapCascadeAtlas, clearMaterial, maxShadowRequests, cascadeBlur, depthBufferBits: directionalShadowDepthBits, name: "Cascade Shadow Map Atlas"); if (ShaderConfig.s_AreaLights == 1) - m_AreaLightShadowAtlas = new HDShadowAtlas(renderPipelineResources, areaLightAtlasInfo.shadowAtlasResolution, areaLightAtlasInfo.shadowAtlasResolution, HDShaderIDs._AreaLightShadowmapAtlas, HDShaderIDs._AreaShadowAtlasSize, clearMaterial, maxShadowRequests, HDShadowAtlas.BlurAlgorithm.EVSM, depthBufferBits: areaLightAtlasInfo.shadowAtlasDepthBits, name: "Area Light Shadow Map Atlas", momentAtlasShaderID: HDShaderIDs._AreaShadowmapMomentAtlas); + m_AreaLightShadowAtlas = new HDShadowAtlas(renderPipelineResources, areaLightAtlasInfo.shadowAtlasResolution, areaLightAtlasInfo.shadowAtlasResolution, HDShaderIDs._AreaLightShadowmapAtlas, clearMaterial, maxShadowRequests, HDShadowAtlas.BlurAlgorithm.EVSM, depthBufferBits: areaLightAtlasInfo.shadowAtlasDepthBits, name: "Area Light Shadow Map Atlas", momentAtlasShaderID: HDShaderIDs._AreaShadowmapMomentAtlas); m_ShadowDataBuffer = new ComputeBuffer(maxShadowRequests, System.Runtime.InteropServices.Marshal.SizeOf(typeof(HDShadowData))); m_DirectionalShadowDataBuffer = new ComputeBuffer(1, System.Runtime.InteropServices.Marshal.SizeOf(typeof(HDDirectionalShadowData))); @@ -316,6 +316,14 @@ public static DirectionalShadowAlgorithm GetDirectionalShadowAlgorithm() return DirectionalShadowAlgorithm.PCF5x5; } + public void UpdateShaderVariablesGlobalCB(ConstantBuffer cb) + { + cb.data._ShadowAtlasSize = new Vector4(m_Atlas.width, m_Atlas.height, 1.0f / m_Atlas.width, 1.0f / m_Atlas.height); + cb.data._CascadeShadowAtlasSize = new Vector4(m_CascadeAtlas.width, m_CascadeAtlas.height, 1.0f / m_CascadeAtlas.width, 1.0f / m_CascadeAtlas.height); + if (ShaderConfig.s_AreaLights == 1) + cb.data._AreaShadowAtlasSize = new Vector4(m_AreaLightShadowAtlas.width, m_AreaLightShadowAtlas.height, 1.0f / m_AreaLightShadowAtlas.width, 1.0f / m_AreaLightShadowAtlas.height); + } + public void UpdateDirectionalShadowResolution(int resolution, int cascadeCount) { Vector2Int atlasResolution = new Vector2Int(resolution, resolution); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 50cf74aa8e1..0be3edeb689 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -976,6 +976,8 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera) UpdateShaderVariablesGlobalSubsurface(m_ShaderVariablesGlobalCB, hdCamera); UpdateShaderVariablesGlobalDecal(m_ShaderVariablesGlobalCB, hdCamera); UpdateShaderVariablesGlobalVolumetrics(m_ShaderVariablesGlobalCB, RTHandles.rtHandleProperties, hdCamera); + m_ShadowManager.UpdateShaderVariablesGlobalCB(m_ShaderVariablesGlobalCB); + // Misc MicroShadowing microShadowingSettings = hdCamera.volumeStack.GetComponent(); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index e6d5f421a2b..c3d0ef28ee4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -125,12 +125,9 @@ unsafe struct ShaderVariablesGlobal // Light Loop public const int s_MaxEnv2DLight = 32; - [HLSLArray(0, typeof(Vector4))] - public fixed float _ShadowAtlasSize[4]; - [HLSLArray(0, typeof(Vector4))] - public fixed float _CascadeShadowAtlasSize[4]; - [HLSLArray(0, typeof(Vector4))] - public fixed float _AreaShadowAtlasSize[4]; + public Vector4 _ShadowAtlasSize; + public Vector4 _CascadeShadowAtlasSize; + public Vector4 _AreaShadowAtlasSize; [HLSLArray(s_MaxEnv2DLight, typeof(Matrix4x4))] public fixed float _Env2DCaptureVP[s_MaxEnv2DLight * 4 * 4]; From ef1c880ecfe111f3db0cac930b2383859f441539 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 6 Mar 2020 17:02:43 +0100 Subject: [PATCH 30/92] Finished up Global Constant Buffer setup --- .../Runtime/Common/ConstantBuffer.cs | 3 +- .../Runtime/Debug/DebugDisplay.cs | 24 ++--- .../Runtime/Lighting/LightLoop/LightLoop.cs | 90 +++++++++--------- .../Lighting/Shadow/HDShadowManager.cs | 2 +- .../Runtime/Material/AxF/AxF.hlsl | 62 ++++++------- .../Runtime/Material/Eye/Eye.hlsl | 8 +- .../Runtime/Material/Fabric/Fabric.hlsl | 6 +- .../Runtime/Material/Hair/Hair.hlsl | 4 +- .../Runtime/Material/Lit/Lit.hlsl | 8 +- .../Runtime/Material/Lit/SimpleLit.hlsl | 6 +- .../Runtime/Material/StackLit/StackLit.hlsl | 92 +++++++++---------- .../SubsurfaceScatteringManager.cs | 2 - .../Runtime/RenderPipeline/Camera/HDCamera.cs | 4 +- .../RenderPipeline/HDRenderPipeline.Debug.cs | 16 ++-- .../HDRenderPipeline.LightLoop.cs | 4 +- .../HDRenderPipeline.RenderGraph.cs | 31 ++----- .../RenderPipeline/HDRenderPipeline.cs | 85 +++++++++-------- .../RenderPipeline/HDStringConstants.cs | 6 +- .../Distortion/ApplyDistortion.shader | 6 +- .../ShaderLibrary/ShaderVariablesGlobal.cs | 5 +- .../ShaderVariablesGlobal.cs.hlsl | 3 +- .../Runtime/Sky/SkyManager.cs | 9 -- 22 files changed, 231 insertions(+), 245 deletions(-) diff --git a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs index 3c1f5f15ea7..54e4edba606 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs @@ -14,9 +14,10 @@ public ConstantBuffer() m_GPUConstantBuffer = new ComputeBuffer(1, UnsafeUtility.SizeOf(), ComputeBufferType.Constant); } - public void Commit(CommandBuffer cmd) + public void Commit(CommandBuffer cmd, int shaderId) { cmd.SetComputeBufferData(m_GPUConstantBuffer, m_Data); + cmd.SetGlobalConstantBuffer(m_GPUConstantBuffer, shaderId, 0, m_GPUConstantBuffer.stride); } public void Release() diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs index 199fd834a91..7de5ea418a1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs @@ -929,54 +929,48 @@ void RegisterLightingDebug() displayName = "Fullscreen Debug Mip", getter = () => { - int id; + float lodCount = 0.0f; switch (data.fullScreenDebugMode) { case FullScreenDebugMode.FinalColorPyramid: case FullScreenDebugMode.PreRefractionColorPyramid: - id = HDShaderIDs._ColorPyramidScale; + //lodCount = hdCamera.colorPyramidHistoryMipCount; break; default: - id = HDShaderIDs._DepthPyramidScale; + //lodCount = depthMipChain.mipLevelCount; break; } - var size = Shader.GetGlobalVector(id); - float lodCount = size.z; return (uint)(data.fullscreenDebugMip * lodCount); }, setter = value => { - int id; + float lodCount = 0.0f; switch (data.fullScreenDebugMode) { case FullScreenDebugMode.FinalColorPyramid: case FullScreenDebugMode.PreRefractionColorPyramid: - id = HDShaderIDs._ColorPyramidScale; + //lodCount = hdCamera.colorPyramidHistoryMipCount; break; default: - id = HDShaderIDs._DepthPyramidScale; + //lodCount = depthMipChain.mipLevelCount; break; } - var size = Shader.GetGlobalVector(id); - float lodCount = size.z; data.fullscreenDebugMip = (float)Convert.ChangeType(value, typeof(float)) / lodCount; }, min = () => 0u, max = () => { - int id; + float lodCount = 0.0f; switch (data.fullScreenDebugMode) { case FullScreenDebugMode.FinalColorPyramid: case FullScreenDebugMode.PreRefractionColorPyramid: - id = HDShaderIDs._ColorPyramidScale; + //lodCount = hdCamera.colorPyramidHistoryMipCount; break; default: - id = HDShaderIDs._DepthPyramidScale; + //lodCount = depthMipChain.mipLevelCount; break; } - var size = Shader.GetGlobalVector(id); - float lodCount = size.z; return (uint)lodCount; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index f86fa3e7718..f1b1073bf77 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3210,7 +3210,6 @@ struct ShadowGlobalParameters { public HDCamera hdCamera; public HDShadowManager shadowManager; - public int sunLightIndex; } ShadowGlobalParameters PrepareShadowGlobalParameters(HDCamera hdCamera) @@ -3218,9 +3217,6 @@ ShadowGlobalParameters PrepareShadowGlobalParameters(HDCamera hdCamera) ShadowGlobalParameters parameters = new ShadowGlobalParameters(); parameters.hdCamera = hdCamera; parameters.shadowManager = m_ShadowManager; - HDAdditionalLightData sunLightData = GetHDAdditionalLightData(m_CurrentSunLight); - bool sunLightShadow = sunLightData != null && m_CurrentShadowSortedSunLightIndex >= 0; - parameters.sunLightIndex = sunLightShadow ? m_CurrentShadowSortedSunLightIndex : -1; return parameters; } @@ -3228,7 +3224,6 @@ struct LightLoopGlobalParameters { public HDCamera hdCamera; public TileAndClusterData tileAndClusterData; - public float clusterScale; } LightLoopGlobalParameters PrepareLightLoopGlobalParameters(HDCamera hdCamera) @@ -3236,45 +3231,73 @@ LightLoopGlobalParameters PrepareLightLoopGlobalParameters(HDCamera hdCamera) LightLoopGlobalParameters parameters = new LightLoopGlobalParameters(); parameters.hdCamera = hdCamera; parameters.tileAndClusterData = m_TileAndClusterData; - parameters.clusterScale = m_ClusterScale; return parameters; } + unsafe void UpdateShaderVariablesGlobalLightLoop(ConstantBuffer cb, HDCamera hdCamera) + { + // Atlases + cb.data._CookieAtlasSize = m_TextureCaches.lightCookieManager.GetCookieAtlasSize(); + cb.data._CookieAtlasData = m_TextureCaches.lightCookieManager.GetCookieAtlasDatas(); + cb.data._PlanarAtlasData = m_TextureCaches.reflectionPlanarProbeCache.GetAtlasDatas(); + cb.data._EnvSliceSize = m_TextureCaches.reflectionProbeCache.GetEnvSliceSize(); + + // Planar reflections + for (int i = 0; i < asset.currentPlatformRenderPipelineSettings.lightLoopSettings.maxPlanarReflectionOnScreen; ++i) + { + for (int j = 0; j < 16; ++j) + cb.data._Env2DCaptureVP[i * 16 + j] = m_TextureCaches.env2DCaptureVP[i][j]; + + for (int j = 0; j < 3; ++j) + cb.data._Env2DCaptureForward[i * 3 + j] = m_TextureCaches.env2DCaptureForward[i * 3 + j]; + + for (int j = 0; j < 4; ++j) + cb.data._Env2DAtlasScaleOffset[i * 4 + j] = m_TextureCaches.env2DAtlasScaleOffset[i][j]; + } + + // Light info + cb.data._PunctualLightCount = (uint)m_lightList.punctualLightCount; + cb.data._AreaLightCount = (uint)m_lightList.areaLightCount; + cb.data._EnvLightCount = (uint)m_lightList.envLights.Count; + cb.data._DirectionalLightCount = (uint)m_lightList.directionalLights.Count; + cb.data._DecalCount = (uint)DecalSystem.m_DecalDatasCount; + HDAdditionalLightData sunLightData = GetHDAdditionalLightData(m_CurrentSunLight); + bool sunLightShadow = sunLightData != null && m_CurrentShadowSortedSunLightIndex >= 0; + cb.data._DirectionalShadowIndex = sunLightShadow ? m_CurrentShadowSortedSunLightIndex : -1; + cb.data._EnableLightLayers = hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers) ? 1u : 0u; + cb.data._EnvLightSkyEnabled = m_SkyManager.IsLightingSkyValid(hdCamera) ? 1 : 0; + + // Tile/Cluster + cb.data._NumTileFtplX = (uint)GetNumTileFtplX(hdCamera); + cb.data._NumTileFtplY = (uint)GetNumTileFtplY(hdCamera); + cb.data.g_fClustScale = m_ClusterScale; + cb.data.g_fClustBase = k_ClustLogBase; + cb.data.g_fNearPlane = hdCamera.camera.nearClipPlane; + cb.data.g_fFarPlane = hdCamera.camera.farClipPlane; + cb.data.g_iLog2NumClusters = k_Log2NumClusters; + cb.data.g_isLogBaseBufferEnabled = k_UseDepthBuffer ? 1 : 0; + cb.data._NumTileClusteredX = (uint)GetNumTileClusteredX(hdCamera); + cb.data._NumTileClusteredY = (uint)GetNumTileClusteredY(hdCamera); + + // Misc + cb.data._EnableSSRefraction = hdCamera.frameSettings.IsEnabled(FrameSettingsField.Refraction) ? 1u : 0u; + } + static void PushLightDataGlobalParams(in LightDataGlobalParameters param, CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PushLightDataGlobalParameters))) { - Camera camera = param.hdCamera.camera; - cmd.SetGlobalTexture(HDShaderIDs._CookieAtlas, param.textureCaches.lightCookieManager.atlasTexture); - cmd.SetGlobalVector(HDShaderIDs._CookieAtlasSize, param.textureCaches.lightCookieManager.GetCookieAtlasSize()); - cmd.SetGlobalVector(HDShaderIDs._CookieAtlasData, param.textureCaches.lightCookieManager.GetCookieAtlasDatas()); cmd.SetGlobalTexture(HDShaderIDs._CookieCubeTextures, param.textureCaches.lightCookieManager.cubeCache); - - cmd.SetGlobalVector(HDShaderIDs._PlanarAtlasData, param.textureCaches.reflectionPlanarProbeCache.GetAtlasDatas()); cmd.SetGlobalTexture(HDShaderIDs._EnvCubemapTextures, param.textureCaches.reflectionProbeCache.GetTexCache()); - cmd.SetGlobalInt(HDShaderIDs._EnvSliceSize, param.textureCaches.reflectionProbeCache.GetEnvSliceSize()); cmd.SetGlobalTexture(HDShaderIDs._Env2DTextures, param.textureCaches.reflectionPlanarProbeCache.GetTexCache()); - cmd.SetGlobalMatrixArray(HDShaderIDs._Env2DCaptureVP, param.textureCaches.env2DCaptureVP); - cmd.SetGlobalFloatArray(HDShaderIDs._Env2DCaptureForward, param.textureCaches.env2DCaptureForward); - cmd.SetGlobalVectorArray(HDShaderIDs._Env2DAtlasScaleOffset, param.textureCaches.env2DAtlasScaleOffset); - // Directional lights are made available immediately after PrepareLightsForGPU for the PBR sky. - // cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, param.lightData.directionalLightData); - // cmd.SetGlobalInt(HDShaderIDs._DirectionalLightCount, param.lightList.directionalLights.Count); cmd.SetGlobalBuffer(HDShaderIDs._LightDatas, param.lightData.lightData); - cmd.SetGlobalInt(HDShaderIDs._PunctualLightCount, param.lightList.punctualLightCount); - cmd.SetGlobalInt(HDShaderIDs._AreaLightCount, param.lightList.areaLightCount); cmd.SetGlobalBuffer(HDShaderIDs._EnvLightDatas, param.lightData.envLightData); - cmd.SetGlobalInt(HDShaderIDs._EnvLightCount, param.lightList.envLights.Count); cmd.SetGlobalBuffer(HDShaderIDs._DecalDatas, param.lightData.decalData); - cmd.SetGlobalInt(HDShaderIDs._DecalCount, DecalSystem.m_DecalDatasCount); - - cmd.SetGlobalInt(HDShaderIDs._EnableSSRefraction, param.hdCamera.frameSettings.IsEnabled(FrameSettingsField.Refraction) ? 1 : 0); // Directional lights are made available immediately after PrepareLightsForGPU for the PBR sky. cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, param.lightData.directionalLightData); - cmd.SetGlobalInt(HDShaderIDs._DirectionalLightCount, param.lightList.directionalLights.Count); } } @@ -3287,7 +3310,6 @@ static void PushShadowGlobalParams(in ShadowGlobalParameters param, CommandBuffe // Shadows param.shadowManager.SyncData(); param.shadowManager.BindResources(cmd); - cmd.SetGlobalInt(HDShaderIDs._DirectionalShadowIndex, param.sunLightIndex); } } @@ -3300,25 +3322,11 @@ static void PushLightLoopGlobalParams(in LightLoopGlobalParameters param, Comman cmd.SetGlobalInt(HDShaderIDs._NumTileBigTileX, GetNumTileBigTileX(param.hdCamera)); cmd.SetGlobalInt(HDShaderIDs._NumTileBigTileY, GetNumTileBigTileY(param.hdCamera)); - cmd.SetGlobalInt(HDShaderIDs._NumTileFtplX, GetNumTileFtplX(param.hdCamera)); - cmd.SetGlobalInt(HDShaderIDs._NumTileFtplY, GetNumTileFtplY(param.hdCamera)); - - cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredX, GetNumTileClusteredX(param.hdCamera)); - cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredY, GetNumTileClusteredY(param.hdCamera)); - if (param.hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass)) cmd.SetGlobalBuffer(HDShaderIDs.g_vBigTileLightList, param.tileAndClusterData.bigTileLightList); // Cluster { - cmd.SetGlobalFloat(HDShaderIDs.g_fClustScale, param.clusterScale); - cmd.SetGlobalFloat(HDShaderIDs.g_fClustBase, k_ClustLogBase); - cmd.SetGlobalFloat(HDShaderIDs.g_fNearPlane, camera.nearClipPlane); - cmd.SetGlobalFloat(HDShaderIDs.g_fFarPlane, camera.farClipPlane); - cmd.SetGlobalInt(HDShaderIDs.g_iLog2NumClusters, k_Log2NumClusters); - - cmd.SetGlobalInt(HDShaderIDs.g_isLogBaseBufferEnabled, k_UseDepthBuffer ? 1 : 0); - cmd.SetGlobalBuffer(HDShaderIDs.g_vLayeredOffsetsBuffer, param.tileAndClusterData.perVoxelOffset); if (k_UseDepthBuffer) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs index 0cb797000f2..4afbe0458db 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs @@ -318,6 +318,7 @@ public static DirectionalShadowAlgorithm GetDirectionalShadowAlgorithm() public void UpdateShaderVariablesGlobalCB(ConstantBuffer cb) { + cb.data._CascadeShadowCount = (uint)(m_CascadeCount + 1); cb.data._ShadowAtlasSize = new Vector4(m_Atlas.width, m_Atlas.height, 1.0f / m_Atlas.width, 1.0f / m_Atlas.height); cb.data._CascadeShadowAtlasSize = new Vector4(m_CascadeAtlas.width, m_CascadeAtlas.height, 1.0f / m_CascadeAtlas.width, 1.0f / m_CascadeAtlas.height); if (ShaderConfig.s_AreaLights == 1) @@ -725,7 +726,6 @@ public void PushGlobalParameters(CommandBuffer cmd) // This code must be in sync with HDShadowContext.hlsl cmd.SetGlobalBuffer(HDShaderIDs._HDShadowDatas, m_ShadowDataBuffer); cmd.SetGlobalBuffer(HDShaderIDs._HDDirectionalShadowData, m_DirectionalShadowDataBuffer); - cmd.SetGlobalInt(HDShaderIDs._CascadeShadowCount, m_CascadeCount + 1); } public void BindResources(CommandBuffer cmd) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.hlsl index 7709d6c8176..5eff4c466d3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.hlsl @@ -31,7 +31,7 @@ //#define DEBUG_HIDE_COAT //----------------------------------------------------------------------------- -#define NdotVMinCosSpread 0.0001 // ie this is the value used by ClampNdotV +#define NdotVMinCosSpread 0.0001 // ie this is the value used by ClampNdotV #ifdef CLEAR_COAT_PERCEPTUAL_ROUGHNESS #undef CLEAR_COAT_PERCEPTUAL_ROUGHNESS @@ -519,7 +519,7 @@ float Fresnel0ToIorSafe(float fresnel0) // we always do conversion as if top has an IOR of 1.0, as the f0 is assumed // measured and baked-in, ie to be evaluated as-is, with whatever was specified // for the top in the rest of the AxF. - return Fresnel0ToIor(min(0.999, fresnel0)); + return Fresnel0ToIor(min(0.999, fresnel0)); } //---------------------------------------------------------------------- @@ -572,7 +572,7 @@ float3 GetBRDFColor(float thetaH, float thetaD) // [ Update1: // Enable this path: in short, the color table seems fully defined in the sample tried like X-Rite_12-PTF_Blue-Violet_NR.axf, // and while acos() yields values up to PI, negative input values shouldn't be used - // for cos(thetaH) (under horizon) and for cos(thetaD), it shouldn't even be possible. + // for cos(thetaH) (under horizon) and for cos(thetaD), it shouldn't even be possible. // ] float2 UV = float2(2.0 * thetaH / PI, 2.0 * thetaD / PI); @@ -588,7 +588,7 @@ float3 GetBRDFColor(float thetaH, float thetaD) // as when thetaH > 0, in the worst case when phiD = 0, thetaD must be <= (PI/2 - thetaH) // ie when thetaH = PI/2 and phiD = 0, thetaD must be 0, // while all values from 0 to PI/2 of thetaD are possible if phiD = PI/2. - // (This is the reason the phiD = PI/2 "slice" contains more information on the BSDF, + // (This is the reason the phiD = PI/2 "slice" contains more information on the BSDF, // see also s2012_pbs_disney_brdf_notes_v3.pdf p4-5) // // But with only thetaH and thetaD indexing the table, phiD is ignored, and the @@ -750,7 +750,7 @@ struct PreLightData float iblPerceptualRoughness; float3 specularFGD; float diffuseFGD; -#elif defined(_AXF_BRDF_TYPE_CAR_PAINT) +#elif defined(_AXF_BRDF_TYPE_CAR_PAINT) #if !defined(USE_COOK_TORRANCE_MULTI_LOBES) float iblPerceptualRoughness; // Use this to store an average lobe roughness float3 specularCTFGDSingleLobe; @@ -900,8 +900,8 @@ float3 CarPaint_BTF(float thetaH, float thetaD, BSDFData bsdfData) // // // // WARNING: double check SDK but our original code was wrong in that case: // // - // // Note that in that case, thetaD_low can be == to thetaD_high, - // // eg with + // // Note that in that case, thetaD_low can be == to thetaD_high, + // // eg with // // _CarPaint_numThetaI = 7, // // _CarPaint_numThetaF = 12, // // original thetaD_low = 2 (and thus original thetaD_high = 3). @@ -911,7 +911,7 @@ float3 CarPaint_BTF(float thetaH, float thetaD, BSDFData bsdfData) // // // // Again in our original code, we systematically took thetaD_high == thetaD_low + 1 when // // verifying the indexing limit using for LUT1: - // // + // // // // uint LUT0 = SampleFlakesLUT(thetaD_low); // // uint LUT1 = SampleFlakesLUT(thetaD_high); // // uint LUT2 = SampleFlakesLUT(thetaD_high + 1); @@ -987,8 +987,8 @@ float3 FindAverageBaseLobeDirOnTop(BSDFData bsdfData, PreLightData preLightData) { float3 outDir; -#if 0 - // simple test: eg for carpaint or any material without any normal maps, this should give the same +#if 0 + // simple test: eg for carpaint or any material without any normal maps, this should give the same // fetch alignment as just using the view reflected on top: float3 vRefractedBottomReflected = reflect(-preLightData.viewWS_UnderCoat, bsdfData.normalWS); outDir = Refract(-vRefractedBottomReflected, -bsdfData.clearcoatNormalWS, bsdfData.clearcoatIOR); @@ -1003,14 +1003,14 @@ float3 FindAverageBaseLobeDirOnTop(BSDFData bsdfData, PreLightData preLightData) //outDir = Refract(-vRefractedBottomReflected, -bsdfData.clearcoatNormalWS, bsdfData.clearcoatIOR); //return outDir; - // Now whether the direction was past the critical angle nor not, refract while making sure that + // Now whether the direction was past the critical angle nor not, refract while making sure that // in case of TIR, we just output an horizon grazing direction: - + //to debug when actually TIR happened: - float3 incomingSaturated; + float3 incomingSaturated; float rayIntensity; outDir = RefractSaturateToTIR(-vRefractedBottomReflected, -bsdfData.clearcoatNormalWS, bsdfData.clearcoatIOR, rayIntensity, incomingSaturated); -#endif +#endif return outDir; } @@ -1045,7 +1045,7 @@ PreLightData GetPreLightData(float3 viewWS_Clearcoat, PositionInputs posInput // Handle IBL + multiscattering // todo_dir: // todo_dir todo_modes todo_pseudorefract: cant use undercoat like that, but better than to lose the bottom normal effect for now... - preLightData.iblDominantDirectionWS_UnderCoat = reflect(-preLightData.viewWS_UnderCoat, bsdfData.normalWS); + preLightData.iblDominantDirectionWS_UnderCoat = reflect(-preLightData.viewWS_UnderCoat, bsdfData.normalWS); if (HasClearcoatAndRefraction()) { preLightData.iblDominantDirectionWS_UnderCoat = FindAverageBaseLobeDirOnTop(bsdfData, preLightData); // much better @@ -1057,7 +1057,7 @@ PreLightData GetPreLightData(float3 viewWS_Clearcoat, PositionInputs posInput // @TODO => Anisotropic IBL? // TODO_SL preLightData.iblPerceptualRoughness = RoughnessToPerceptualRoughness(GetScalarRoughnessFromAnisoRoughness(bsdfData.roughness.x, bsdfData.roughness.y)); - + // todo_fresnel: TOCHECK: Make BRDF and FGD for env. consistent with dirac lights for HasFresnelTerm() handling: // currently, we only check it for Ward and its variants. float3 tempF0 = HasFresnelTerm() ? bsdfData.fresnelF0.rrr : 1.0; @@ -1107,7 +1107,7 @@ PreLightData GetPreLightData(float3 viewWS_Clearcoat, PositionInputs posInput preLightData.singleBRDFColor = 1.0; float thetaH = 0; //acos(clamp(NdotH, 0, 1)); float thetaD = acos(clamp(preLightData.NdotV_UnderCoat, 0, 1)); - + preLightData.singleBRDFColor *= GetBRDFColor(thetaH, thetaD); preLightData.singleFlakesComponent = CarPaint_BTF(thetaH, thetaD, bsdfData); @@ -1172,8 +1172,8 @@ PreLightData GetPreLightData(float3 viewWS_Clearcoat, PositionInputs posInput // captured by a high res normal map with the problems that this implies. // So instead we have a pseudo BTF that is the "left overs" that the CT lobes don't fit, indexed // by two angles (which is theoretically a problem, see comments in GetBRDFColor). - // If we wanted to add more variations on top, here we could consider - // a pre-integrated FGD for flakes. + // If we wanted to add more variations on top, here we could consider + // a pre-integrated FGD for flakes. // If we assume very low roughness like the coat, we could also approximate it as being a Fresnel // term like for coatFGD below. // If the f0 is already very high though (metallic flakes), the variations won't be substantial. @@ -1222,7 +1222,7 @@ PreLightData GetPreLightData(float3 viewWS_Clearcoat, PositionInputs posInput switch ((_SVBRDF_BRDFType >> 1) & 7) { // Warning: all these LTC_MATRIX_INDEX_ are the same for now, and fitted for GGX, hence the code - // above that selected the UVs all used a preLightData.iblPerceptualRoughness value that used a + // above that selected the UVs all used a preLightData.iblPerceptualRoughness value that used a // conversion formula for Beckmann NDF (exp) based BRDFs // (see switch ((_SVBRDF_BRDFType >> 1) & 7) above and usage of PerceptualRoughnessBeckmannToGGX) // @@ -1431,14 +1431,14 @@ float3 ComputeWard(float3 H, float LdotH, float NdotL, float NdotV, PreLightData float2 roughness = max(0.0001, bsdfData.roughness); //if (bsdfData.roughness.y == 0.0) bsdfData.specularColor = float3(1,0,0); - if (roughness.x * roughness.y <= 0.0001 && tsH.z < 1.0) + if (roughness.x * roughness.y <= 0.0001 && tsH.z < 1.0) { return 0; } - + float N = exp(-Sq(rotH.x / roughness.x) - Sq(rotH.y / roughness.y)); N /= max(0.0001, PI * roughness.x * roughness.y); - //N /= (PI * roughness.x * roughness.y); + //N /= (PI * roughness.x * roughness.y); switch ((_SVBRDF_BRDFVariants >> 2) & 3) { @@ -1975,7 +1975,7 @@ DirectLighting EvaluateBSDF_Line( LightLoopContext lightLoopContext, thetaH = acos(clamp(NdotH, 0, 1)); thetaD = acos(clamp(VdotH, 0, 1)); #else - // Just use the same assumptions as for environments + // Just use the same assumptions as for environments // (already calculated thetaH and thetaD above) #endif //now already in rebuilt specularFGD: lighting.specular *= GetBRDFColor(thetaH, thetaD); @@ -2180,7 +2180,7 @@ DirectLighting EvaluateBSDF_Rect(LightLoopContext lightLoopContext, // Evaluate a BRDF color response in specular direction // We project the point onto the area light's plane using the reflected view direction and recompute the light direction from this position - // TODO_dir: + // TODO_dir: #if 0 float3 bestLightWS_Specular = ComputeBestLightDirection_Rectangle(lightPositionRWS, preLightData.iblDominantDirectionWS_UnderCoat, lightData); @@ -2194,7 +2194,7 @@ DirectLighting EvaluateBSDF_Rect(LightLoopContext lightLoopContext, thetaH = acos(clamp(NdotH, 0, 1)); thetaD = acos(clamp(VdotH, 0, 1)); #else - // Just use the same assumptions as for environments + // Just use the same assumptions as for environments // (already calculated thetaH and thetaD above) #endif @@ -2349,7 +2349,7 @@ float GetEnvMipLevel(EnvLightData lightData, float iblPerceptualRoughness) if (IsEnvIndexTexture2D(lightData.envIndex)) { // Empirical remapping - iblMipLevel = PlanarPerceptualRoughnessToMipmapLevel(iblPerceptualRoughness, _ColorPyramidScale.z); + iblMipLevel = PlanarPerceptualRoughnessToMipmapLevel(iblPerceptualRoughness, _ColorPyramidLodCount); } else { @@ -2407,7 +2407,7 @@ IndirectLighting EvaluateBSDF_Env( LightLoopContext lightLoopContext, #if defined(_AXF_BRDF_TYPE_SVBRDF) float3 envLighting = 0.0; - + float NdotV = ClampNdotV(preLightData.NdotV_UnderCoat); environmentSamplingDirectionWS_UnderCoat = GetModifiedEnvSamplingDir(lightData, bsdfData.normalWS, preLightData.iblDominantDirectionWS_UnderCoat, preLightData.iblPerceptualRoughness, NdotV); @@ -2432,7 +2432,7 @@ IndirectLighting EvaluateBSDF_Env( LightLoopContext lightLoopContext, float NdotV = ClampNdotV(preLightData.NdotV_UnderCoat); // A part of this BRDF depends on thetaH and thetaD and should thus have entered - // the split sum pre-integration. We do a further approximation by pulling those + // the split sum pre-integration. We do a further approximation by pulling those // terms out and evaluating them in the specular dominant direction, // for BRDFColor and flakes. float3 viewWS_UnderCoat = preLightData.viewWS_UnderCoat; @@ -2510,7 +2510,7 @@ IndirectLighting EvaluateBSDF_Env( LightLoopContext lightLoopContext, EvaluateLight_EnvIntersection(positionWS, bsdfData.clearcoatNormalWS, lightData, _influenceShapeType, lightWS_Clearcoat, unusedWeight); // Attenuate environment lighting under the clearcoat by the complement to the Fresnel term - //todo_energy: + //todo_energy: envLighting *= 1.0 - preLightData.coatFGD; //envLighting *= Sq(1.0 - preLightData.coatFGD); @@ -2561,7 +2561,7 @@ void PostEvaluateBSDF( LightLoopContext lightLoopContext, // // WIP // -// todo/tocheck_envsampling, envsampling_test, todotodo, +// todo/tocheck_envsampling, envsampling_test, todotodo, // todo_dir todo_modes todo_pseudorefract // todo_energy // todo_fresnel diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/Eye.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/Eye.hlsl index df704ded1ff..63f72077d62 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/Eye.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/Eye.hlsl @@ -48,7 +48,7 @@ void ApplyDebugToSurfaceData(float3x3 tangentToWorld, inout SurfaceData surfaceD bool overrideAlbedo = _DebugLightingAlbedo.x != 0.0; bool overrideSmoothness = _DebugLightingSmoothness.x != 0.0; bool overrideNormal = _DebugLightingNormal.x != 0.0; - bool overrideAO = _DebugLightingAmbientOcclusion.x != 0.0; + bool overrideAO = _DebugLightingAmbientOcclusion.x != 0.0; if (overrideAlbedo) { @@ -135,7 +135,7 @@ BSDFData ConvertSurfaceDataToBSDFData(uint2 positionSS, SurfaceData surfaceData) bsdfData.diffuseNormalWS = surfaceData.irisNormalWS; bsdfData.geomNormalWS = surfaceData.geomNormalWS; - bsdfData.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness); + bsdfData.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness); bsdfData.fresnel0 = IorToFresnel0(surfaceData.IOR).xxx; bsdfData.IOR = surfaceData.IOR; @@ -323,7 +323,7 @@ void ModifyBakedDiffuseLighting(float3 V, PositionInputs posInput, SurfaceData s BSDFData bsdfData = ConvertSurfaceDataToBSDFData(posInput.positionSS, surfaceData); PreLightData preLightData = GetPreLightData(V, posInput, bsdfData); - // For SSS we need to take into account the state of diffuseColor + // For SSS we need to take into account the state of diffuseColor if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_EYE_SUBSURFACE_SCATTERING)) { bsdfData.diffuseColor = GetModifiedDiffuseColorForSSS(bsdfData); @@ -797,7 +797,7 @@ IndirectLighting EvaluateBSDF_Env( LightLoopContext lightLoopContext, if (IsEnvIndexTexture2D(lightData.envIndex)) { // Empirical remapping - iblMipLevel = PlanarPerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness, _ColorPyramidScale.z); + iblMipLevel = PlanarPerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness, _ColorPyramidLodCount); } else { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/Fabric.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/Fabric.hlsl index edba96f2019..244e6a7d0ad 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/Fabric.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/Fabric.hlsl @@ -160,7 +160,7 @@ BSDFData ConvertSurfaceDataToBSDFData(uint2 positionSS, SurfaceData surfaceData) // In forward everything is statically know and we could theorically cumulate all the material features. So the code reflect it. // However in practice we keep parity between deferred and forward, so we should constrain the various features. // The UI is in charge of setuping the constrain, not the code. So if users is forward only and want unleash power, it is easy to unleash by some UI change - + bsdfData.diffusionProfileIndex = FindDiffusionProfileIndex(surfaceData.diffusionProfileHash); if (HasFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_FABRIC_SUBSURFACE_SCATTERING)) @@ -329,7 +329,7 @@ void ModifyBakedDiffuseLighting(float3 V, PositionInputs posInput, SurfaceData s builtinData.bakeDiffuseLighting += builtinData.backBakeDiffuseLighting * bsdfData.transmittance; } - // For SSS we need to take into account the state of diffuseColor + // For SSS we need to take into account the state of diffuseColor if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_FABRIC_SUBSURFACE_SCATTERING)) { bsdfData.diffuseColor = GetModifiedDiffuseColorForSSS(bsdfData); @@ -621,7 +621,7 @@ IndirectLighting EvaluateBSDF_Env( LightLoopContext lightLoopContext, if (IsEnvIndexTexture2D(lightData.envIndex)) { // Empirical remapping - iblMipLevel = PositivePow(preLightData.iblPerceptualRoughness, 0.8) * uint(max(_ColorPyramidScale.z - 1, 0)); + iblMipLevel = PositivePow(preLightData.iblPerceptualRoughness, 0.8) * uint(max(_ColorPyramidLodCount - 1, 0)); } else { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/Hair.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/Hair.hlsl index 9f0642346ef..2d0d91bd56d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/Hair.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/Hair.hlsl @@ -155,7 +155,7 @@ BSDFData ConvertSurfaceDataToBSDFData(uint2 positionSS, SurfaceData surfaceData) // Kajiya kay if (HasFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_HAIR_KAJIYA_KAY)) { - bsdfData.secondaryPerceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(surfaceData.secondaryPerceptualSmoothness); + bsdfData.secondaryPerceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(surfaceData.secondaryPerceptualSmoothness); bsdfData.specularTint = surfaceData.specularTint; bsdfData.secondarySpecularTint = surfaceData.secondarySpecularTint; bsdfData.specularShift = surfaceData.specularShift; @@ -565,7 +565,7 @@ IndirectLighting EvaluateBSDF_Env( LightLoopContext lightLoopContext, if (IsEnvIndexTexture2D(lightData.envIndex)) { // Empirical remapping - iblMipLevel = PositivePow(preLightData.iblPerceptualRoughness, 0.8) * uint(max(_ColorPyramidScale.z - 1, 0)); + iblMipLevel = PositivePow(preLightData.iblPerceptualRoughness, 0.8) * uint(max(_ColorPyramidLodCount - 1, 0)); } else { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl index d4dcfc77194..f81a686479c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl @@ -1105,7 +1105,7 @@ PreLightData GetPreLightData(float3 V, PositionInputs posInput, inout BSDFData b // Empirical remap to try to match a bit the refraction probe blurring for the fallback // Use IblPerceptualRoughness so we can handle approx of clear coat. - preLightData.transparentSSMipLevel = PositivePow(preLightData.iblPerceptualRoughness, 1.3) * uint(max(_ColorPyramidScale.z - 1, 0)); + preLightData.transparentSSMipLevel = PositivePow(preLightData.iblPerceptualRoughness, 1.3) * uint(max(_ColorPyramidLodCount - 1, 0)); #endif return preLightData; @@ -1708,7 +1708,7 @@ IndirectLighting EvaluateBSDF_ScreenSpaceReflection(PositionInputs posInput, // Apply the weight on the ssr contribution (if required) ApplyScreenSpaceReflectionWeight(ssrLighting); - + // TODO: we should multiply all indirect lighting by the FGD value only ONCE. lighting.specularReflected = ssrLighting.rgb * preLightData.specularFGD; reflectionHierarchyWeight = ssrLighting.a; @@ -1775,7 +1775,7 @@ IndirectLighting EvaluateBSDF_ScreenspaceRefraction(LightLoopContext lightLoopCo float2 samplingPositionNDC = lerp(posInput.positionNDC, hit.positionNDC, refractionOffsetMultiplier); float3 preLD = SAMPLE_TEXTURE2D_X_LOD(_ColorPyramidTexture, s_trilinear_clamp_sampler, // Offset by half a texel to properly interpolate between this pixel and its mips - samplingPositionNDC * _ColorPyramidScale.xy, preLightData.transparentSSMipLevel).rgb; + samplingPositionNDC * _RTHandleScaleHistory.xy, preLightData.transparentSSMipLevel).rgb; // Inverse pre-exposure preLD *= GetInverseCurrentExposureMultiplier(); @@ -1873,7 +1873,7 @@ IndirectLighting EvaluateBSDF_Env( LightLoopContext lightLoopContext, if (IsEnvIndexTexture2D(lightData.envIndex)) { // Empirical remapping - iblMipLevel = PlanarPerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness, _ColorPyramidScale.z); + iblMipLevel = PlanarPerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness, _ColorPyramidLodCount); } else { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/SimpleLit.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/SimpleLit.hlsl index 6e311ca6951..93ee8bb6450 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/SimpleLit.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/SimpleLit.hlsl @@ -34,7 +34,7 @@ float3 GetNormalForShadowBias(BSDFData bsdfData) return bsdfData.geomNormalWS; #else return bsdfData.normalWS; -#endif +#endif } float GetAmbientOcclusionForMicroShadowing(BSDFData bsdfData) @@ -229,7 +229,7 @@ PreLightData GetPreLightData(float3 V, PositionInputs posInput, inout BSDFData b preLightData.transparentTransmittance = exp(-bsdfData.absorptionCoefficient * refraction.dist); // Empirical remap to try to match a bit the refraction probe blurring for the fallback // Use IblPerceptualRoughness so we can handle approx of clear coat. - preLightData.transparentSSMipLevel = PositivePow(preLightData.iblPerceptualRoughness, 1.3) * uint(max(_ColorPyramidScale.z - 1, 0)); + preLightData.transparentSSMipLevel = PositivePow(preLightData.iblPerceptualRoughness, 1.3) * uint(max(_ColorPyramidLodCount - 1, 0)); #endif return preLightData; @@ -423,7 +423,7 @@ IndirectLighting EvaluateBSDF_Env( LightLoopContext lightLoopContext, if (IsEnvIndexTexture2D(lightData.envIndex)) { // Empirical remapping - iblMipLevel = PlanarPerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness, _ColorPyramidScale.z); + iblMipLevel = PlanarPerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness, _ColorPyramidLodCount); } else { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLit.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLit.hlsl index ac030a088d9..e8ccf9b6967 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLit.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLit.hlsl @@ -178,7 +178,7 @@ void GetAmbientOcclusionFactor(float3 indirectAmbientOcclusion, float3 indirectS #define TOP_DIR_IDX 0 #define BOTTOM_DIR_IDX (NB_LV_DIR-1) -// BASE_NB_LOBES will never be 1, we let the compiler optimize +// BASE_NB_LOBES will never be 1, we let the compiler optimize // everything out from bsdfData.lobeMix = 0; #define BASE_NB_LOBES 2 // use numeric indices for these arrays #define TOTAL_NB_LOBES (BASE_NB_LOBES+COAT_NB_LOBES) // use *_LOBE?_IDX for these arrays. @@ -252,9 +252,9 @@ bool IsCoatNormalMapEnabled(BSDFData bsdfData) // based on Fresnel terms (hack to reduce pre-integrated FGD fetches TODOENERGY). // // Normally when shading with normal maps, we clamp / saturate diverse values -// (eg see here BSDF_SetupNormalsAndAngles or CommonLighting's GetBSDFAngle) to avoid +// (eg see here BSDF_SetupNormalsAndAngles or CommonLighting's GetBSDFAngle) to avoid // special casing the BSDF evaluation but still shade according to the normal maps. -// Fresnel is normally evaluated with the LdotH angle, but this normally never "clips" +// Fresnel is normally evaluated with the LdotH angle, but this normally never "clips" // to the hemisphere (oriented on the normal) the complete BSDF evaluation as LdotH is // never negative (H is at most 90 degrees away from L and V). // @@ -271,9 +271,9 @@ bool IsCoatNormalMapEnabled(BSDFData bsdfData) // Obviously this is still a hack as stated but is more pleasing and is roughly akin to // having the top layer "folds" as dual-faced. // -// When no recompute per light is done or we are doing ComputeAdding in the first call in +// When no recompute per light is done or we are doing ComputeAdding in the first call in // GetPreLightData for split-sum type of lights (non dirac), we don't have a particular L -// to use and use clamped NdotV. In that case, the normal is taken as the H vector, and +// to use and use clamped NdotV. In that case, the normal is taken as the H vector, and // there will be regions where NdotV can be negative so is clamped near zero. In that case, // being in the "grazing angle region", integrated FGD or Fresnel would yeld reflectance // operators that yield zero energy transmitted to the bottom layer, and everything reflected @@ -285,15 +285,15 @@ bool IsCoatNormalMapEnabled(BSDFData bsdfData) // the geometric normal on the top since it should not be back facing to begin the // computations - in that case, we lose the Fresnel variations induced by the top normal map // and it only affects other parts of BSDF evaluations later for all types of lights. -// +// // This is VLAYERED_DUAL_NORMALS_TOP_FIX_GEOM_NORMAL. // // Otherwise, we also provide a behavior similar to flipping of the normal, and we even // saturate a bit less close to zero (than ClampNdotV) to remove the effect of the grazing -// angle. +// angle. // // This is VLAYERED_DUAL_NORMALS_TOP_FIX_FLIP_NORMAL -// +// #define VLAYERED_DUAL_NORMALS_TOP_FIX_DEFAULT 0 // do nothing #define VLAYERED_DUAL_NORMALS_TOP_FIX_GEOM_NORMAL 1 #define VLAYERED_DUAL_NORMALS_TOP_FIX_FLIP_NORMAL 2 @@ -565,7 +565,7 @@ void ApplyDebugToSurfaceData(float3x3 tangentToWorld, inout SurfaceData surfaceD // There is no metallic with SSS and specular color mode float metallic = HasFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_SPECULAR_COLOR | MATERIALFEATUREFLAGS_STACK_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_STACK_LIT_TRANSMISSION) ? 0.0 : surfaceData.metallic; - + float3 diffuseColor = ComputeDiffuseColor(surfaceData.baseColor, metallic); bool specularWorkflow = HasFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_SPECULAR_COLOR); float3 specularColor = specularWorkflow ? surfaceData.specularColor : ComputeFresnel0(surfaceData.baseColor, surfaceData.metallic, IorToFresnel0(surfaceData.dielectricIor)); @@ -635,7 +635,7 @@ NormalData ConvertSurfaceDataToNormalData(SurfaceData surfaceData) { // In HazyGloss mode. ConvertSurfaceDataToNormalData() would need positionSS and to call // ConvertSurfaceDataToBSDFData, might be too heavy for a prepass, maybe find a lightweight approximation - // of HazeMapping. + // of HazeMapping. // This is a moot point though: mixing two roughnesses directly in one is already a hack, the // resulting lobe isn't representative of this. But for what ConvertSurfaceDataToNormalData() influences // (like SSR and shadows), it might be sufficient. @@ -672,7 +672,7 @@ NormalData ConvertSurfaceDataToNormalData(SurfaceData surfaceData) void HazeMapping(float3 fresnel0, float roughnessAT, float roughnessAB, float haziness, float hazeExtent, float hazeExtentAnisotropy, float3 hazyGlossMaxf0, inout BSDFData bsdfData) { float w = 10.0; // interpolation steepness weight (Bezier weight of central point) - bool useBezierToMapKh = true; + bool useBezierToMapKh = true; float3 r_c = fresnel0; // We can use clamping of roughnessA here to avoid a "p == 0/0" case if roughnessA == 0. @@ -705,7 +705,7 @@ void HazeMapping(float3 fresnel0, float roughnessAT, float roughnessAB, float ha // maximum core roughness and since this primary roughness (of lobe A) can be textured, we // don't know it). float p = alpha_n_xy/alpha_w_xy; // peak ratio formula at theta_d = 0 (ie p is in the paper := P(0)) - + float r_c_max = Max3(r_c.r, r_c.g, r_c.b); float k_h_max = 0.0; @@ -714,13 +714,13 @@ void HazeMapping(float3 fresnel0, float roughnessAT, float roughnessAB, float ha bsdfData.lobeMix = 0.0; } //else if (alpha_w_xy <= FLT_EPS) { bsdfData.lobeMix = beta_h; } - else + else { if (useBezierToMapKh) { // Smooth out C1 discontinuity at k_h = p with a Bezier curve // (loose some hazeExtent in the process). - + float b = 2*(r_c_max*(1-w)+w*p); float u; // parametric coordinate for rational Bezier curve if (abs(2*(b-1)) <= FLT_EPS) @@ -740,18 +740,18 @@ void HazeMapping(float3 fresnel0, float roughnessAT, float roughnessAB, float ha // Interpolation between 0 and positivity and energy constraints: these are lines // but form a triangle so there's a discontinuity at k_h := K_h(0) = p, hence the // branch here: - k_h_max = (r_c_max > p) ? beta_h*(1-r_c_max)/(1-p) : beta_h*r_c_max/p; + k_h_max = (r_c_max > p) ? beta_h*(1-r_c_max)/(1-p) : beta_h*r_c_max/p; } - + float r_max = r_c_max + (1-p)*k_h_max; // compound reflectivity (max color channel) float3 chromaVec = r_c/r_c_max; - + bsdfData.fresnel0 = r_max*chromaVec; bsdfData.fresnel0 = min(bsdfData.fresnel0, hazyGlossMaxf0); bsdfData.lobeMix = k_h_max / r_max; //bsdfData.lobeMix = 0.5; - // For IBL, convert back to the scalar roughness + anisotropy parametrization for the + // For IBL, convert back to the scalar roughness + anisotropy parametrization for the // secondary lobe: float anisotropyB; float roughnessB; @@ -829,7 +829,7 @@ BSDFData ConvertSurfaceDataToBSDFData(uint2 positionSS, SurfaceData surfaceData) // It is important to deal with the hazy gloss parametrization after we have fresnel0 for the base but // before the effect of the coat is applied on it. When hazy gloss is used, the current fresnel0 at this // point is reinterpreted as a pseudo-f0 ("core lobe reflectivity" or Fc(0) or r_c in the paper) - // + // if (HasFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_HAZY_GLOSS)) { // reminder: ComputeFresnel0 lerps from last param to first param using middle param as lerp factor. @@ -1070,7 +1070,7 @@ struct PreLightData float screenSpaceAmbientOcclusion; // Keep a copy of the screen space occlusion texture fetch between // PreLightData and PostEvaluateBSDF. float3 hemiSpecularOcclusion[TOTAL_NB_LOBES]; // Specular occlusion calculated from roughness and for an unknown - // (the less sparse / more uniform the better) light structure + // (the less sparse / more uniform the better) light structure // potentially covering the whole hemisphere. }; @@ -1096,7 +1096,7 @@ struct PreLightData // 1b) Clamp input roughnesses before the stack computations, so that the new top roughness also impacts the bottom. // // 2) For 1b), we also could interpret the minRoughness as clamping the coat only: since the bottom will get the -// impact of the clamp indirectly, this could suffice. +// impact of the clamp indirectly, this could suffice. // // As the light.minRoughness is a hack that can be used to simulate a sphere light from a point light, all options // can be valid, it depends on what appearance the user wants. @@ -1146,7 +1146,7 @@ void ClampRoughness(inout PreLightData preLightData, inout BSDFData bsdfData, fl // we don't update this, no need to: bsdfData.coatPerceptualRoughness = RoughnessToPerceptualRoughness(bsdfData.coatRoughness); } } - + if (!GetRecomputeStackPerLightOption()) { preLightData.layeredRoughnessT[0] = max(minRoughness, preLightData.layeredRoughnessT[0]); @@ -1164,7 +1164,7 @@ void ClampRoughness(inout PreLightData preLightData, inout BSDFData bsdfData, fl { preLightData.layeredCoatRoughness = max(minRoughness, preLightData.layeredCoatRoughness); } - + preLightData.layeredRoughnessT[0] = max(minRoughness, preLightData.layeredRoughnessT[0]); preLightData.layeredRoughnessT[1] = max(minRoughness, preLightData.layeredRoughnessT[1]); preLightData.layeredRoughnessB[0] = max(minRoughness, preLightData.layeredRoughnessB[0]); @@ -1261,7 +1261,7 @@ float3 GetOrthogonalComponent(float3 V, float3 N, bool testSingularity = false) if (testSingularity && (abs(1.0 - VdotN) <= FLT_EPS)) { // In this case N == V, and azimuth orientation around N shouldn't matter for the caller, - // we can use any quaternion-based method, like Frisvad or Reynold's (Pixar): + // we can use any quaternion-based method, like Frisvad or Reynold's (Pixar): float3x3 orthoBasis = GetLocalFrame(N); unitVOrtho = orthoBasis[0]; // we pick any axis, compiler should optimize out calculation of [1] } @@ -1522,7 +1522,7 @@ void ComputeStatistics(in float cti, in float3 V, in float3 vOrthoGeomN, in bo if( stt <= 1.0f ) { // See p5 fig5 a) vs b) : using a refraction as a peak mean is the dotted line, while the ref is the solid line. - // The scale is a hack to reproduce this effect: + // The scale is a hack to reproduce this effect: // As roughness -> 1, remove the effect of changing angle of entry. // Note that we never track complete means per se because of symmetry, we have no azimuth, so the "space" of the // means sin(theta) (here sti and stt) is just a line perpendicular to the normal in the plane of incidence. @@ -1704,9 +1704,9 @@ void ComputeAdding(float _cti, float3 V, in BSDFData bsdfData, inout PreLightDat { // Just a precaution minRoughness = 0.0; - // ie We will only take it into account if called per light. + // ie We will only take it into account if called per light. // If GetHonorPerLightMinRoughness(), we will still escape the default clamp of ClampRoughnessForDiracLightsByDefault() though. - // The net result if we're never recomputing the stack per light but signal we honor the per-light minRoughness is that we + // The net result if we're never recomputing the stack per light but signal we honor the per-light minRoughness is that we // won't clamp anything in ComputeAdding and just late clamp the resulting roughnesses at each light evaluation via ClampRoughness(). // The change in coat roughness will obviously not affect the bottom roughness in that case and the results will be wrong, but // depending on the scene setup, could be acceptable. @@ -1876,7 +1876,7 @@ void ComputeAdding(float _cti, float3 V, in BSDFData bsdfData, inout PreLightDat // Update mean - // Avoid grazing angle black artefacts and instead of + // Avoid grazing angle black artefacts and instead of // cti = ctt; cti = ClampNdotV(ctt); @@ -2476,10 +2476,10 @@ void PreLightData_SetupOcclusion(PositionInputs posInput, BSDFData bsdfData, flo // -We have 3 lobes with different roughnesses, and these have been placed unclamped and modified by vlayering in // iblPerceptualRoughness[]. // -We might have 2 different shading normals to consider. - // -Bentnormal is always considered if the algorithm permits it, but it might trivially be the normal if no bent + // -Bentnormal is always considered if the algorithm permits it, but it might trivially be the normal if no bent // normals were given by the user. // - // -Finally, our pre-calculated specular occlusion will serve for IBL for now, which have unknown structure so the + // -Finally, our pre-calculated specular occlusion will serve for IBL for now, which have unknown structure so the // whole hemisphere around the normal is taken as potential light visibility region, that's why the pre-calculated // values are identified as "hemiSpecularOcclusion". This would potentially need to be different per light type, // or even per light: @@ -2679,7 +2679,7 @@ PreLightData GetPreLightData(float3 V, PositionInputs posInput, inout BSDFData b float diffuseFGDTmp; // unused, for coat layer FGD fetch - // We will do the coat specific FGD fetch here: + // We will do the coat specific FGD fetch here: // (FGD fetches used for IBL + area light + multiscattering) GetPreIntegratedFGDGGXAndDisneyDiffuse(NdotV[COAT_NORMAL_IDX], preLightData.iblPerceptualRoughness[COAT_LOBE_IDX], @@ -2688,7 +2688,7 @@ PreLightData GetPreLightData(float3 V, PositionInputs posInput, inout BSDFData b diffuseFGDTmp, specularReflectivity[COAT_LOBE_IDX]); - // We apply the coatMask here since even an f0 of 0 in the fetch above will give a + // We apply the coatMask here since even an f0 of 0 in the fetch above will give a // directional albedo (aka specular reflectivity) that is non zero: preLightData.specularFGD[COAT_LOBE_IDX] *= bsdfData.coatMask; // This is for the base FGD fetches factored out of "if vlayering or not": @@ -2775,7 +2775,7 @@ PreLightData GetPreLightData(float3 V, PositionInputs posInput, inout BSDFData b if (AREA_LIGHTS_ANISOTROPY_ENABLED == false) { // If area lights don't support anisotropy, we can setup area lights here and occlusion after, as the former - // don't need the anisotropic modified normal and roughness (IBL anisotropy hack) and the later can use + // don't need the anisotropic modified normal and roughness (IBL anisotropy hack) and the later can use // the area lights preLightData.orthoBasisViewNormal: PreLightData_SetupAreaLights(bsdfData, V, N, NdotV, preLightData); @@ -2803,7 +2803,7 @@ PreLightData GetPreLightData(float3 V, PositionInputs posInput, inout BSDFData b // isn't really needed, as if no vlayering, COAT_LOBE_IDX will be == to one of the BASE_LOBE?_IDX // and the following line will be pruned out by the compiler: preLightData.partLambdaV[COAT_LOBE_IDX] = GetSmithJointGGXPartLambdaV(NdotV[COAT_NORMAL_IDX], preLightData.layeredCoatRoughness); - + preLightData.partLambdaV[BASE_LOBEA_IDX] = GetSmithJointGGXAnisoPartLambdaV(TdotV, BdotV, NdotV[BASE_NORMAL_IDX], preLightData.layeredRoughnessT[0], preLightData.layeredRoughnessB[0]); preLightData.partLambdaV[BASE_LOBEB_IDX] = GetSmithJointGGXAnisoPartLambdaV(TdotV, BdotV, NdotV[BASE_NORMAL_IDX], @@ -2941,7 +2941,7 @@ void ModifyBakedDiffuseLighting(float3 V, PositionInputs posInput, SurfaceData s builtinData.bakeDiffuseLighting += builtinData.backBakeDiffuseLighting * bsdfData.transmittance; } - // For SSS we need to take into account the state of diffuseColor + // For SSS we need to take into account the state of diffuseColor if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_SUBSURFACE_SCATTERING)) { bsdfData.diffuseColor = GetModifiedDiffuseColorForSSS(bsdfData); @@ -2953,7 +2953,7 @@ void ModifyBakedDiffuseLighting(float3 V, PositionInputs posInput, SurfaceData s // Note: When baking reflection probes, we approximate the diffuse with the fresnel0 builtinData.bakeDiffuseLighting *= preLightData.diffuseFGD * preLightData.diffuseEnergy * GetDiffuseOrDefaultColor(bsdfData, _ReplaceDiffuseForIndirect).rgb; - // The lobe specific specular occlusion data, along with the result of the screen space occlusion sampling + // The lobe specific specular occlusion data, along with the result of the screen space occlusion sampling // will be computed in PreLightData. } @@ -2979,7 +2979,7 @@ float GetInferredMetallic(float dielectricF0, float3 inDiffuseColor, float3 inFr if (dielectricF0 <= 0.0001) { // The baseColor + metallic parameterization gives (note that this is used to build - // a possible conversion, but the given fresnel0, diffuseColor and dielectricF0 might not + // a possible conversion, but the given fresnel0, diffuseColor and dielectricF0 might not // be possible with a baseColor + metallic parameterization): // // (A) fresnel0 = metallic * basecolor + (1.0 - metallic) * dielectricF0; @@ -3005,7 +3005,7 @@ float GetInferredMetallic(float dielectricF0, float3 inDiffuseColor, float3 inFr // metallic = 1/(diffuseColor/fresnel0 + 1); // metallic = fresnel0/(diffuseColor + fresnel0); // - // So we will use that formula when dielectricF0 == 0 since it outputs plausible values: + // So we will use that formula when dielectricF0 == 0 since it outputs plausible values: // // -When fresnel0 is 0, it will always output a desired (for the reasons discussed above) value of metallic = 0. // -When input values are possible for (A) and (B), the formula is correct (for when dielectricF0 == 0 of course). @@ -3410,9 +3410,9 @@ void GetNLForDirectionalPunctualLights(BSDFData bsdfData, PreLightData preLightD // For the rest, we will use the N which produces the biggest NdotL, as we don't want // to early out eg from the bottom layer when the top should have a highlight, // while the final BSDF evaluation will take care of applying the proper NdotL in any - // case. + // case. // We could increase the cost and complexity of all this and actually - // commit fully to making all these diract-light evaluations local to this file and + // commit fully to making all these diract-light evaluations local to this file and // pass to BSDF the L[], V[], etc. arrays instead of hacking our way around just here. float maxNdotL = max(NdotL[COAT_NORMAL_IDX], NdotL[BASE_NORMAL_IDX]); @@ -3569,7 +3569,7 @@ CBSDF EvaluateBSDF(float3 inV, float3 inL, PreLightData preLightData, BSDFData b // NO VLAYERING: // -------------------------------------------------------------------- - // Note: See GetPreLightData(), in that case, + // Note: See GetPreLightData(), in that case, // preLightData.layeredRoughnessT[0] = bsdfData.roughnessAT; // preLightData.layeredRoughnessB[0] = bsdfData.roughnessAB; // preLightData.layeredRoughnessT[1] = bsdfData.roughnessBT; @@ -3845,7 +3845,7 @@ DirectLighting EvaluateBSDF_Line( LightLoopContext lightLoopContext, { localP1 = mul(P1, transpose(preLightData.orthoBasisViewNormal[COAT_NORMAL_IDX])); localP2 = mul(P2, transpose(preLightData.orthoBasisViewNormal[COAT_NORMAL_IDX])); - B = normalize(cross(localP1, localP2)); + B = normalize(cross(localP1, localP2)); } if (AREA_LIGHTS_ANISOTROPY_ENABLED) // statically known, so no need for if else, just overwrite the above { @@ -4171,7 +4171,7 @@ IndirectLighting EvaluateBSDF_ScreenSpaceReflection(PositionInputs posInput, ApplyScreenSpaceReflectionWeight(ssrLighting); // For performance reasons, SSR doesn't allow us to be discriminating per lobe, ie wrt direction, roughness, - // anisotropy, etc. + // anisotropy, etc. // At least the vlayered BSDF stack model already represents the stack with a single interface with multiple // effective/equivalent lobes. @@ -4181,7 +4181,7 @@ IndirectLighting EvaluateBSDF_ScreenSpaceReflection(PositionInputs posInput, // This is the approach we take since roughnesses between coat and base lobes can be very different, while // if the coat exist, ConvertSurfaceDataToNormalData will output the roughness of the coat and we don't need // a boost of sharp reflections from a potentially rough bottom layer. - + float3 reflectanceFactor = (float3)0.0; if (IsVLayeredEnabled(bsdfData)) @@ -4339,7 +4339,7 @@ IndirectLighting EvaluateBSDF_Env( LightLoopContext lightLoopContext, if (IsEnvIndexTexture2D(lightData.envIndex)) { // Empirical remapping - iblMipLevel = PlanarPerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness[i], _ColorPyramidScale.z); + iblMipLevel = PlanarPerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness[i], _ColorPyramidLodCount); } else { @@ -4397,7 +4397,7 @@ void PostEvaluateBSDF( LightLoopContext lightLoopContext, // bsdfData.diffuseColor is not appropriate to use when vlayered when doing GTAOMultiBounce here, but we can // try something with (bsdfData.diffuseColor * bsdfData.coatExtinction) (for specular occlusion with f0, it's // even worse but both are a hack anyway) We could also try "renormalizing diffuseEnergy" to the luminance of - // diffuseColor. + // diffuseColor. // For now, we use (bsdfData.diffuseColor * preLightData.diffuseEnergy) directly: float3 GTAOMultiBounceTintBase = (bsdfData.diffuseColor * preLightData.diffuseEnergy); GetApplyScreenSpaceDiffuseOcclusionForDirect(GTAOMultiBounceTintBase, preLightData.screenSpaceAmbientOcclusion, directAmbientOcclusion, lighting); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index 4b866be554d..dd909631af4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -197,8 +197,6 @@ unsafe void UpdateShaderVariablesGlobalSubsurface(ConstantBuffer("Push Full Screen Debug", out var passData)) { - passData.scaleBias = mipIndex != -1 ? scaleBias : new Vector4(1.0f, 1.0f, 0.0f, 0.0f); passData.mipIndex = mipIndex; passData.input = builder.ReadTexture(input); passData.output = builder.UseColorBuffer(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) @@ -313,10 +311,12 @@ void PushFullScreenDebugTexture(RenderGraph renderGraph, TextureHandle input, Ve builder.SetRenderFunc( (PushFullScreenDebugPassData data, RenderGraphContext ctx) => { + var texture = ctx.resources.GetTexture(passData.input); + var scale = new Vector4(texture.rtHandleProperties.rtHandleScale.x, texture.rtHandleProperties.rtHandleScale.y, 0f, 0f); if (data.mipIndex != -1) - HDUtils.BlitCameraTexture(ctx.cmd, ctx.resources.GetTexture(passData.input), ctx.resources.GetTexture(passData.output), data.scaleBias, data.mipIndex); + HDUtils.BlitCameraTexture(ctx.cmd, texture, ctx.resources.GetTexture(passData.output), scale, data.mipIndex); else - HDUtils.BlitCameraTexture(ctx.cmd, ctx.resources.GetTexture(passData.input), ctx.resources.GetTexture(passData.output)); + HDUtils.BlitCameraTexture(ctx.cmd, texture, ctx.resources.GetTexture(passData.output)); }); m_DebugFullScreenTexture = passData.output; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index b83ba5f13f9..188fb48f113 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -336,8 +336,8 @@ class RenderContactShadowPassData public ContactShadowsParameters parameters; public LightLoopLightData lightLoopLightData; public TileAndClusterData tileAndClusterData; - public TextureHandle depthTexture; - public TextureHandle contactShadowsTexture; + public TextureHandle depthTexture; + public TextureHandle contactShadowsTexture; public HDShadowManager shadowManager; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index 7a45d7d2502..d1c25ed0480 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -582,7 +582,8 @@ TextureHandle DownsampleDepthForLowResTransparency(RenderGraph renderGraph, HDCa class RenderLowResTransparentPassData { - public FrameSettings frameSettings; + public ConstantBuffer globalCB; + public FrameSettings frameSettings; public RendererListHandle rendererList; public TextureHandle lowResBuffer; public TextureHandle downsampledDepthBuffer; @@ -594,6 +595,7 @@ TextureHandle RenderLowResTransparent(RenderGraph renderGraph, HDCamera hdCamera { var passNames = m_Asset.currentPlatformRenderPipelineSettings.supportTransparentBackface ? m_AllTransparentPassNames : m_TransparentNoBackfaceNames; + passData.globalCB = m_ShaderVariablesGlobalCB; passData.frameSettings = hdCamera.frameSettings; passData.rendererList = builder.UseRendererList(renderGraph.CreateRendererList( CreateTransparentRendererListDesc(cullingResults, hdCamera.camera, passNames, m_CurrentRendererConfigurationBakedLighting, HDRenderQueue.k_RenderQueue_LowTransparent))); @@ -605,13 +607,13 @@ TextureHandle RenderLowResTransparent(RenderGraph renderGraph, HDCamera hdCamera builder.SetRenderFunc( (RenderLowResTransparentPassData data, RenderGraphContext context) => { - context.cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 1); - context.cmd.SetGlobalInt(HDShaderIDs._OffScreenDownsampleFactor, 2); + UpdateOffscreenRenderingConstants(data.globalCB, true, 2u); + data.globalCB.Commit(context.cmd, HDShaderIDs._ShaderVariablesGlobal); DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, context.resources.GetRendererList(data.rendererList)); - context.cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 0); - context.cmd.SetGlobalInt(HDShaderIDs._OffScreenDownsampleFactor, 1); + UpdateOffscreenRenderingConstants(data.globalCB, false, 1u); + data.globalCB.Commit(context.cmd, HDShaderIDs._ShaderVariablesGlobal); }); return passData.lowResBuffer; @@ -869,19 +871,6 @@ void GenerateColorPyramid(RenderGraph renderGraph, HDCamera hdCamera, TextureHan var colorPyramid = context.resources.GetTexture(data.colorPyramid); var inputTexture = context.resources.GetTexture(data.inputColor); data.hdCamera.colorPyramidHistoryMipCount = data.mipGenerator.RenderColorGaussianPyramid(context.cmd, pyramidSize, inputTexture, colorPyramid); - - // TODO : Replace that by _RTHandleScaleHistory in the shaders. Only missing part is lodCount - float scaleX = data.hdCamera.actualWidth / (float)colorPyramid.rt.width; - float scaleY = data.hdCamera.actualHeight / (float)colorPyramid.rt.height; - Vector4 pyramidScaleLod = new Vector4(scaleX, scaleY, data.hdCamera.colorPyramidHistoryMipCount, 0.0f); - // Warning! Danger! - // The color pyramid scale is only correct for the most detailed MIP level. - // For the other MIP levels, due to truncation after division by 2, a row or - // column of texels may be lost. Since this can happen to BOTH the texture - // size AND the viewport, (uv * _ColorPyramidScale.xy) can be off by a texel - // unless the scale is 1 (and it will not be 1 if the texture was resized - // and is of greater size compared to the viewport). - context.cmd.SetGlobalVector(HDShaderIDs._ColorPyramidScale, pyramidScaleLod); }); } @@ -896,13 +885,13 @@ class AccumulateDistortionPassData public TextureHandle distortionBuffer; public TextureHandle depthStencilBuffer; public RendererListHandle distortionRendererList; - public FrameSettings frameSettings; + public FrameSettings frameSettings; } TextureHandle AccumulateDistortion( RenderGraph renderGraph, - HDCamera hdCamera, + HDCamera hdCamera, TextureHandle depthStencilBuffer, - CullingResults cullResults) + CullingResults cullResults) { using (var builder = renderGraph.AddRenderPass("Accumulate Distortion", out var passData, ProfilingSampler.Get(HDProfileId.Distortion))) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 0be3edeb689..68f545e78aa 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -965,19 +965,15 @@ void Resize(HDCamera hdCamera) } } - void UpdateShaderVariablesGlobalCB(HDCamera hdCamera) + void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) { - /* - _ShadowFrustumPlanes - */ - hdCamera.UpdateShaderVariableGlobalCB(m_ShaderVariablesGlobalCB, m_FrameCount); Fog.UpdateShaderVariablesGlobalCB(m_ShaderVariablesGlobalCB, hdCamera); UpdateShaderVariablesGlobalSubsurface(m_ShaderVariablesGlobalCB, hdCamera); UpdateShaderVariablesGlobalDecal(m_ShaderVariablesGlobalCB, hdCamera); UpdateShaderVariablesGlobalVolumetrics(m_ShaderVariablesGlobalCB, RTHandles.rtHandleProperties, hdCamera); m_ShadowManager.UpdateShaderVariablesGlobalCB(m_ShaderVariablesGlobalCB); - + UpdateShaderVariablesGlobalLightLoop(m_ShaderVariablesGlobalCB, hdCamera); // Misc MicroShadowing microShadowingSettings = hdCamera.volumeStack.GetComponent(); @@ -991,27 +987,38 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera) m_ShaderVariablesGlobalCB.data._IndirectLightingMultiplier = new Vector4(hdCamera.volumeStack.GetComponent().indirectDiffuseIntensity.value, 0, 0, 0); m_ShaderVariablesGlobalCB.data._OffScreenRendering = 0; + m_ShaderVariablesGlobalCB.data._OffScreenDownsampleFactor = 1; m_ShaderVariablesGlobalCB.data._ReplaceDiffuseForIndirect = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ReplaceDiffuseForIndirect) ? 1.0f : 0.0f; m_ShaderVariablesGlobalCB.data._EnableSkyReflection = hdCamera.frameSettings.IsEnabled(FrameSettingsField.SkyReflection) ? 1u : 0u; m_ShaderVariablesGlobalCB.data._ContactShadowOpacity = m_ContactShadows.opacity.value; + int coarseStencilWidth = HDUtils.DivRoundUp(hdCamera.actualWidth, 8); + int coarseStencilHeight = HDUtils.DivRoundUp(hdCamera.actualHeight, 8); + m_ShaderVariablesGlobalCB.data._CoarseStencilBufferSize = new Vector4(coarseStencilWidth, coarseStencilHeight, 1.0f / coarseStencilWidth, 1.0f / coarseStencilHeight); + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) { m_ShaderVariablesGlobalCB.data._RaytracedIndirectDiffuse = ValidIndirectDiffuseState(hdCamera) ? 1 : 0; m_ShaderVariablesGlobalCB.data._RaytracingFrameIndex = RayTracingFrameIndex(hdCamera); + + var settings = hdCamera.volumeStack.GetComponent(); + bool usesRaytracedReflections = hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value; + m_ShaderVariablesGlobalCB.data._UseRayTracedReflections = usesRaytracedReflections ? 1 : 0; } + else + { + m_ShaderVariablesGlobalCB.data._RaytracedIndirectDiffuse = 0; + m_ShaderVariablesGlobalCB.data._RaytracingFrameIndex = RayTracingFrameIndex(hdCamera); + m_ShaderVariablesGlobalCB.data._UseRayTracedReflections = 0; + } + + m_ShaderVariablesGlobalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); } void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PushGlobalParameters))) { - UpdateShaderVariablesGlobalCB(hdCamera); - - - - - PushVolumetricLightingGlobalParams(hdCamera, cmd, m_FrameCount); // Set up UnityPerView CBuffer. @@ -1105,9 +1112,6 @@ static void BuildCoarseStencilAndResolveIfNeeded(BuildCoarseStencilAndResolvePar ComputeShader cs = parameters.resolveStencilCS; int kernel = SampleCountToPassIndex(MSAAEnabled ? hdCamera.msaaSamples : MSAASamples.None); kernel = resolveIsNecessary ? kernel + 3 : kernel; // We have a different variant if we need to resolve to non-MSAA stencil - int coarseStencilWidth = HDUtils.DivRoundUp(hdCamera.actualWidth, 8); - int coarseStencilHeight = HDUtils.DivRoundUp(hdCamera.actualHeight, 8); - cmd.SetGlobalVector(HDShaderIDs._CoarseStencilBufferSize, new Vector4(coarseStencilWidth, coarseStencilHeight, 1.0f / coarseStencilWidth, 1.0f / coarseStencilHeight)); cmd.SetComputeBufferParam(cs, kernel, HDShaderIDs._CoarseStencilBuffer, coarseStencilBuffer); cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._StencilTexture, depthStencilBuffer, 0, RenderTextureSubElement.Stencil); @@ -1116,6 +1120,8 @@ static void BuildCoarseStencilAndResolveIfNeeded(BuildCoarseStencilAndResolvePar cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._OutputStencilBuffer, resolvedStencilBuffer); } + int coarseStencilWidth = HDUtils.DivRoundUp(hdCamera.actualWidth, 8); + int coarseStencilHeight = HDUtils.DivRoundUp(hdCamera.actualHeight, 8); cmd.DispatchCompute(cs, kernel, coarseStencilWidth, coarseStencilHeight, hdCamera.viewCount); } } @@ -1129,7 +1135,6 @@ void ConfigureKeywords(bool enableBakeShadowMask, HDCamera hdCamera, CommandBuff m_currentDebugViewMaterialGBuffer = enableBakeShadowMask ? m_DebugViewMaterialGBufferShadowMask : m_DebugViewMaterialGBuffer; CoreUtils.SetKeyword(cmd, "LIGHT_LAYERS", hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers)); - cmd.SetGlobalInt(HDShaderIDs._EnableLightLayers, hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers) ? 1 : 0); // configure keyword for both decal.shader and material if (m_Asset.currentPlatformRenderPipelineSettings.supportDecals) @@ -1945,6 +1950,7 @@ AOVRequestData aovRequest // So the first thing to do is to go through all the light: PrepareLightsForGPU bool enableBakeShadowMask = PrepareLightsForGPU(cmd, hdCamera, cullingResults, hdProbeCullingResults, densityVolumes, m_CurrentDebugDisplaySettings, aovRequest); + UpdateShaderVariablesGlobalCB(hdCamera, cmd); // Let's bind as soon as possible the light data BindLightDataParameters(hdCamera, cmd); @@ -3672,15 +3678,17 @@ void RenderLowResTransparent(CullingResults cullResults, HDCamera hdCamera, Scri using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.LowResTransparent))) { - cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 1); - cmd.SetGlobalInt(HDShaderIDs._OffScreenDownsampleFactor, 2); + UpdateOffscreenRenderingConstants(m_ShaderVariablesGlobalCB, true, 2u); + m_ShaderVariablesGlobalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); + CoreUtils.SetRenderTarget(cmd, m_LowResTransparentBuffer, m_SharedRTManager.GetLowResDepthBuffer(), clearFlag: ClearFlag.Color, Color.black); RenderQueueRange transparentRange = HDRenderQueue.k_RenderQueue_LowTransparent; var passNames = m_Asset.currentPlatformRenderPipelineSettings.supportTransparentBackface ? m_AllTransparentPassNames : m_TransparentNoBackfaceNames; var rendererList = RendererList.Create(CreateTransparentRendererListDesc(cullResults, hdCamera.camera, passNames, m_CurrentRendererConfigurationBakedLighting, HDRenderQueue.k_RenderQueue_LowTransparent)); DrawTransparentRendererList(renderContext, cmd, hdCamera.frameSettings, rendererList); - cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 0); - cmd.SetGlobalInt(HDShaderIDs._OffScreenDownsampleFactor, 1); + + UpdateOffscreenRenderingConstants(m_ShaderVariablesGlobalCB, false, 1u); + m_ShaderVariablesGlobalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); } } @@ -3885,7 +3893,6 @@ void RenderSSR(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext ren hdCamera.colorPyramidHistoryIsValid = true; // For the next frame... } } - cmd.SetGlobalInt(HDShaderIDs._UseRayTracedReflections, usesRaytracedReflections ? 1 : 0); PushFullScreenDebugTexture(hdCamera, cmd, m_SsrLightingTexture, FullScreenDebugMode.ScreenSpaceReflections); } @@ -3951,10 +3958,6 @@ void RenderColorPyramid(HDCamera hdCamera, CommandBuffer cmd, bool isPreRefracti hdCamera.colorPyramidHistoryMipCount = lodCount; } - float scaleX = hdCamera.actualWidth / (float)currentColorPyramid.rt.width; - float scaleY = hdCamera.actualHeight / (float)currentColorPyramid.rt.height; - Vector4 pyramidScaleLod = new Vector4(scaleX, scaleY, lodCount, 0.0f); - Vector4 pyramidScale = new Vector4(scaleX, scaleY, 0f, 0f); // Warning! Danger! // The color pyramid scale is only correct for the most detailed MIP level. // For the other MIP levels, due to truncation after division by 2, a row or @@ -3963,8 +3966,7 @@ void RenderColorPyramid(HDCamera hdCamera, CommandBuffer cmd, bool isPreRefracti // unless the scale is 1 (and it will not be 1 if the texture was resized // and is of greater size compared to the viewport). cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, currentColorPyramid); - cmd.SetGlobalVector(HDShaderIDs._ColorPyramidScale, pyramidScaleLod); - PushFullScreenDebugTextureMip(hdCamera, cmd, currentColorPyramid, lodCount, pyramidScale, isPreRefraction ? FullScreenDebugMode.PreRefractionColorPyramid : FullScreenDebugMode.FinalColorPyramid); + PushFullScreenDebugTextureMip(hdCamera, cmd, currentColorPyramid, lodCount, isPreRefraction ? FullScreenDebugMode.PreRefractionColorPyramid : FullScreenDebugMode.FinalColorPyramid); } void GenerateDepthPyramid(HDCamera hdCamera, CommandBuffer cmd, FullScreenDebugMode debugMode) @@ -3978,13 +3980,8 @@ void GenerateDepthPyramid(HDCamera hdCamera, CommandBuffer cmd, FullScreenDebugM m_MipGenerator.RenderMinDepthPyramid(cmd, m_SharedRTManager.GetDepthTexture(), m_SharedRTManager.GetDepthBufferMipChainInfo()); } - float scaleX = hdCamera.actualWidth / (float)m_SharedRTManager.GetDepthTexture().rt.width; - float scaleY = hdCamera.actualHeight / (float)m_SharedRTManager.GetDepthTexture().rt.height; - Vector4 pyramidScaleLod = new Vector4(scaleX, scaleY, mipCount, 0.0f); - Vector4 pyramidScale = new Vector4(scaleX, scaleY, 0f, 0f); cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, m_SharedRTManager.GetDepthTexture()); - cmd.SetGlobalVector(HDShaderIDs._DepthPyramidScale, pyramidScaleLod); - PushFullScreenDebugTextureMip(hdCamera, cmd, m_SharedRTManager.GetDepthTexture(), mipCount, pyramidScale, debugMode); + PushFullScreenDebugTextureMip(hdCamera, cmd, m_SharedRTManager.GetDepthTexture(), mipCount, debugMode); } void DownsampleDepthForLowResTransparency(HDCamera hdCamera, CommandBuffer cmd) @@ -4148,14 +4145,14 @@ internal void PushFullScreenDebugTexture(HDCamera hdCamera, CommandBuffer cmd, R } } - void PushFullScreenDebugTextureMip(HDCamera hdCamera, CommandBuffer cmd, RTHandle texture, int lodCount, Vector4 scaleBias, FullScreenDebugMode debugMode) + void PushFullScreenDebugTextureMip(HDCamera hdCamera, CommandBuffer cmd, RTHandle texture, int lodCount, FullScreenDebugMode debugMode) { if (debugMode == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode) { var mipIndex = Mathf.FloorToInt(m_CurrentDebugDisplaySettings.data.fullscreenDebugMip * (lodCount)); m_FullScreenDebugPushed = true; // We need this flag because otherwise if no full screen debug is pushed (like for example if the corresponding pass is disabled), when we render the result in RenderDebug m_DebugFullScreenTempBuffer will contain potential garbage - HDUtils.BlitCameraTexture(cmd, texture, m_DebugFullScreenTempBuffer, scaleBias, mipIndex); + HDUtils.BlitCameraTexture(cmd, texture, m_DebugFullScreenTempBuffer, texture.rtHandleProperties.rtHandleScale, mipIndex); } } @@ -4433,6 +4430,8 @@ void ClearBuffers(HDCamera hdCamera, CommandBuffer cmd) struct PostProcessParameters { + public ConstantBuffer globalCB; + public HDCamera hdCamera; public bool postProcessIsFinalPass; public bool flipYInPostProcess; @@ -4450,6 +4449,7 @@ struct PostProcessParameters PostProcessParameters PreparePostProcess(CullingResults cullResults, HDCamera hdCamera) { PostProcessParameters result = new PostProcessParameters(); + result.globalCB = m_ShaderVariablesGlobalCB; result.hdCamera = hdCamera; result.postProcessIsFinalPass = HDUtils.PostProcessIsFinalPass(hdCamera); // Y-Flip needs to happen during the post process pass only if it's the final pass and is the regular game view @@ -4517,6 +4517,11 @@ RTHandle GetAfterPostProcessOffScreenBuffer() return m_GbufferManager.GetBuffer(0); } + static void UpdateOffscreenRenderingConstants(ConstantBuffer cb, bool enabled, uint factor) + { + cb.data._OffScreenRendering = enabled ? 1u : 0u; + cb.data._OffScreenDownsampleFactor = factor; + } static void RenderAfterPostProcess( PostProcessParameters parameters, in RendererList opaqueAfterPostProcessRendererList, @@ -4532,13 +4537,17 @@ static void RenderAfterPostProcess( PostProcessParameters parameters, // The issue is that the only available depth buffer is jittered so pixels would wobble around depth tested edges. // In order to avoid that we decide that objects rendered after Post processes while TAA is active will not benefit from the depth buffer so we disable it. parameters.hdCamera.UpdateAllViewConstants(false); - parameters.hdCamera.SetupGlobalParams(cmd, parameters.frameCount); + parameters.hdCamera.UpdateShaderVariableGlobalCB(parameters.globalCB, parameters.frameCount); + + UpdateOffscreenRenderingConstants(parameters.globalCB, true, 1); + parameters.globalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); - cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 1); DrawOpaqueRendererList(renderContext, cmd, parameters.hdCamera.frameSettings, opaqueAfterPostProcessRendererList); // Setup off-screen transparency here DrawTransparentRendererList(renderContext, cmd, parameters.hdCamera.frameSettings, transparentAfterPostProcessRendererList); - cmd.SetGlobalInt(HDShaderIDs._OffScreenRendering, 0); + + UpdateOffscreenRenderingConstants(parameters.globalCB, false, 1); + parameters.globalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index bdae4919c1b..8874336f173 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -380,6 +380,8 @@ static class HDShaderIDs Shader.PropertyToID("_DBufferTexture3") }; + public static readonly int _ShaderVariablesGlobal = Shader.PropertyToID("ShaderVariablesGlobal"); + public static readonly int _SSSBufferTexture = Shader.PropertyToID("_SSSBufferTexture"); public static readonly int _NormalBufferTexture = Shader.PropertyToID("_NormalBufferTexture"); @@ -409,9 +411,7 @@ static class HDShaderIDs public static readonly int _LightLayersTexture = Shader.PropertyToID("_LightLayersTexture"); public static readonly int _DistortionTexture = Shader.PropertyToID("_DistortionTexture"); public static readonly int _ColorPyramidTexture = Shader.PropertyToID("_ColorPyramidTexture"); - public static readonly int _ColorPyramidScale = Shader.PropertyToID("_ColorPyramidScale"); public static readonly int _ColorPyramidUvScaleAndLimitPrevFrame = Shader.PropertyToID("_ColorPyramidUvScaleAndLimitPrevFrame"); - public static readonly int _DepthPyramidScale = Shader.PropertyToID("_DepthPyramidScale"); public static readonly int _DebugColorPickerTexture = Shader.PropertyToID("_DebugColorPickerTexture"); public static readonly int _ColorPickerMode = Shader.PropertyToID("_ColorPickerMode"); @@ -522,8 +522,6 @@ static class HDShaderIDs public static readonly int _VolumeMaskDimensions = Shader.PropertyToID("_VolumeMaskDimensions"); public static readonly int _EnableLightLayers = Shader.PropertyToID("_EnableLightLayers"); - public static readonly int _OffScreenRendering = Shader.PropertyToID("_OffScreenRendering"); - public static readonly int _OffScreenDownsampleFactor = Shader.PropertyToID("_OffScreenDownsampleFactor"); public static readonly int _ReplaceDiffuseForIndirect = Shader.PropertyToID("_ReplaceDiffuseForIndirect"); public static readonly int _EnableSkyReflection = Shader.PropertyToID("_EnableSkyReflection"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/Distortion/ApplyDistortion.shader b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/Distortion/ApplyDistortion.shader index 6fd5921fd77..22c02ee8326 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/Distortion/ApplyDistortion.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/Distortion/ApplyDistortion.shader @@ -94,8 +94,8 @@ Shader "Hidden/HDRP/ApplyDistortion" // Get source pixel for distortion float2 distordedUV = float2(input.positionCS.xy + distortion * _FetchBias) * _Size.zw; - float mip = (_ColorPyramidScale.z - 1) * clamp(distortionBlur, 0.0, 1.0); - float4 sampled = SAMPLE_TEXTURE2D_X_LOD(_ColorPyramidTexture, s_trilinear_clamp_sampler, distordedUV * _ColorPyramidScale.xy, mip); + float mip = (_ColorPyramidLodCount - 1) * clamp(distortionBlur, 0.0, 1.0); + float4 sampled = SAMPLE_TEXTURE2D_X_LOD(_ColorPyramidTexture, s_trilinear_clamp_sampler, distordedUV * _RTHandleScaleHistory.xy, mip); return sampled; } @@ -110,7 +110,7 @@ Shader "Hidden/HDRP/ApplyDistortion" Stencil { WriteMask [_StencilMask] - ReadMask [_StencilMask] + ReadMask [_StencilMask] Ref [_StencilRef] Comp Equal Pass Zero // We can clear the bit since we won't need anymore. diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index c3d0ef28ee4..d4ad0d2abfe 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -134,7 +134,7 @@ unsafe struct ShaderVariablesGlobal [HLSLArray(s_MaxEnv2DLight * 3, typeof(float))] public fixed float _Env2DCaptureForward[s_MaxEnv2DLight * 3]; [HLSLArray(s_MaxEnv2DLight, typeof(Vector4))] - public fixed float _Env2DAtlasScaleOffset[s_MaxEnv2DLight * 3]; + public fixed float _Env2DAtlasScaleOffset[s_MaxEnv2DLight * 4]; public uint _DirectionalLightCount; public uint _PunctualLightCount; @@ -176,8 +176,7 @@ unsafe struct ShaderVariablesGlobal public int _RaytracedIndirectDiffuse; // Buffer pyramid - public Vector4 _ColorPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused - public Vector4 _DepthPyramidScale; // (x,y) = Screen Scale, z = lod count, w = unused + public float _ColorPyramidLodCount; // Ambient occlusion public Vector4 _AmbientOcclusionParam; // xyz occlusion color, w directLightStrenght diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 5f927d3598b..f17287d1e6e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -100,8 +100,7 @@ cbuffer ShaderVariablesGlobal uint _NumTileClusteredY; int _EnvSliceSize; int _RaytracedIndirectDiffuse; - float4 _ColorPyramidScale; - float4 _DepthPyramidScale; + float _ColorPyramidLodCount; float4 _AmbientOcclusionParam; float4 _IndirectLightingMultiplier; float _SSRefractionInvScreenWeightDistance; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs index 4e8852b73c0..7218d95c7c5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs @@ -797,15 +797,6 @@ public void UpdateEnvironment(HDCamera hdCamera, ScriptableRenderContext renderC var reflectionTexture = GetReflectionTexture(hdCamera.lightingSky); cmd.SetGlobalTexture(HDShaderIDs._SkyTexture, reflectionTexture); - - if (IsLightingSkyValid(hdCamera)) - { - cmd.SetGlobalInt(HDShaderIDs._EnvLightSkyEnabled, 1); - } - else - { - cmd.SetGlobalInt(HDShaderIDs._EnvLightSkyEnabled, 0); - } } internal void UpdateBuiltinParameters(SkyUpdateContext skyContext, HDCamera hdCamera, Light sunLight, RTHandle colorBuffer, RTHandle depthBuffer, DebugDisplaySettings debugSettings, int frameIndex, CommandBuffer cmd) From 8f7898472973aeaeede8b5a47265d5e87dab8ff6 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 6 Mar 2020 17:08:24 +0100 Subject: [PATCH 31/92] Fix null ref --- .../Lighting/VolumetricLighting/VolumetricLighting.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 532fd4dacfc..95f925278d7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -442,6 +442,11 @@ static float CornetteShanksPhasePartConstant(float anisotropy) void UpdateShaderVariablesGlobalVolumetrics(ConstantBuffer cb, in RTHandleProperties sharedRTHandleProperties, HDCamera hdCamera) { + if (!Fog.IsVolumetricFogEnabled(hdCamera)) + { + return; + } + var currFrameParams = hdCamera.vBufferParams[0]; Vector2Int sharedBufferSize = sharedRTHandleProperties.currentRenderTargetSize; From e5f1e0aa094bbe43f22d38fd63ca68dc9ad81b82 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Mon, 9 Mar 2020 17:45:13 +0100 Subject: [PATCH 32/92] Fixed global constant buffer alignment issues. --- .../ShaderGenerator/ShaderTypeGeneration.cs | 12 ++ .../ShaderGeneratorAttributes.cs | 6 + .../Lighting/AtmosphericScattering/Fog.cs | 10 +- .../Runtime/Lighting/LightLoop/LightLoop.cs | 16 +- .../Lighting/LightLoop/LightLoopDef.hlsl | 18 +- .../SubsurfaceScattering.hlsl | 2 +- .../SubsurfaceScatteringManager.cs | 2 +- .../ShaderLibrary/ShaderVariablesGlobal.cs | 166 +++++++++--------- .../ShaderVariablesGlobal.cs.hlsl | 42 +++-- 9 files changed, 148 insertions(+), 126 deletions(-) diff --git a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs index bab785441d3..3ace8f04abb 100644 --- a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs +++ b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs @@ -1021,6 +1021,16 @@ public bool Generate() var arrayInfos = (field.GetCustomAttributes(typeof(HLSLArray), false) as HLSLArray[]); if (arrayInfos.Length != 0) { + // For constant buffers, every element of the array needs to be aligned to a Vector4 + if (attr.generateCBuffer && + arrayInfos[0].elementType != typeof(Vector4) && + arrayInfos[0].elementType != typeof(ShaderGenUInt4) && + arrayInfos[0].elementType != typeof(Matrix4x4)) + { + Error("Invalid HLSLArray target: '" + field.FieldType + "'" + ", only Vector4 and ShaderGenUInt4 are supported for integer arrays in constant buffers."); + return false; + } + arraySize = arrayInfos[0].arraySize; fieldType = arrayInfos[0].elementType; } @@ -1177,6 +1187,8 @@ public bool Generate() EmitPrimitiveType(floatPrecision, 3, arraySize, field.Name, "", m_ShaderFields); else if (fieldType == typeof(Vector4)) EmitPrimitiveType(floatPrecision, 4, arraySize, field.Name, "", m_ShaderFields); + else if (fieldType == typeof(ShaderGenUInt4)) + EmitPrimitiveType(PrimitiveType.UInt, 4, arraySize, field.Name, "", m_ShaderFields); else if (fieldType == typeof(Matrix4x4)) EmitMatrixType(floatPrecision, 4, 4, arraySize, field.Name, "", m_ShaderFields); else if (!ExtractComplex(field, m_ShaderFields)) diff --git a/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs b/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs index 18ed9096130..d27b6f8c625 100644 --- a/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs +++ b/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs @@ -287,5 +287,11 @@ public PackingAttribute(string displayName = "", FieldPacking packingScheme = Fi } } + /// + /// This type needs to be used when generating unsigned integer arrays for constant buffers. + /// + public struct ShaderGenUInt4 + { + } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs index 7d97328d88a..0e753b41bfd 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs @@ -125,10 +125,13 @@ internal static void UpdateShaderVariablesGlobalCB(ConstantBuffer cb, HDCamera hdCamera) { + bool enableVolumetrics = enableVolumetricFog.value && hdCamera.frameSettings.IsEnabled(FrameSettingsField.Volumetrics); + cb.data._FogEnabled = 1; + cb.data._PBRFogEnabled = IsPBRFogEnabled(hdCamera) ? 1 : 0; + cb.data._EnableVolumetricFog = enableVolumetrics ? 1 : 0; cb.data._MaxFogDistance = maxFogDistance.value; - // Fog Color Color fogColor = (colorMode.value == FogColorMode.ConstantColor) ? color.value : tint.value; cb.data._FogColorMode = (float)colorMode.value; cb.data._FogColor = new Color(fogColor.r, fogColor.g, fogColor.b, 0.0f); @@ -151,12 +154,7 @@ void UpdateShaderVariablesGlobalCBFogParameters(ConstantBuffer env2DCaptureVP { get; private set; } - public List env2DCaptureForward { get; private set; } + public List env2DCaptureForward { get; private set; } public List env2DAtlasScaleOffset {get; private set; } = new List(); Material m_CubeToPanoMaterial; @@ -264,13 +264,11 @@ public void Initialize(HDRenderPipelineAsset hdrpAsset, RenderPipelineResources lightCookieManager = new LightCookieManager(hdrpAsset, k_MaxCacheSize); env2DCaptureVP = new List(); - env2DCaptureForward = new List(); + env2DCaptureForward = new List(); for (int i = 0, c = Mathf.Max(1, lightLoopSettings.maxPlanarReflectionOnScreen); i < c; ++i) { env2DCaptureVP.Add(Matrix4x4.identity); - env2DCaptureForward.Add(0); - env2DCaptureForward.Add(0); - env2DCaptureForward.Add(0); + env2DCaptureForward.Add(Vector4.zero); env2DAtlasScaleOffset.Add(Vector4.zero); } @@ -1754,9 +1752,7 @@ internal bool GetEnvLightData(CommandBuffer cmd, HDCamera hdCamera, in Processed var capturedForwardWS = renderData.captureRotation * Vector3.forward; //capturedForwardWS.z *= -1; // Transform to RHS standard - m_TextureCaches.env2DCaptureForward[fetchIndex * 3 + 0] = capturedForwardWS.x; - m_TextureCaches.env2DCaptureForward[fetchIndex * 3 + 1] = capturedForwardWS.y; - m_TextureCaches.env2DCaptureForward[fetchIndex * 3 + 2] = capturedForwardWS.z; + m_TextureCaches.env2DCaptureForward[fetchIndex] = new Vector4(capturedForwardWS.x, capturedForwardWS.y, capturedForwardWS.z, 0.0f); break; } case HDAdditionalReflectionData _: @@ -3248,8 +3244,8 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ConstantBuffer 1) ? 0.0 : 1.0; #endif - float3 capturedForwardWS = float3( - _Env2DCaptureForward[index * 3 + 0], - _Env2DCaptureForward[index * 3 + 1], - _Env2DCaptureForward[index * 3 + 2] - ); + float3 capturedForwardWS = _Env2DCaptureForward[index].xyz; if (dot(capturedForwardWS, texCoord) < 0.0) color.a = 0.0; } @@ -266,7 +262,7 @@ bool IsFastPath(uint lightStart, out uint lightStartLane0) #if SCALARIZE_LIGHT_LOOP // Fast path is when we all pixels in a wave are accessing same tile or cluster. lightStartLane0 = WaveReadLaneFirst(lightStart); - return WaveActiveAllTrue(lightStart == lightStartLane0); + return WaveActiveAllTrue(lightStart == lightStartLane0); #else lightStartLane0 = lightStart; return false; @@ -282,7 +278,7 @@ uint ScalarizeElementIndex(uint v_elementIdx, bool fastPath) #if SCALARIZE_LIGHT_LOOP if (!fastPath) { - // If we are not in fast path, v_elementIdx is not scalar, so we need to query the Min value across the wave. + // If we are not in fast path, v_elementIdx is not scalar, so we need to query the Min value across the wave. s_elementIdx = WaveActiveMin(v_elementIdx); // If WaveActiveMin returns 0xffffffff it means that all lanes are actually dead, so we can safely ignore the loop and move forward. // This could happen as an helper lane could reach this point, hence having a valid v_elementIdx, but their values will be ignored by the WaveActiveMin @@ -338,7 +334,7 @@ EnvLightData FetchEnvLight(uint index) void UnpackContactShadowData(uint contactShadowData, out float fade, out uint mask) { fade = float(contactShadowData >> 24) / 255.0; - mask = contactShadowData & 0xFFFFFF; // store only the first 24 bits which represent + mask = contactShadowData & 0xFFFFFF; // store only the first 24 bits which represent } uint PackContactShadowData(float fade, uint mask) @@ -382,5 +378,5 @@ float GetScreenSpaceShadow(PositionInputs posInput, uint shadowIndex) float3 GetScreenSpaceColorShadow(PositionInputs posInput, int shadowIndex) { float4 res = LOAD_TEXTURE2D_ARRAY(_ScreenSpaceShadowsTexture, posInput.positionSS, INDEX_TEXTURE2D_ARRAY_X(shadowIndex & SCREEN_SPACE_SHADOW_INDEX_MASK)); - return (SCREEN_SPACE_COLOR_SHADOW_FLAG & shadowIndex) ? res.xyz : res.xxx; + return (SCREEN_SPACE_COLOR_SHADOW_FLAG & shadowIndex) ? res.xyz : res.xxx; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl index cff46fed307..33452629640 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl @@ -231,7 +231,7 @@ uint FindDiffusionProfileIndex(uint diffusionProfileHash) // Fetch the 4 bit index number by looking for the diffusion profile unique ID: for (i = 0; i < _DiffusionProfileCount; i++) { - if (_DiffusionProfileHashTable[i] == diffusionProfileHash) + if (_DiffusionProfileHashTable[i].x == diffusionProfileHash) { diffusionProfileIndex = i; break; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index dd909631af4..5dd11a141a4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -212,7 +212,7 @@ unsafe void UpdateShaderVariablesGlobalSubsurface(ConstantBuffer Don't move a float parameter away from where it belongs for filling a hole. Add padding in this case. [GenerateHLSL(needAccessors = false, generateCBuffer = true)] unsafe struct ShaderVariablesGlobal { @@ -94,33 +101,30 @@ unsafe struct ShaderVariablesGlobal public Vector4 _TimeParameters; // { t, sin(t), cos(t) } public Vector4 _LastTimeParameters; // { t, sin(t), cos(t) } - // Volumetric lighting. - public Vector4 _FogColor; // color in rgb - public Vector4 _MipFogParameters; - public Vector3 _HeightFogBaseScattering; - public float _HeightFogBaseExtinction; - public int _FogEnabled; - public int _PBRFogEnabled; - public float _MaxFogDistance; - public float _FogColorMode; - public Vector2 _HeightFogExponents; // { 1/H, H } - public float _HeightFogBaseHeight; - public float _GlobalFogAnisotropy; - - public Vector4 _VBufferViewportSize; // { w, h, 1/w, 1/h } - - public uint _VBufferSliceCount; - public float _VBufferRcpSliceCount; - public float _VBufferRcpInstancedViewCount; // Used to remap VBuffer coordinates for XR - public float _ContactShadowOpacity; - - public Vector4 _VBufferSharedUvScaleAndLimit; // Necessary us to work with sub-allocation (resource aliasing) in the RTHandle system - - public Vector4 _VBufferDistanceEncodingParams; // See the call site for description - public Vector4 _VBufferDistanceDecodingParams; // See the call site for description - - public float _VBufferLastSliceDist; // The distance to the middle of the last slice - public int _EnableVolumetricFog; // bool... + // Volumetric lighting / Fog. + public int _FogEnabled; + public int _PBRFogEnabled; + public int _EnableVolumetricFog; + public float _MaxFogDistance; + public Vector4 _FogColor; // color in rgb + public float _FogColorMode; + public Vector3 _Pad2; + public Vector4 _MipFogParameters; + public Vector3 _HeightFogBaseScattering; + public float _HeightFogBaseExtinction; + public Vector2 _HeightFogExponents; // { 1/H, H } + public float _HeightFogBaseHeight; + public float _GlobalFogAnisotropy; + + // VBuffer + public Vector4 _VBufferViewportSize; // { w, h, 1/w, 1/h } + public Vector4 _VBufferSharedUvScaleAndLimit; // Necessary us to work with sub-allocation (resource aliasing) in the RTHandle system + public Vector4 _VBufferDistanceEncodingParams; // See the call site for description + public Vector4 _VBufferDistanceDecodingParams; // See the call site for description + public uint _VBufferSliceCount; + public float _VBufferRcpSliceCount; + public float _VBufferRcpInstancedViewCount; // Used to remap VBuffer coordinates for XR + public float _VBufferLastSliceDist; // The distance to the middle of the last slice // Light Loop public const int s_MaxEnv2DLight = 32; @@ -131,60 +135,58 @@ unsafe struct ShaderVariablesGlobal [HLSLArray(s_MaxEnv2DLight, typeof(Matrix4x4))] public fixed float _Env2DCaptureVP[s_MaxEnv2DLight * 4 * 4]; - [HLSLArray(s_MaxEnv2DLight * 3, typeof(float))] - public fixed float _Env2DCaptureForward[s_MaxEnv2DLight * 3]; + [HLSLArray(s_MaxEnv2DLight, typeof(Vector4))] + public fixed float _Env2DCaptureForward[s_MaxEnv2DLight * 4]; [HLSLArray(s_MaxEnv2DLight, typeof(Vector4))] public fixed float _Env2DAtlasScaleOffset[s_MaxEnv2DLight * 4]; - public uint _DirectionalLightCount; - public uint _PunctualLightCount; - public uint _AreaLightCount; - public uint _EnvLightCount; - - public int _EnvLightSkyEnabled; // TODO: make it a bool - public uint _CascadeShadowCount; - public int _DirectionalShadowIndex; - public uint _EnableLightLayers; - - public float _ReplaceDiffuseForIndirect; - public uint _EnableSkyReflection; - public uint _EnableSSRefraction; - public float _MicroShadowOpacity; + public uint _DirectionalLightCount; + public uint _PunctualLightCount; + public uint _AreaLightCount; + public uint _EnvLightCount; - public float _DirectionalTransmissionMultiplier; + public int _EnvLightSkyEnabled; + public uint _CascadeShadowCount; + public int _DirectionalShadowIndex; + public uint _EnableLightLayers; - public Vector4 _CookieAtlasSize; - public Vector4 _CookieAtlasData; - public Vector4 _PlanarAtlasData; + public float _ReplaceDiffuseForIndirect; + public uint _EnableSkyReflection; + public uint _EnableSSRefraction; + public float _MicroShadowOpacity; - // Tile/Cluster - public uint _NumTileFtplX; - public uint _NumTileFtplY; - public float g_fClustScale; - public float g_fClustBase; - - public float g_fNearPlane; - public float g_fFarPlane; - public int g_iLog2NumClusters; // We need to always define these to keep constant buffer layouts compatible - public uint g_isLogBaseBufferEnabled; + public float _DirectionalTransmissionMultiplier; + public float _ProbeExposureScale; + public float _ContactShadowOpacity; + public float _ColorPyramidLodCount; - public uint _NumTileClusteredX; - public uint _NumTileClusteredY; - public int _EnvSliceSize; + public Vector4 _AmbientOcclusionParam; // xyz occlusion color, w directLightStrenght + public Vector4 _IndirectLightingMultiplier; // .x indirect diffuse multiplier (use with indirect lighting volume controler) - // Uniform variables that defines if we should be using the raytraced indirect diffuse - public int _RaytracedIndirectDiffuse; + public float _SSRefractionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback + public float _Pad3; + public float _Pad4; + public float _Pad5; - // Buffer pyramid - public float _ColorPyramidLodCount; + public Vector4 _CookieAtlasSize; + public Vector4 _CookieAtlasData; + public Vector4 _PlanarAtlasData; - // Ambient occlusion - public Vector4 _AmbientOcclusionParam; // xyz occlusion color, w directLightStrenght + // Tile/Cluster + public uint _NumTileFtplX; + public uint _NumTileFtplY; + public float g_fClustScale; + public float g_fClustBase; - public Vector4 _IndirectLightingMultiplier; // .x indirect diffuse multiplier (use with indirect lighting volume controler) + public float g_fNearPlane; + public float g_fFarPlane; + public int g_iLog2NumClusters; // We need to always define these to keep constant buffer layouts compatible + public uint g_isLogBaseBufferEnabled; - // Screen space refraction - public float _SSRefractionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback + public uint _NumTileClusteredX; + public uint _NumTileClusteredY; + public int _EnvSliceSize; + public float _Pad6; // Subsurface scattering // Use float4 to avoid any packing issue between compute and pixel shaders @@ -196,8 +198,12 @@ unsafe struct ShaderVariablesGlobal public fixed float _TransmissionTintsAndFresnel0[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // RGB = 1/4 * color, A = fresnel0 [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(Vector4))] public fixed float _WorldScales[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // X = meters per world unit; Y = world units per meter - [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(uint))] - public fixed uint _DiffusionProfileHashTable[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT]; // TODO: constant + + // Because of constant buffer limitation, arrays can only hold 4 components elements (otherwise we get alignment issues) + // We could pack the 16 values inside 4 uint4 but then the generated code is inefficient and generates a lots of swizzle operations instead of a single load. + // That's why we have 16 uint and only use the first component of each element. + [HLSLArray(DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT, typeof(ShaderGenUInt4))] + public fixed uint _DiffusionProfileHashTable[DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT * 4]; // TODO: constant public uint _EnableSubsurfaceScattering; // Globally toggles subsurface and transmission scattering on/off public uint _TexturingModeFlags; // 1 bit/profile; 0 = PreAndPostScatter, 1 = PostScatter @@ -205,19 +211,21 @@ unsafe struct ShaderVariablesGlobal public uint _DiffusionProfileCount; // Decals - public Vector2 _DecalAtlasResolution; - public uint _EnableDecals; - public uint _DecalCount; + public Vector2 _DecalAtlasResolution; + public uint _EnableDecals; + public uint _DecalCount; public uint _OffScreenRendering; public uint _OffScreenDownsampleFactor; public uint _XRViewCount; - public int _FrameCount; - - public float _ProbeExposureScale; - public int _UseRayTracedReflections; - public int _RaytracingFrameIndex; + public int _FrameCount; public Vector4 _CoarseStencilBufferSize; + + // Uniform variables that defines if we should be using the raytraced indirect diffuse + public int _RaytracedIndirectDiffuse; + public int _UseRayTracedReflections; + public int _RaytracingFrameIndex; + public float _Pad7; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index f17287d1e6e..074401ea57d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -45,32 +45,32 @@ cbuffer ShaderVariablesGlobal float4 unity_DeltaTime; float4 _TimeParameters; float4 _LastTimeParameters; - float4 _FogColor; - float4 _MipFogParameters; - float3 _HeightFogBaseScattering; - float _HeightFogBaseExtinction; int _FogEnabled; int _PBRFogEnabled; + int _EnableVolumetricFog; float _MaxFogDistance; + float4 _FogColor; float _FogColorMode; + float3 _Pad2; + float4 _MipFogParameters; + float3 _HeightFogBaseScattering; + float _HeightFogBaseExtinction; float2 _HeightFogExponents; float _HeightFogBaseHeight; float _GlobalFogAnisotropy; float4 _VBufferViewportSize; - uint _VBufferSliceCount; - float _VBufferRcpSliceCount; - float _VBufferRcpInstancedViewCount; - float _ContactShadowOpacity; float4 _VBufferSharedUvScaleAndLimit; float4 _VBufferDistanceEncodingParams; float4 _VBufferDistanceDecodingParams; + uint _VBufferSliceCount; + float _VBufferRcpSliceCount; + float _VBufferRcpInstancedViewCount; float _VBufferLastSliceDist; - int _EnableVolumetricFog; float4 _ShadowAtlasSize; float4 _CascadeShadowAtlasSize; float4 _AreaShadowAtlasSize; float4x4 _Env2DCaptureVP[32]; - float _Env2DCaptureForward[96]; + float4 _Env2DCaptureForward[32]; float4 _Env2DAtlasScaleOffset[32]; uint _DirectionalLightCount; uint _PunctualLightCount; @@ -85,6 +85,15 @@ cbuffer ShaderVariablesGlobal uint _EnableSSRefraction; float _MicroShadowOpacity; float _DirectionalTransmissionMultiplier; + float _ProbeExposureScale; + float _ContactShadowOpacity; + float _ColorPyramidLodCount; + float4 _AmbientOcclusionParam; + float4 _IndirectLightingMultiplier; + float _SSRefractionInvScreenWeightDistance; + float _Pad3; + float _Pad4; + float _Pad5; float4 _CookieAtlasSize; float4 _CookieAtlasData; float4 _PlanarAtlasData; @@ -99,16 +108,12 @@ cbuffer ShaderVariablesGlobal uint _NumTileClusteredX; uint _NumTileClusteredY; int _EnvSliceSize; - int _RaytracedIndirectDiffuse; - float _ColorPyramidLodCount; - float4 _AmbientOcclusionParam; - float4 _IndirectLightingMultiplier; - float _SSRefractionInvScreenWeightDistance; + float _Pad6; float4 _ThicknessRemaps[16]; float4 _ShapeParams[16]; float4 _TransmissionTintsAndFresnel0[16]; float4 _WorldScales[16]; - uint _DiffusionProfileHashTable[16]; + uint4 _DiffusionProfileHashTable[16]; uint _EnableSubsurfaceScattering; uint _TexturingModeFlags; uint _TransmissionFlags; @@ -120,10 +125,11 @@ cbuffer ShaderVariablesGlobal uint _OffScreenDownsampleFactor; uint _XRViewCount; int _FrameCount; - float _ProbeExposureScale; + float4 _CoarseStencilBufferSize; + int _RaytracedIndirectDiffuse; int _UseRayTracedReflections; int _RaytracingFrameIndex; - float4 _CoarseStencilBufferSize; + float _Pad7; }; From 3e83e64bc3613c438dbfd37c58d89bc905b2e9f0 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 10 Mar 2020 14:06:07 +0100 Subject: [PATCH 33/92] Fixed shadows and SSS --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 4 +- .../Runtime/Lighting/Shadow/HDShadowAtlas.cs | 38 +++++++------ .../Shadow/HDShadowManager.RenderGraph.cs | 12 ++-- .../Lighting/Shadow/HDShadowManager.cs | 8 +-- .../SubsurfaceScattering.hlsl | 2 +- .../SubsurfaceScatteringManager.cs | 22 -------- .../HDRenderPipeline.LightLoop.cs | 13 +++-- .../RenderPipeline/HDRenderPipeline.cs | 5 +- .../RenderPipeline/HDStringConstants.cs | 55 ++++++++----------- 9 files changed, 68 insertions(+), 91 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index addba4db500..eb2815ed18b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3336,10 +3336,10 @@ static void PushLightLoopGlobalParams(in LightLoopGlobalParameters param, Comman } - void RenderShadowMaps(ScriptableRenderContext renderContext, CommandBuffer cmd, CullingResults cullResults, HDCamera hdCamera) + void RenderShadowMaps(ScriptableRenderContext renderContext, CommandBuffer cmd, ConstantBuffer globalCB, CullingResults cullResults, HDCamera hdCamera) { // kick off the shadow jobs here - m_ShadowManager.RenderShadows(renderContext, cmd, cullResults, hdCamera); + m_ShadowManager.RenderShadows(renderContext, cmd, globalCB, cullResults, hdCamera); // Bind the shadow data var globalParams = PrepareShadowGlobalParameters(hdCamera); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs index 2bbb3121574..0df0a106d6c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs @@ -439,7 +439,7 @@ void LayoutResize() atlasShapeID++; } - public void RenderShadows(CullingResults cullResults, FrameSettings frameSettings, ScriptableRenderContext renderContext, CommandBuffer cmd) + public void RenderShadows(CullingResults cullResults, ConstantBuffer globalCB, FrameSettings frameSettings, ScriptableRenderContext renderContext, CommandBuffer cmd) { if (m_ShadowRequests.Count == 0) return; @@ -447,7 +447,7 @@ public void RenderShadows(CullingResults cullResults, FrameSettings frameSetting ShadowDrawingSettings shadowDrawSettings = new ShadowDrawingSettings(cullResults, 0); shadowDrawSettings.useRenderingLayerMaskTest = frameSettings.IsEnabled(FrameSettingsField.LightLayers); - var parameters = PrepareRenderShadowsParameters(); + var parameters = PrepareRenderShadowsParameters(globalCB); RenderShadows(parameters, m_Atlas, shadowDrawSettings, renderContext, cmd); if (parameters.blurAlgorithm == BlurAlgorithm.IM) @@ -462,23 +462,25 @@ public void RenderShadows(CullingResults cullResults, FrameSettings frameSetting struct RenderShadowsParameters { - public List shadowRequests; - public Material clearMaterial; - public bool debugClearAtlas; - public int atlasShaderID; - public BlurAlgorithm blurAlgorithm; + public ConstantBuffer globalCB; + public List shadowRequests; + public Material clearMaterial; + public bool debugClearAtlas; + public int atlasShaderID; + public BlurAlgorithm blurAlgorithm; // EVSM - public ComputeShader evsmShadowBlurMomentsCS; - public int momentAtlasShaderID; + public ComputeShader evsmShadowBlurMomentsCS; + public int momentAtlasShaderID; // IM - public ComputeShader imShadowBlurMomentsCS; + public ComputeShader imShadowBlurMomentsCS; } - RenderShadowsParameters PrepareRenderShadowsParameters() + RenderShadowsParameters PrepareRenderShadowsParameters(ConstantBuffer globalCB) { var parameters = new RenderShadowsParameters(); + parameters.globalCB = globalCB; parameters.shadowRequests = m_ShadowRequests; parameters.clearMaterial = m_ClearMaterial; parameters.debugClearAtlas = m_LightingDebugSettings.clearShadowAtlas; @@ -523,12 +525,14 @@ static void RenderShadows( RenderShadowsParameters parameters, // Setup matrices for shadow rendering: Matrix4x4 viewProjection = shadowRequest.deviceProjectionYFlip * shadowRequest.view; - cmd.SetGlobalMatrix(HDShaderIDs._ViewMatrix, shadowRequest.view); - cmd.SetGlobalMatrix(HDShaderIDs._InvViewMatrix, shadowRequest.view.inverse); - cmd.SetGlobalMatrix(HDShaderIDs._ProjMatrix, shadowRequest.deviceProjectionYFlip); - cmd.SetGlobalMatrix(HDShaderIDs._InvProjMatrix, shadowRequest.deviceProjectionYFlip.inverse); - cmd.SetGlobalMatrix(HDShaderIDs._ViewProjMatrix, viewProjection); - cmd.SetGlobalMatrix(HDShaderIDs._InvViewProjMatrix, viewProjection.inverse); + parameters.globalCB.data._ViewMatrix = shadowRequest.view; + parameters.globalCB.data._InvViewMatrix = shadowRequest.view.inverse; + parameters.globalCB.data._ProjMatrix = shadowRequest.deviceProjectionYFlip; + parameters.globalCB.data._InvProjMatrix = shadowRequest.deviceProjectionYFlip.inverse; + parameters.globalCB.data._ViewProjMatrix = viewProjection; + parameters.globalCB.data._InvViewProjMatrix = viewProjection.inverse; + parameters.globalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); + cmd.SetGlobalVectorArray(HDShaderIDs._ShadowClipPlanes, shadowRequest.frustumPlanes); // TODO: remove this execute when DrawShadows will use a CommandBuffer diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs index e007e65f05f..1694d44ddb0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs @@ -26,16 +26,16 @@ internal static ShadowResult ReadShadowResult(ShadowResult shadowResult, RenderG return result; } - internal ShadowResult RenderShadows(RenderGraph renderGraph, HDCamera hdCamera, CullingResults cullResults) + internal ShadowResult RenderShadows(RenderGraph renderGraph, ConstantBuffer globalCB, HDCamera hdCamera, CullingResults cullResults) { var result = new ShadowResult(); // Avoid to do any commands if there is no shadow to draw if (m_ShadowRequestCount == 0) return result; - result.punctualShadowResult = m_Atlas.RenderShadows(renderGraph, cullResults, hdCamera.frameSettings, "Punctual Lights Shadows rendering"); - result.directionalShadowResult = m_CascadeAtlas.RenderShadows(renderGraph, cullResults, hdCamera.frameSettings, "Directional Light Shadows rendering"); - result.areaShadowResult = m_AreaLightShadowAtlas.RenderShadows(renderGraph, cullResults, hdCamera.frameSettings, "Area Light Shadows rendering"); + result.punctualShadowResult = m_Atlas.RenderShadows(renderGraph, cullResults, globalCB, hdCamera.frameSettings, "Punctual Lights Shadows rendering"); + result.directionalShadowResult = m_CascadeAtlas.RenderShadows(renderGraph, cullResults, globalCB, hdCamera.frameSettings, "Directional Light Shadows rendering"); + result.areaShadowResult = m_AreaLightShadowAtlas.RenderShadows(renderGraph, cullResults, globalCB, hdCamera.frameSettings, "Area Light Shadows rendering"); return result; } @@ -61,7 +61,7 @@ TextureHandle AllocateMomentAtlas(RenderGraph renderGraph, string name, int shad { colorFormat = GraphicsFormat.R32G32_SFloat, useMipMap = true, autoGenerateMips = false, name = name, enableRandomWrite = true }, shaderID); } - internal TextureHandle RenderShadows(RenderGraph renderGraph, CullingResults cullResults, FrameSettings frameSettings, string shadowPassName) + internal TextureHandle RenderShadows(RenderGraph renderGraph, CullingResults cullResults, ConstantBuffer globalCB, FrameSettings frameSettings, string shadowPassName) { TextureHandle result = new TextureHandle(); @@ -70,7 +70,7 @@ internal TextureHandle RenderShadows(RenderGraph renderGraph, CullingResults cul using (var builder = renderGraph.AddRenderPass(shadowPassName, out var passData, ProfilingSampler.Get(HDProfileId.RenderShadowMaps))) { - passData.parameters = PrepareRenderShadowsParameters(); + passData.parameters = PrepareRenderShadowsParameters(globalCB); // TODO: Get rid of this and refactor to use the same kind of API than RendererList passData.shadowDrawSettings = new ShadowDrawingSettings(cullResults, 0); passData.shadowDrawSettings.useRenderingLayerMaskTest = frameSettings.IsEnabled(FrameSettingsField.LightLayers); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs index 4afbe0458db..425e7f9139d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs @@ -685,7 +685,7 @@ unsafe public void PrepareGPUShadowDatas(CullingResults cullResults, HDCamera ca m_DirectionalShadowData.cascadeDirection.w = camera.volumeStack.GetComponent().cascadeShadowSplitCount.value; } - public void RenderShadows(ScriptableRenderContext renderContext, CommandBuffer cmd, CullingResults cullResults, HDCamera hdCamera) + public void RenderShadows(ScriptableRenderContext renderContext, CommandBuffer cmd, ConstantBuffer globalCB, CullingResults cullResults, HDCamera hdCamera) { // Avoid to do any commands if there is no shadow to draw if (m_ShadowRequestCount == 0) @@ -694,18 +694,18 @@ public void RenderShadows(ScriptableRenderContext renderContext, CommandBuffer c // Clear atlas render targets and draw shadows using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderPunctualShadowMaps))) { - m_Atlas.RenderShadows(cullResults, hdCamera.frameSettings, renderContext, cmd); + m_Atlas.RenderShadows(cullResults, globalCB, hdCamera.frameSettings, renderContext, cmd); } using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderDirectionalShadowMaps))) { - m_CascadeAtlas.RenderShadows(cullResults, hdCamera.frameSettings, renderContext, cmd); + m_CascadeAtlas.RenderShadows(cullResults, globalCB, hdCamera.frameSettings, renderContext, cmd); } using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderAreaShadowMaps))) { if (ShaderConfig.s_AreaLights == 1) - m_AreaLightShadowAtlas.RenderShadows(cullResults, hdCamera.frameSettings, renderContext, cmd); + m_AreaLightShadowAtlas.RenderShadows(cullResults, globalCB, hdCamera.frameSettings, renderContext, cmd); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl index 33452629640..8c320fe3c13 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.hlsl @@ -22,7 +22,7 @@ uint GetSubsurfaceScatteringTexturingMode(int diffusionProfile) if (enableSss) { - bool performPostScatterTexturing = IsBitSet(asuint(_TexturingModeFlags), diffusionProfile); + bool performPostScatterTexturing = IsBitSet(_TexturingModeFlags, diffusionProfile); if (performPostScatterTexturing) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index 5dd11a141a4..f6fe58404c3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -234,14 +234,10 @@ struct SubsurfaceScatteringParameters public bool needTemporaryBuffer; public Material copyStencilForSplitLighting; public Material combineLighting; - public uint texturingModeFlags; public int numTilesX; public int numTilesY; public int numTilesZ; - public Vector4[] worldScales; public Vector4[] filterKernels; - public Vector4[] shapeParams; - //public float[] diffusionProfileHashes; public ComputeBuffer coarseStencilBuffer; } @@ -267,16 +263,10 @@ SubsurfaceScatteringParameters PrepareSubsurfaceScatteringParameters(HDCamera hd parameters.needTemporaryBuffer = NeedTemporarySubsurfaceBuffer() || hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); parameters.copyStencilForSplitLighting = m_SSSCopyStencilForSplitLighting; parameters.combineLighting = m_CombineLightingPass; - parameters.texturingModeFlags = m_SSSTexturingModeFlags; parameters.numTilesX = ((int)hdCamera.screenSize.x + 15) / 16; parameters.numTilesY = ((int)hdCamera.screenSize.y + 15) / 16; parameters.numTilesZ = hdCamera.viewCount; - - parameters.worldScales = m_SSSWorldScales; parameters.filterKernels = m_SSSFilterKernels; - parameters.shapeParams = m_SSSShapeParams; - //parameters.diffusionProfileHashes = m_SSSDiffusionProfileHashes; - parameters.coarseStencilBuffer = m_SharedRTManager.GetCoarseStencilBuffer(); return parameters; @@ -450,19 +440,7 @@ void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle c // However, the compute can't output and MSAA target so we blend the non-MSAA target into the MSAA one. static void RenderSubsurfaceScattering(in SubsurfaceScatteringParameters parameters, in SubsurfaceScatteringResources resources, CommandBuffer cmd) { - unsafe - { - // Warning: Unity is not able to losslessly transfer integers larger than 2^24 to the shader system. - // Therefore, we bitcast uint to float in C#, and bitcast back to uint in the shader. - uint textureingModeFlags = parameters.texturingModeFlags; - cmd.SetComputeFloatParam(parameters.subsurfaceScatteringCS, HDShaderIDs._TexturingModeFlags, *(float*)&textureingModeFlags); - } - - cmd.SetComputeVectorArrayParam(parameters.subsurfaceScatteringCS, HDShaderIDs._WorldScales, parameters.worldScales); cmd.SetComputeVectorArrayParam(parameters.subsurfaceScatteringCS, HDShaderIDs._FilterKernels, parameters.filterKernels); - cmd.SetComputeVectorArrayParam(parameters.subsurfaceScatteringCS, HDShaderIDs._ShapeParams, parameters.shapeParams); - //cmd.SetComputeFloatParams(parameters.subsurfaceScatteringCS, HDShaderIDs._DiffusionProfileHashTable, parameters.diffusionProfileHashes); - cmd.SetComputeTextureParam(parameters.subsurfaceScatteringCS, parameters.subsurfaceScatteringCSKernel, HDShaderIDs._DepthTexture, resources.depthTexture); cmd.SetComputeTextureParam(parameters.subsurfaceScatteringCS, parameters.subsurfaceScatteringCSKernel, HDShaderIDs._IrradianceSource, resources.diffuseBuffer); cmd.SetComputeTextureParam(parameters.subsurfaceScatteringCS, parameters.subsurfaceScatteringCSKernel, HDShaderIDs._SSSBufferTexture, resources.sssBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 188fb48f113..f0fadd48a8d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -93,8 +93,9 @@ void BuildGPULightList(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle class PushGlobalCameraParamPassData { - public HDCamera hdCamera; - public int frameCount; + public HDCamera hdCamera; + public int frameCount; + public ConstantBuffer globalCB; } @@ -104,20 +105,22 @@ void PushGlobalCameraParams(RenderGraph renderGraph, HDCamera hdCamera) { passData.hdCamera = hdCamera; passData.frameCount = m_FrameCount; + passData.globalCB = m_ShaderVariablesGlobalCB; builder.SetRenderFunc( (PushGlobalCameraParamPassData data, RenderGraphContext context) => { + data.hdCamera.UpdateShaderVariableGlobalCB(data.globalCB, data.frameCount); data.hdCamera.SetupGlobalParams(context.cmd, data.frameCount); + data.globalCB.Commit(context.cmd, HDShaderIDs._ShaderVariablesGlobal); }); } } internal ShadowResult RenderShadows(RenderGraph renderGraph, HDCamera hdCamera, CullingResults cullResults) { - var result = m_ShadowManager.RenderShadows(m_RenderGraph, hdCamera, cullResults); - - // TODO: Remove this once shadows don't pollute global parameters anymore. + var result = m_ShadowManager.RenderShadows(m_RenderGraph, m_ShaderVariablesGlobalCB, hdCamera, cullResults); + // Need to restore global camera parameters. PushGlobalCameraParams(renderGraph, hdCamera); return result; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 68f545e78aa..f48f6ce064b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -2152,9 +2152,10 @@ void AsyncSSAODispatch(CommandBuffer c, HDGPUAsyncTaskParams a) using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderShadowMaps))) { // This call overwrites camera properties passed to the shader system. - RenderShadowMaps(renderContext, cmd, cullingResults, hdCamera); + RenderShadowMaps(renderContext, cmd, m_ShaderVariablesGlobalCB, cullingResults, hdCamera); - hdCamera.SetupGlobalParams(cmd, m_FrameCount); + hdCamera.UpdateShaderVariableGlobalCB(m_ShaderVariablesGlobalCB, m_FrameCount); + m_ShaderVariablesGlobalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); } if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 8874336f173..ac4238b86e3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -220,17 +220,8 @@ static class HDShaderIDs public static readonly int _AmbientOcclusionParam = Shader.PropertyToID("_AmbientOcclusionParam"); public static readonly int _SkyTexture = Shader.PropertyToID("_SkyTexture"); - public static readonly int _EnableSubsurfaceScattering = Shader.PropertyToID("_EnableSubsurfaceScattering"); - public static readonly int _TransmittanceMultiplier = Shader.PropertyToID("_TransmittanceMultiplier"); - public static readonly int _TexturingModeFlags = Shader.PropertyToID("_TexturingModeFlags"); - public static readonly int _TransmissionFlags = Shader.PropertyToID("_TransmissionFlags"); - public static readonly int _ThicknessRemaps = Shader.PropertyToID("_ThicknessRemaps"); - public static readonly int _ShapeParams = Shader.PropertyToID("_ShapeParams"); - public static readonly int _TransmissionTintsAndFresnel0 = Shader.PropertyToID("_TransmissionTintsAndFresnel0"); public static readonly int specularLightingUAV = Shader.PropertyToID("specularLightingUAV"); public static readonly int diffuseLightingUAV = Shader.PropertyToID("diffuseLightingUAV"); - public static readonly int _DiffusionProfileHashTable = Shader.PropertyToID("_DiffusionProfileHashTable"); - public static readonly int _DiffusionProfileCount = Shader.PropertyToID("_DiffusionProfileCount"); public static readonly int _DiffusionProfileAsset = Shader.PropertyToID("_DiffusionProfileAsset"); public static readonly int _MaterialID = Shader.PropertyToID("_MaterialID"); @@ -285,29 +276,29 @@ static class HDShaderIDs public static readonly int _DecalPropertyMaskBufferSRV = Shader.PropertyToID("_DecalPropertyMaskBufferSRV"); - public static readonly int _WorldSpaceCameraPos = Shader.PropertyToID("_WorldSpaceCameraPos_Internal"); - public static readonly int _PrevCamPosRWS = Shader.PropertyToID("_PrevCamPosRWS_Internal"); - public static readonly int _ViewMatrix = Shader.PropertyToID("_ViewMatrix"); - public static readonly int _InvViewMatrix = Shader.PropertyToID("_InvViewMatrix"); - public static readonly int _ProjMatrix = Shader.PropertyToID("_ProjMatrix"); - public static readonly int _InvProjMatrix = Shader.PropertyToID("_InvProjMatrix"); - public static readonly int _NonJitteredViewProjMatrix = Shader.PropertyToID("_NonJitteredViewProjMatrix"); - public static readonly int _ViewProjMatrix = Shader.PropertyToID("_ViewProjMatrix"); - public static readonly int _CameraViewProjMatrix = Shader.PropertyToID("_CameraViewProjMatrix"); - public static readonly int _InvViewProjMatrix = Shader.PropertyToID("_InvViewProjMatrix"); - public static readonly int _ZBufferParams = Shader.PropertyToID("_ZBufferParams"); - public static readonly int _ProjectionParams = Shader.PropertyToID("_ProjectionParams"); - public static readonly int unity_OrthoParams = Shader.PropertyToID("unity_OrthoParams"); - public static readonly int _InvProjParam = Shader.PropertyToID("_InvProjParam"); - public static readonly int _ScreenSize = Shader.PropertyToID("_ScreenSize"); - public static readonly int _ScreenParams = Shader.PropertyToID("_ScreenParams"); - public static readonly int _RTHandleScale = Shader.PropertyToID("_RTHandleScale"); - public static readonly int _RTHandleScaleHistory = Shader.PropertyToID("_RTHandleScaleHistory"); - public static readonly int _PrevViewProjMatrix = Shader.PropertyToID("_PrevViewProjMatrix"); - public static readonly int _PrevInvViewProjMatrix = Shader.PropertyToID("_PrevInvViewProjMatrix"); - public static readonly int _FrustumPlanes = Shader.PropertyToID("_FrustumPlanes"); - public static readonly int _TaaFrameInfo = Shader.PropertyToID("_TaaFrameInfo"); - public static readonly int _TaaJitterStrength = Shader.PropertyToID("_TaaJitterStrength"); + //public static readonly int _WorldSpaceCameraPos = Shader.PropertyToID("_WorldSpaceCameraPos_Internal"); + //public static readonly int _PrevCamPosRWS = Shader.PropertyToID("_PrevCamPosRWS_Internal"); + //public static readonly int _ViewMatrix = Shader.PropertyToID("_ViewMatrix"); + //public static readonly int _InvViewMatrix = Shader.PropertyToID("_InvViewMatrix"); + //public static readonly int _ProjMatrix = Shader.PropertyToID("_ProjMatrix"); + //public static readonly int _InvProjMatrix = Shader.PropertyToID("_InvProjMatrix"); + //public static readonly int _NonJitteredViewProjMatrix = Shader.PropertyToID("_NonJitteredViewProjMatrix"); + //public static readonly int _ViewProjMatrix = Shader.PropertyToID("_ViewProjMatrix"); + //public static readonly int _CameraViewProjMatrix = Shader.PropertyToID("_CameraViewProjMatrix"); + //public static readonly int _InvViewProjMatrix = Shader.PropertyToID("_InvViewProjMatrix"); + //public static readonly int _ZBufferParams = Shader.PropertyToID("_ZBufferParams"); + //public static readonly int _ProjectionParams = Shader.PropertyToID("_ProjectionParams"); + //public static readonly int unity_OrthoParams = Shader.PropertyToID("unity_OrthoParams"); + //public static readonly int _InvProjParam = Shader.PropertyToID("_InvProjParam"); + //public static readonly int _ScreenSize = Shader.PropertyToID("_ScreenSize"); + //public static readonly int _ScreenParams = Shader.PropertyToID("_ScreenParams"); + //public static readonly int _RTHandleScale = Shader.PropertyToID("_RTHandleScale"); + //public static readonly int _RTHandleScaleHistory = Shader.PropertyToID("_RTHandleScaleHistory"); + //public static readonly int _PrevViewProjMatrix = Shader.PropertyToID("_PrevViewProjMatrix"); + //public static readonly int _PrevInvViewProjMatrix = Shader.PropertyToID("_PrevInvViewProjMatrix"); + //public static readonly int _FrustumPlanes = Shader.PropertyToID("_FrustumPlanes"); + //public static readonly int _TaaFrameInfo = Shader.PropertyToID("_TaaFrameInfo"); + //public static readonly int _TaaJitterStrength = Shader.PropertyToID("_TaaJitterStrength"); public static readonly int _WorldSpaceCameraPos1 = Shader.PropertyToID("_WorldSpaceCameraPos1"); public static readonly int _ViewMatrix1 = Shader.PropertyToID("_ViewMatrix1"); From e30a677def9c94b6a9490937c610402fcca0ed4c Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 10 Mar 2020 14:39:49 +0100 Subject: [PATCH 34/92] Small ConstantBuffer API refacto --- .../Runtime/Common/ConstantBuffer.cs | 15 ++++++++++++++- .../Runtime/Lighting/Shadow/HDShadowAtlas.cs | 3 ++- .../RenderPipeline/HDRenderPipeline.LightLoop.cs | 2 +- .../HDRenderPipeline.RenderGraph.cs | 4 ++-- .../Runtime/RenderPipeline/HDRenderPipeline.cs | 14 +++++++------- 5 files changed, 26 insertions(+), 12 deletions(-) diff --git a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs index 54e4edba606..8ca619fcb59 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs @@ -14,12 +14,25 @@ public ConstantBuffer() m_GPUConstantBuffer = new ComputeBuffer(1, UnsafeUtility.SizeOf(), ComputeBufferType.Constant); } - public void Commit(CommandBuffer cmd, int shaderId) + public void Commit(CommandBuffer cmd) { cmd.SetComputeBufferData(m_GPUConstantBuffer, m_Data); + } + + public void PushGlobal(CommandBuffer cmd, int shaderId, bool commitData = false) + { + if (commitData) + Commit(cmd); cmd.SetGlobalConstantBuffer(m_GPUConstantBuffer, shaderId, 0, m_GPUConstantBuffer.stride); } + public void Push(CommandBuffer cmd, ComputeShader cs, int kernel, bool commitData = false) + { + if (commitData) + Commit(cmd); + cmd.SetComputeConstantBufferParam(cs, kernel, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); + } + public void Release() { CoreUtils.SafeRelease(m_GPUConstantBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs index 0df0a106d6c..ed65f0fcf52 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs @@ -531,7 +531,8 @@ static void RenderShadows( RenderShadowsParameters parameters, parameters.globalCB.data._InvProjMatrix = shadowRequest.deviceProjectionYFlip.inverse; parameters.globalCB.data._ViewProjMatrix = viewProjection; parameters.globalCB.data._InvViewProjMatrix = viewProjection.inverse; - parameters.globalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); + + parameters.globalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); cmd.SetGlobalVectorArray(HDShaderIDs._ShadowClipPlanes, shadowRequest.frustumPlanes); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index f0fadd48a8d..46abebf4e9e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -112,7 +112,7 @@ void PushGlobalCameraParams(RenderGraph renderGraph, HDCamera hdCamera) { data.hdCamera.UpdateShaderVariableGlobalCB(data.globalCB, data.frameCount); data.hdCamera.SetupGlobalParams(context.cmd, data.frameCount); - data.globalCB.Commit(context.cmd, HDShaderIDs._ShaderVariablesGlobal); + data.globalCB.PushGlobal(context.cmd, HDShaderIDs._ShaderVariablesGlobal, true); }); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index d1c25ed0480..02815f1ea40 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -608,12 +608,12 @@ TextureHandle RenderLowResTransparent(RenderGraph renderGraph, HDCamera hdCamera (RenderLowResTransparentPassData data, RenderGraphContext context) => { UpdateOffscreenRenderingConstants(data.globalCB, true, 2u); - data.globalCB.Commit(context.cmd, HDShaderIDs._ShaderVariablesGlobal); + data.globalCB.PushGlobal(context.cmd, HDShaderIDs._ShaderVariablesGlobal, true); DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, context.resources.GetRendererList(data.rendererList)); UpdateOffscreenRenderingConstants(data.globalCB, false, 1u); - data.globalCB.Commit(context.cmd, HDShaderIDs._ShaderVariablesGlobal); + data.globalCB.PushGlobal(context.cmd, HDShaderIDs._ShaderVariablesGlobal, true); }); return passData.lowResBuffer; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index f48f6ce064b..2772ae395f1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -1012,7 +1012,7 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) m_ShaderVariablesGlobalCB.data._UseRayTracedReflections = 0; } - m_ShaderVariablesGlobalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); + m_ShaderVariablesGlobalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); } void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd) @@ -2155,8 +2155,8 @@ void AsyncSSAODispatch(CommandBuffer c, HDGPUAsyncTaskParams a) RenderShadowMaps(renderContext, cmd, m_ShaderVariablesGlobalCB, cullingResults, hdCamera); hdCamera.UpdateShaderVariableGlobalCB(m_ShaderVariablesGlobalCB, m_FrameCount); - m_ShaderVariablesGlobalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); - } + m_ShaderVariablesGlobalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); + } if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) { @@ -3680,7 +3680,7 @@ void RenderLowResTransparent(CullingResults cullResults, HDCamera hdCamera, Scri using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.LowResTransparent))) { UpdateOffscreenRenderingConstants(m_ShaderVariablesGlobalCB, true, 2u); - m_ShaderVariablesGlobalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); + m_ShaderVariablesGlobalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); CoreUtils.SetRenderTarget(cmd, m_LowResTransparentBuffer, m_SharedRTManager.GetLowResDepthBuffer(), clearFlag: ClearFlag.Color, Color.black); RenderQueueRange transparentRange = HDRenderQueue.k_RenderQueue_LowTransparent; @@ -3689,7 +3689,7 @@ void RenderLowResTransparent(CullingResults cullResults, HDCamera hdCamera, Scri DrawTransparentRendererList(renderContext, cmd, hdCamera.frameSettings, rendererList); UpdateOffscreenRenderingConstants(m_ShaderVariablesGlobalCB, false, 1u); - m_ShaderVariablesGlobalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); + m_ShaderVariablesGlobalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); } } @@ -4541,14 +4541,14 @@ static void RenderAfterPostProcess( PostProcessParameters parameters, parameters.hdCamera.UpdateShaderVariableGlobalCB(parameters.globalCB, parameters.frameCount); UpdateOffscreenRenderingConstants(parameters.globalCB, true, 1); - parameters.globalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); + parameters.globalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); DrawOpaqueRendererList(renderContext, cmd, parameters.hdCamera.frameSettings, opaqueAfterPostProcessRendererList); // Setup off-screen transparency here DrawTransparentRendererList(renderContext, cmd, parameters.hdCamera.frameSettings, transparentAfterPostProcessRendererList); UpdateOffscreenRenderingConstants(parameters.globalCB, false, 1); - parameters.globalCB.Commit(cmd, HDShaderIDs._ShaderVariablesGlobal); + parameters.globalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); } } From 770039e5c9155dabb259fceda59338f1611148e0 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 10 Mar 2020 14:46:33 +0100 Subject: [PATCH 35/92] Small fix --- .../Runtime/Common/ConstantBuffer.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs index 8ca619fcb59..cdeed682f0e 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs @@ -26,11 +26,21 @@ public void PushGlobal(CommandBuffer cmd, int shaderId, bool commitData = false) cmd.SetGlobalConstantBuffer(m_GPUConstantBuffer, shaderId, 0, m_GPUConstantBuffer.stride); } - public void Push(CommandBuffer cmd, ComputeShader cs, int kernel, bool commitData = false) + public void Push(CommandBuffer cmd, ComputeShader cs, int shaderId, bool commitData = false) { if (commitData) Commit(cmd); - cmd.SetComputeConstantBufferParam(cs, kernel, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); + cmd.SetComputeConstantBufferParam(cs, shaderId, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); + } + + public void Push(CommandBuffer cmd, Material mat, int shaderId, bool commitData = false) + { + if (commitData) + Commit(cmd); + // This isn't done via command buffer because as long as the buffer itself is not destroyed, + // the binding stays valid. Only the commit of data needs to go through the command buffer. + // We do it here anyway for now to simplify user API. + mat.SetConstantBuffer(shaderId, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); } public void Release() From 7bfafa8c30ad446b3451f4fed49ad8c09cfd3d71 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 10 Mar 2020 17:44:21 +0100 Subject: [PATCH 36/92] Volumetric Constant Buffer implementation + Fix --- .../VolumeVoxelization.compute | 19 -- .../VolumetricLighting.compute | 19 -- .../VolumetricLighting/VolumetricLighting.cs | 256 +++++++++--------- .../VolumetricLighting.cs.hlsl | 22 ++ .../HDRenderPipeline.LightLoop.cs | 11 +- .../HDRenderPipeline.RenderGraph.cs | 2 +- .../RenderPipeline/HDRenderPipeline.cs | 4 +- .../RenderPipeline/HDStringConstants.cs | 56 +--- .../ShaderLibrary/ShaderVariables.hlsl | 11 - 9 files changed, 162 insertions(+), 238 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute index cdc875aa477..2301e781817 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute @@ -59,25 +59,6 @@ TEXTURE3D(_VolumeMaskAtlas); RW_TEXTURE3D(float4, _VBufferDensity); // RGB = sqrt(scattering), A = sqrt(extinction) -// TODO: avoid creating another Constant Buffer... -CBUFFER_START(UnityVolumetricLighting) - float4x4 _VBufferCoordToViewDirWS[SHADEROPTIONS_XR_MAX_VIEWS]; - - float _VBufferUnitDepthTexelSpacing; - uint _NumVisibleDensityVolumes; - float _CornetteShanksConstant; // Not used by this shader - uint _VBufferLightingHistoryIsValid; // Not used by this shader - - float4 _VBufferSampleOffset; // Not used by this shader - float4 _VolumeMaskDimensions; // x = 1/numTextures , y = width, z = depth = width * numTextures, w = maxLod - - // BigTile... - uint _NumTileBigTileX; - uint _NumTileBigTileY; - uint _EnvLightIndexShift; - uint _DensityVolumeIndexShift; -CBUFFER_END - //-------------------------------------------------------------------------------------------------- // Implementation //-------------------------------------------------------------------------------------------------- diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute index 287ed65d0e1..3c0a42bf69c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute @@ -88,25 +88,6 @@ RW_TEXTURE3D(float4, _VBufferLightingFeedback); TEXTURE3D(_VBufferLightingHistory); TEXTURE3D(_VBufferDensity); // RGB = scattering, A = extinction -// TODO: avoid creating another Constant Buffer... -CBUFFER_START(UnityVolumetricLighting) - float4x4 _VBufferCoordToViewDirWS[SHADEROPTIONS_XR_MAX_VIEWS]; - - float _VBufferUnitDepthTexelSpacing; - uint _NumVisibleDensityVolumes; // Not used by this shader - float _CornetteShanksConstant; - uint _VBufferLightingHistoryIsValid; - - float4 _VBufferSampleOffset; - float4 _VolumeMaskDimensions; // Not used by this shader - - // BigTile... - uint _NumTileBigTileX; - uint _NumTileBigTileY; - uint _EnvLightIndexShift; - uint _DensityVolumeIndexShift; -CBUFFER_END - //-------------------------------------------------------------------------------------------------- // Implementation //-------------------------------------------------------------------------------------------------- diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 95f925278d7..0205c9b8434 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -40,6 +40,36 @@ public static DensityVolumeEngineData GetNeutralValues() } } // struct VolumeProperties + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + unsafe struct ShaderVariablesVolumetric + { + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float _VBufferCoordToViewDirWS[(int)ShaderOptions.XrMaxViews * 16]; + + public float _VBufferUnitDepthTexelSpacing; + public uint _NumVisibleDensityVolumes; + public float _CornetteShanksConstant; + public uint _VBufferLightingHistoryIsValid; + + public Vector4 _VBufferSampleOffset; + public Vector4 _VolumeMaskDimensions; + + [HLSLArray(7, typeof(Vector4))] + public fixed float _AmbientProbeCoeffs[7 * 4]; // 3 bands of SH, packed, rescaled and convolved with the phase function + + public Vector4 _VBufferPrevViewportSize; + public Vector4 _VBufferHistoryPrevUvScaleAndLimit; + public Vector4 _VBufferPrevDepthEncodingParams; + public Vector4 _VBufferPrevDepthDecodingParams; + + // TODO: Remove if equals to the ones in global CB? + public uint _NumTileBigTileX; + public uint _NumTileBigTileY; + public uint _EnvLightIndexShift; + public uint _DensityVolumeIndexShift; + } + + class VolumeRenderingUtils { public static float MeanFreePathFromExtinction(float extinction) @@ -178,6 +208,8 @@ public partial class HDRenderPipeline RTHandle m_DensityBufferHandle; RTHandle m_LightingBufferHandle; + ConstantBuffer m_ShaderVariablesVolumetricCB; + // Is the feature globally disabled? bool m_SupportVolumetrics = false; @@ -224,6 +256,8 @@ void InitializeVolumetricLighting() m_PixelCoordToViewDirWS = new Matrix4x4[ShaderConfig.s_XrMaxViews]; + m_ShaderVariablesVolumetricCB = new ConstantBuffer(); + CreateVolumetricLightingBuffers(); } @@ -368,6 +402,8 @@ void CleanupVolumetricLighting() // Note: No need to test for support volumetric here, we do saferelease and null assignation DestroyVolumetricLightingBuffers(); + m_ShaderVariablesVolumetricCB.Release(); + m_VolumeVoxelizationCS = null; m_VolumetricLightingCS = null; } @@ -422,17 +458,6 @@ static Vector3Int ComputeVBufferResolution(VolumetricLightingPreset preset, int return new Vector3Int(w, h, d); } - void SetPreconvolvedAmbientLightProbe(HDCamera hdCamera, CommandBuffer cmd, float dimmer, float anisotropy) - { - SphericalHarmonicsL2 probeSH = SphericalHarmonicMath.UndoCosineRescaling(m_SkyManager.GetAmbientProbe(hdCamera)); - probeSH = SphericalHarmonicMath.RescaleCoefficients(probeSH, dimmer); - ZonalHarmonicsL2.GetCornetteShanksPhaseFunction(m_PhaseZH, anisotropy); - SphericalHarmonicsL2 finalSH = SphericalHarmonicMath.PremultiplyCoefficients(SphericalHarmonicMath.Convolve(probeSH, m_PhaseZH)); - - SphericalHarmonicMath.PackCoefficients(m_PackedCoeffs, finalSH); - cmd.SetGlobalVectorArray(HDShaderIDs._AmbientProbeCoeffs, m_PackedCoeffs); - } - static float CornetteShanksPhasePartConstant(float anisotropy) { float g = anisotropy; @@ -448,18 +473,14 @@ void UpdateShaderVariablesGlobalVolumetrics(ConstantBuffer(); - SetPreconvolvedAmbientLightProbe(hdCamera, cmd, fog.globalLightProbeDimmer.value, fog.anisotropy.value); - - var prevFrameParams = hdCamera.vBufferParams[1]; - - // The lighting & density buffers are shared by all cameras. - // The history & feedback buffers are specific to the camera. - // These 2 types of buffers can have different sizes. - // Additionally, history buffers can have different sizes, since they are not resized at the same time - // (every frame, we swap the buffers, and resize the feedback buffer but not the history buffer). - // The viewport size is the same for all of these buffers. - // All of these buffers may have sub-native-resolution viewports. - // The 3rd dimension (number of slices) is the same for all of these buffers. - Vector2Int historyBufferSize = Vector2Int.zero; - - if (hdCamera.IsVolumetricReprojectionEnabled()) + else { - historyBufferSize = ComputeVBufferResolutionXY(hdCamera.historyRTHandleProperties.currentRenderTargetSize); + cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, m_LightingBufferHandle); } - - var pvp = prevFrameParams.viewportSize; - - cmd.SetGlobalVector(HDShaderIDs._VBufferPrevViewportSize, new Vector4(pvp.x, pvp.y, 1.0f / pvp.x, 1.0f / pvp.y)); - cmd.SetGlobalVector(HDShaderIDs._VBufferHistoryPrevUvScaleAndLimit, prevFrameParams.ComputeUvScaleAndLimit(historyBufferSize)); - cmd.SetGlobalVector(HDShaderIDs._VBufferPrevDepthEncodingParams, prevFrameParams.depthEncodingParams); - cmd.SetGlobalVector(HDShaderIDs._VBufferPrevDepthDecodingParams, prevFrameParams.depthDecodingParams); - - cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, m_LightingBufferHandle); } DensityVolumeList PrepareVisibleDensityVolumeList(HDCamera hdCamera, CommandBuffer cmd, float time) @@ -568,62 +562,110 @@ struct VolumeVoxelizationParameters public int voxelizationKernel; public Vector4 resolution; - public int numBigTileX, numBigTileY; public int viewCount; public bool tiledLighting; - public float unitDepthTexelSpacing; - public int numVisibleVolumes; public Texture3D volumeAtlas; - public Vector4 volumeAtlasDimensions; - public Matrix4x4[] pixelCoordToViewDirWS; + public ConstantBuffer volumetricCB; } - VolumeVoxelizationParameters PrepareVolumeVoxelizationParameters(HDCamera hdCamera) + unsafe void SetPreconvolvedAmbientLightProbe(ConstantBuffer cb, HDCamera hdCamera, Fog fog) + { + SphericalHarmonicsL2 probeSH = SphericalHarmonicMath.UndoCosineRescaling(m_SkyManager.GetAmbientProbe(hdCamera)); + probeSH = SphericalHarmonicMath.RescaleCoefficients(probeSH, fog.globalLightProbeDimmer.value); + ZonalHarmonicsL2.GetCornetteShanksPhaseFunction(m_PhaseZH, fog.anisotropy.value); + SphericalHarmonicsL2 finalSH = SphericalHarmonicMath.PremultiplyCoefficients(SphericalHarmonicMath.Convolve(probeSH, m_PhaseZH)); + + SphericalHarmonicMath.PackCoefficients(m_PackedCoeffs, finalSH); + for (int i = 0; i < 7; i++) + for (int j = 0; j < 4; ++j) + cb.data._AmbientProbeCoeffs[i * 4 + j] = m_PackedCoeffs[i][j]; + } + + unsafe void UpdateShaderVariableslVolumetrics(ConstantBuffer cb, HDCamera hdCamera, in Vector4 resolution, int frameIndex) + { + var fog = hdCamera.volumeStack.GetComponent(); + var vFoV = hdCamera.camera.GetGateFittedFieldOfView() * Mathf.Deg2Rad; + var gpuAspect = HDUtils.ProjectionMatrixAspect(hdCamera.mainViewConstants.projMatrix); + + // Compose the matrix which allows us to compute the world space view direction. + hdCamera.GetPixelCoordToViewDirWS(resolution, gpuAspect, ref m_PixelCoordToViewDirWS); + + for (int i = 0; i < m_PixelCoordToViewDirWS.Length; ++i) + for (int j = 0; j < 16; ++j) + cb.data._VBufferCoordToViewDirWS[i * 16 + j] = m_PixelCoordToViewDirWS[i][j]; + cb.data._VBufferUnitDepthTexelSpacing = HDUtils.ComputZPlaneTexelSpacing(1.0f, vFoV, resolution.y); + cb.data._NumVisibleDensityVolumes = (uint)m_VisibleVolumeBounds.Count; + cb.data._CornetteShanksConstant = CornetteShanksPhasePartConstant(fog.anisotropy.value); + cb.data._VBufferLightingHistoryIsValid = hdCamera.volumetricHistoryIsValid ? 1u : 0u; + + GetHexagonalClosePackedSpheres7(m_xySeq); + int sampleIndex = frameIndex % 7; + Vector4 xySeqOffset = new Vector4(); + // TODO: should we somehow reorder offsets in Z based on the offset in XY? S.t. the samples more evenly cover the domain. + // Currently, we assume that they are completely uncorrelated, but maybe we should correlate them somehow. + xySeqOffset.Set(m_xySeq[sampleIndex].x, m_xySeq[sampleIndex].y, m_zSeq[sampleIndex], frameIndex); + cb.data._VBufferSampleOffset = xySeqOffset; + + var volumeAtlas = DensityVolumeManager.manager.volumeAtlas.GetAtlas(); + cb.data._VolumeMaskDimensions = Vector4.zero; + if (DensityVolumeManager.manager.volumeAtlas.GetAtlas() != null) + { + cb.data._VolumeMaskDimensions.x = (float)volumeAtlas.width / volumeAtlas.depth; // 1 / number of textures + cb.data._VolumeMaskDimensions.y = volumeAtlas.width; + cb.data._VolumeMaskDimensions.z = volumeAtlas.depth; + cb.data._VolumeMaskDimensions.w = Mathf.Log(volumeAtlas.width, 2); // Max LoD + } + + SetPreconvolvedAmbientLightProbe(cb, hdCamera, fog); + + // The lighting & density buffers are shared by all cameras. + // The history & feedback buffers are specific to the camera. + // These 2 types of buffers can have different sizes. + // Additionally, history buffers can have different sizes, since they are not resized at the same time + // (every frame, we swap the buffers, and resize the feedback buffer but not the history buffer). + // The viewport size is the same for all of these buffers. + // All of these buffers may have sub-native-resolution viewports. + // The 3rd dimension (number of slices) is the same for all of these buffers. + var prevFrameParams = hdCamera.vBufferParams[1]; + var pvp = prevFrameParams.viewportSize; + + cb.data._VBufferPrevViewportSize = new Vector4(pvp.x, pvp.y, 1.0f / pvp.x, 1.0f / pvp.y); + cb.data._VBufferHistoryPrevUvScaleAndLimit = prevFrameParams.ComputeUvScaleAndLimit(ComputeVBufferResolutionXY(hdCamera.historyRTHandleProperties.currentRenderTargetSize)); + cb.data._VBufferPrevDepthEncodingParams = prevFrameParams.depthEncodingParams; + cb.data._VBufferPrevDepthDecodingParams = prevFrameParams.depthDecodingParams; + cb.data._NumTileBigTileX = (uint)GetNumTileBigTileX(hdCamera); + cb.data._NumTileBigTileY = (uint)GetNumTileBigTileY(hdCamera); + + // TODO: this should probably move to a lighting specific constant buffer. + int decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); + cb.data._EnvLightIndexShift = (uint)m_lightList.lights.Count; + cb.data._DensityVolumeIndexShift = (uint)(m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount); + } + + VolumeVoxelizationParameters PrepareVolumeVoxelizationParameters(HDCamera hdCamera, int frameIndex) { var parameters = new VolumeVoxelizationParameters(); parameters.viewCount = hdCamera.viewCount; - parameters.numBigTileX = GetNumTileBigTileX(hdCamera); - parameters.numBigTileY = GetNumTileBigTileY(hdCamera); - parameters.tiledLighting = HasLightToCull() && hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass); bool highQuality = volumetricLightingPreset == VolumetricLightingPreset.High; parameters.voxelizationCS = m_VolumeVoxelizationCS; parameters.voxelizationKernel = (parameters.tiledLighting ? 1 : 0) | (highQuality ? 2 : 0); - var currFrameParams = hdCamera.vBufferParams[0]; - var cvp = currFrameParams.viewportSize; - + var cvp = hdCamera.vBufferParams[0].viewportSize; parameters.resolution = new Vector4(cvp.x, cvp.y, 1.0f / cvp.x, 1.0f / cvp.y); - var vFoV = hdCamera.camera.GetGateFittedFieldOfView() * Mathf.Deg2Rad; - var gpuAspect = HDUtils.ProjectionMatrixAspect(hdCamera.mainViewConstants.projMatrix); - - // Compose the matrix which allows us to compute the world space view direction. - hdCamera.GetPixelCoordToViewDirWS(parameters.resolution, gpuAspect, ref m_PixelCoordToViewDirWS); - parameters.pixelCoordToViewDirWS = m_PixelCoordToViewDirWS; - - // Compute texel spacing at the depth of 1 meter. - parameters.unitDepthTexelSpacing = HDUtils.ComputZPlaneTexelSpacing(1.0f, vFoV, parameters.resolution.y); - - parameters.numVisibleVolumes = m_VisibleVolumeBounds.Count; parameters.volumeAtlas = DensityVolumeManager.manager.volumeAtlas.GetAtlas(); - parameters.volumeAtlasDimensions = new Vector4(0.0f, 0.0f, 0.0f, 0.0f); - if (parameters.volumeAtlas != null) - { - parameters.volumeAtlasDimensions.x = (float)parameters.volumeAtlas.width / parameters.volumeAtlas.depth; // 1 / number of textures - parameters.volumeAtlasDimensions.y = parameters.volumeAtlas.width; - parameters.volumeAtlasDimensions.z = parameters.volumeAtlas.depth; - parameters.volumeAtlasDimensions.w = Mathf.Log(parameters.volumeAtlas.width, 2); // Max LoD - } - else + if (parameters.volumeAtlas == null) { parameters.volumeAtlas = CoreUtils.blackVolumeTexture; } + UpdateShaderVariableslVolumetrics(m_ShaderVariablesVolumetricCB, hdCamera, parameters.resolution, frameIndex); + parameters.volumetricCB = m_ShaderVariablesVolumetricCB; return parameters; } @@ -633,9 +675,7 @@ static void VolumeVoxelizationPass( in VolumeVoxelizationParameters parameters, ComputeBuffer visibleVolumeDataBuffer, ComputeBuffer bigTileLightList, CommandBuffer cmd) - { - cmd.SetComputeIntParam(parameters.voxelizationCS, HDShaderIDs._NumTileBigTileX, parameters.numBigTileX); - cmd.SetComputeIntParam(parameters.voxelizationCS, HDShaderIDs._NumTileBigTileY, parameters.numBigTileY); + { if (parameters.tiledLighting) cmd.SetComputeBufferParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs.g_vBigTileLightList, bigTileLightList); @@ -644,24 +684,20 @@ static void VolumeVoxelizationPass( in VolumeVoxelizationParameters parameters, cmd.SetComputeBufferParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs._VolumeData, visibleVolumeDataBuffer); cmd.SetComputeTextureParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs._VolumeMaskAtlas, parameters.volumeAtlas); - // TODO: set the constant buffer data only once. - cmd.SetComputeMatrixArrayParam(parameters.voxelizationCS, HDShaderIDs._VBufferCoordToViewDirWS, parameters.pixelCoordToViewDirWS); - cmd.SetComputeFloatParam(parameters.voxelizationCS, HDShaderIDs._VBufferUnitDepthTexelSpacing, parameters.unitDepthTexelSpacing); - cmd.SetComputeIntParam(parameters.voxelizationCS, HDShaderIDs._NumVisibleDensityVolumes, parameters.numVisibleVolumes); - cmd.SetComputeVectorParam(parameters.voxelizationCS, HDShaderIDs._VolumeMaskDimensions, parameters.volumeAtlasDimensions); + parameters.volumetricCB.Push(cmd, parameters.voxelizationCS, HDShaderIDs._ShaderVariablesVolumetric, true); // The shader defines GROUP_SIZE_1D = 8. cmd.DispatchCompute(parameters.voxelizationCS, parameters.voxelizationKernel, ((int)parameters.resolution.x + 7) / 8, ((int)parameters.resolution.y + 7) / 8, parameters.viewCount); } - void VolumeVoxelizationPass(HDCamera hdCamera, CommandBuffer cmd) + void VolumeVoxelizationPass(HDCamera hdCamera, CommandBuffer cmd, int frameIndex) { if (!Fog.IsVolumetricFogEnabled(hdCamera)) return; using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.VolumeVoxelization))) { - var parameters = PrepareVolumeVoxelizationParameters(hdCamera); + var parameters = PrepareVolumeVoxelizationParameters(hdCamera, frameIndex); VolumeVoxelizationPass(parameters, m_DensityBufferHandle, m_VisibleVolumeBoundsBuffer, m_VisibleVolumeDataBuffer, m_TileAndClusterData.bigTileLightList, cmd); } } @@ -710,16 +746,10 @@ struct VolumetricLightingParameters public int volumetricFilteringKernelY; public bool tiledLighting; public Vector4 resolution; - public int numBigTileX, numBigTileY; - public float unitDepthTexelSpacing; - public float anisotropy; - public Vector4 xySeqOffset; public bool enableReprojection; - public bool historyIsValid; public int viewCount; public bool filterVolume; - - public Matrix4x4[] pixelCoordToViewDirWS; + public ConstantBuffer volumetricCB; } VolumetricLightingParameters PrepareVolumetricLightingParameters(HDCamera hdCamera, int frameIndex) @@ -739,32 +769,14 @@ VolumetricLightingParameters PrepareVolumetricLightingParameters(HDCamera hdCame parameters.volumetricLightingKernel = (parameters.tiledLighting ? 1 : 0) | (parameters.enableReprojection ? 2 : 0) | (enableAnisotropy ? 4 : 0) | (highQuality ? 8 : 0); parameters.volumetricFilteringKernelX = 16; parameters.volumetricFilteringKernelY = 17; - var currFrameParams = hdCamera.vBufferParams[0]; - var cvp = currFrameParams.viewportSize; + var cvp = hdCamera.vBufferParams[0].viewportSize; parameters.resolution = new Vector4(cvp.x, cvp.y, 1.0f / cvp.x, 1.0f / cvp.y); - var vFoV = hdCamera.camera.GetGateFittedFieldOfView() * Mathf.Deg2Rad; - var gpuAspect = HDUtils.ProjectionMatrixAspect(hdCamera.mainViewConstants.projMatrix); - - // Compose the matrix which allows us to compute the world space view direction. - hdCamera.GetPixelCoordToViewDirWS(parameters.resolution, gpuAspect, ref m_PixelCoordToViewDirWS); - parameters.pixelCoordToViewDirWS = m_PixelCoordToViewDirWS; - - // Compute texel spacing at the depth of 1 meter. - parameters.unitDepthTexelSpacing = HDUtils.ComputZPlaneTexelSpacing(1.0f, vFoV, parameters.resolution.y); - - parameters.anisotropy = fog.anisotropy.value; - parameters.historyIsValid = hdCamera.volumetricHistoryIsValid; parameters.viewCount = hdCamera.viewCount; - parameters.numBigTileX = GetNumTileBigTileX(hdCamera); - parameters.numBigTileY = GetNumTileBigTileY(hdCamera); parameters.filterVolume = fog.filter.value; - GetHexagonalClosePackedSpheres7(m_xySeq); - int sampleIndex = frameIndex % 7; - // TODO: should we somehow reorder offsets in Z based on the offset in XY? S.t. the samples more evenly cover the domain. - // Currently, we assume that they are completely uncorrelated, but maybe we should correlate them somehow. - parameters.xySeqOffset.Set(m_xySeq[sampleIndex].x, m_xySeq[sampleIndex].y, m_zSeq[sampleIndex], frameIndex); + UpdateShaderVariableslVolumetrics(m_ShaderVariablesVolumetricCB, hdCamera, parameters.resolution, frameIndex); + parameters.volumetricCB = m_ShaderVariablesVolumetricCB; return parameters; } @@ -777,29 +789,20 @@ static void VolumetricLightingPass( in VolumetricLightingParameters parameters, ComputeBuffer bigTileLightList, CommandBuffer cmd) { - cmd.SetComputeIntParam(parameters.volumetricLightingCS, HDShaderIDs._NumTileBigTileX, parameters.numBigTileX); - cmd.SetComputeIntParam(parameters.volumetricLightingCS, HDShaderIDs._NumTileBigTileY, parameters.numBigTileY); if (parameters.tiledLighting) cmd.SetComputeBufferParam(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, HDShaderIDs.g_vBigTileLightList, bigTileLightList); - // TODO: set 'm_VolumetricLightingPreset'. - // TODO: set the constant buffer data only once. - cmd.SetComputeMatrixArrayParam(parameters.volumetricLightingCS, HDShaderIDs._VBufferCoordToViewDirWS, parameters.pixelCoordToViewDirWS); - cmd.SetComputeFloatParam(parameters.volumetricLightingCS, HDShaderIDs._VBufferUnitDepthTexelSpacing, parameters.unitDepthTexelSpacing); - cmd.SetComputeFloatParam(parameters.volumetricLightingCS, HDShaderIDs._CornetteShanksConstant, CornetteShanksPhasePartConstant(parameters.anisotropy)); - cmd.SetComputeVectorParam(parameters.volumetricLightingCS, HDShaderIDs._VBufferSampleOffset, parameters.xySeqOffset); cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, HDShaderIDs._VBufferDensity, densityBuffer); // Read cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, HDShaderIDs._VBufferLightingIntegral, lightingBuffer); // Write - // We set this even when not re-projecting to make sure it stays in a safe state when we switch camera - cmd.SetComputeIntParam(parameters.volumetricLightingCS, HDShaderIDs._VBufferLightingHistoryIsValid, parameters.historyIsValid ? 1 : 0); - if (parameters.enableReprojection) { cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, HDShaderIDs._VBufferLightingHistory, historyRT); // Read cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, HDShaderIDs._VBufferLightingFeedback, feedbackRT); // Write } + parameters.volumetricCB.Push(cmd, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesVolumetric, true); + // The shader defines GROUP_SIZE_1D = 8. cmd.DispatchCompute(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, ((int)parameters.resolution.x + 7) / 8, ((int)parameters.resolution.y + 7) / 8, parameters.viewCount); } @@ -808,6 +811,7 @@ static void FilterVolumetricLighting(in VolumetricLightingParameters parameters, { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.VolumetricLightingFiltering))) { + parameters.volumetricCB.Push(cmd, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesVolumetric); // The shader defines GROUP_SIZE_1D = 8. cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelX, HDShaderIDs._VBufferLightingFeedback, inputBuffer); // Read diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl index 4fd8a0d064b..cb4b6f28e32 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl @@ -20,6 +20,28 @@ struct DensityVolumeEngineData float endTimesRcpDistFadeLen; }; +// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesVolumetric +// PackingRules = Exact +cbuffer ShaderVariablesVolumetric +{ + float4x4 _VBufferCoordToViewDirWS[2]; + float _VBufferUnitDepthTexelSpacing; + uint _NumVisibleDensityVolumes; + float _CornetteShanksConstant; + uint _VBufferLightingHistoryIsValid; + float4 _VBufferSampleOffset; + float4 _VolumeMaskDimensions; + float4 _AmbientProbeCoeffs[7]; + float4 _VBufferPrevViewportSize; + float4 _VBufferHistoryPrevUvScaleAndLimit; + float4 _VBufferPrevDepthEncodingParams; + float4 _VBufferPrevDepthDecodingParams; + uint _NumTileBigTileX; + uint _NumTileBigTileY; + uint _EnvLightIndexShift; + uint _DensityVolumeIndexShift; +}; + // // Accessors for UnityEngine.Rendering.HighDefinition.DensityVolumeEngineData // diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 46abebf4e9e..49c798e4198 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -391,10 +391,11 @@ class VolumeVoxelizationPassData } TextureHandle VolumeVoxelizationPass( RenderGraph renderGraph, - HDCamera hdCamera, - ComputeBuffer visibleVolumeBoundsBuffer, - ComputeBuffer visibleVolumeDataBuffer, - ComputeBuffer bigTileLightListBuffer) + HDCamera hdCamera, + ComputeBuffer visibleVolumeBoundsBuffer, + ComputeBuffer visibleVolumeDataBuffer, + ComputeBuffer bigTileLightListBuffer, + int frameIndex) { if (Fog.IsVolumetricFogEnabled(hdCamera)) { @@ -402,7 +403,7 @@ TextureHandle VolumeVoxelizationPass( RenderGraph renderGraph, { builder.EnableAsyncCompute(hdCamera.frameSettings.VolumeVoxelizationRunsAsync()); - passData.parameters = PrepareVolumeVoxelizationParameters(hdCamera); + passData.parameters = PrepareVolumeVoxelizationParameters(hdCamera, frameIndex); passData.visibleVolumeBoundsBuffer = visibleVolumeBoundsBuffer; passData.visibleVolumeDataBuffer = visibleVolumeDataBuffer; passData.bigTileLightListBuffer = bigTileLightListBuffer; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index 02815f1ea40..915af7519ff 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -81,7 +81,7 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, lightingBuffers.contactShadowsBuffer = RenderContactShadows(m_RenderGraph, hdCamera, msaa ? prepassOutput.depthValuesMSAA : prepassOutput.depthPyramidTexture, GetDepthBufferMipChainInfo().mipLevelOffsets[1].y); - var volumetricDensityBuffer = VolumeVoxelizationPass(m_RenderGraph, hdCamera, m_VisibleVolumeBoundsBuffer, m_VisibleVolumeDataBuffer, m_TileAndClusterData.bigTileLightList); + var volumetricDensityBuffer = VolumeVoxelizationPass(m_RenderGraph, hdCamera, m_VisibleVolumeBoundsBuffer, m_VisibleVolumeDataBuffer, m_TileAndClusterData.bigTileLightList, m_FrameCount); shadowResult = RenderShadows(m_RenderGraph, hdCamera, cullingResults); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 2772ae395f1..e9639e92d2f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -2127,7 +2127,7 @@ void Callback(CommandBuffer c, HDGPUAsyncTaskParams a) haveAsyncTaskWithShadows = true; void Callback(CommandBuffer c, HDGPUAsyncTaskParams a) - => VolumeVoxelizationPass(a.hdCamera, c); + => VolumeVoxelizationPass(a.hdCamera, c, m_FrameCount); } if (hdCamera.frameSettings.SSRRunsAsync()) @@ -2219,7 +2219,7 @@ void Callback(CommandBuffer c, HDCamera cam) else { // Perform the voxelization step which fills the density 3D texture. - VolumeVoxelizationPass(hdCamera, cmd); + VolumeVoxelizationPass(hdCamera, cmd, m_FrameCount); } // Render the volumetric lighting. diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index ac4238b86e3..99dfe1313b4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -275,31 +275,6 @@ static class HDShaderIDs public static readonly int _DecalPropertyMaskBuffer = Shader.PropertyToID("_DecalPropertyMaskBuffer"); public static readonly int _DecalPropertyMaskBufferSRV = Shader.PropertyToID("_DecalPropertyMaskBufferSRV"); - - //public static readonly int _WorldSpaceCameraPos = Shader.PropertyToID("_WorldSpaceCameraPos_Internal"); - //public static readonly int _PrevCamPosRWS = Shader.PropertyToID("_PrevCamPosRWS_Internal"); - //public static readonly int _ViewMatrix = Shader.PropertyToID("_ViewMatrix"); - //public static readonly int _InvViewMatrix = Shader.PropertyToID("_InvViewMatrix"); - //public static readonly int _ProjMatrix = Shader.PropertyToID("_ProjMatrix"); - //public static readonly int _InvProjMatrix = Shader.PropertyToID("_InvProjMatrix"); - //public static readonly int _NonJitteredViewProjMatrix = Shader.PropertyToID("_NonJitteredViewProjMatrix"); - //public static readonly int _ViewProjMatrix = Shader.PropertyToID("_ViewProjMatrix"); - //public static readonly int _CameraViewProjMatrix = Shader.PropertyToID("_CameraViewProjMatrix"); - //public static readonly int _InvViewProjMatrix = Shader.PropertyToID("_InvViewProjMatrix"); - //public static readonly int _ZBufferParams = Shader.PropertyToID("_ZBufferParams"); - //public static readonly int _ProjectionParams = Shader.PropertyToID("_ProjectionParams"); - //public static readonly int unity_OrthoParams = Shader.PropertyToID("unity_OrthoParams"); - //public static readonly int _InvProjParam = Shader.PropertyToID("_InvProjParam"); - //public static readonly int _ScreenSize = Shader.PropertyToID("_ScreenSize"); - //public static readonly int _ScreenParams = Shader.PropertyToID("_ScreenParams"); - //public static readonly int _RTHandleScale = Shader.PropertyToID("_RTHandleScale"); - //public static readonly int _RTHandleScaleHistory = Shader.PropertyToID("_RTHandleScaleHistory"); - //public static readonly int _PrevViewProjMatrix = Shader.PropertyToID("_PrevViewProjMatrix"); - //public static readonly int _PrevInvViewProjMatrix = Shader.PropertyToID("_PrevInvViewProjMatrix"); - //public static readonly int _FrustumPlanes = Shader.PropertyToID("_FrustumPlanes"); - //public static readonly int _TaaFrameInfo = Shader.PropertyToID("_TaaFrameInfo"); - //public static readonly int _TaaJitterStrength = Shader.PropertyToID("_TaaJitterStrength"); - public static readonly int _WorldSpaceCameraPos1 = Shader.PropertyToID("_WorldSpaceCameraPos1"); public static readonly int _ViewMatrix1 = Shader.PropertyToID("_ViewMatrix1"); @@ -372,6 +347,7 @@ static class HDShaderIDs }; public static readonly int _ShaderVariablesGlobal = Shader.PropertyToID("ShaderVariablesGlobal"); + public static readonly int _ShaderVariablesVolumetric = Shader.PropertyToID("ShaderVariablesVolumetric"); public static readonly int _SSSBufferTexture = Shader.PropertyToID("_SSSBufferTexture"); public static readonly int _NormalBufferTexture = Shader.PropertyToID("_NormalBufferTexture"); @@ -473,44 +449,14 @@ static class HDShaderIDs public static readonly int _DstOffset = Shader.PropertyToID("_DstOffset"); public static readonly int _DepthMipChain = Shader.PropertyToID("_DepthMipChain"); - - public static readonly int _FogEnabled = Shader.PropertyToID("_FogEnabled"); - public static readonly int _PBRFogEnabled = Shader.PropertyToID("_PBRFogEnabled"); - public static readonly int _MaxFogDistance = Shader.PropertyToID("_MaxFogDistance"); - public static readonly int _AmbientProbeCoeffs = Shader.PropertyToID("_AmbientProbeCoeffs"); - public static readonly int _HeightFogBaseExtinction = Shader.PropertyToID("_HeightFogBaseExtinction"); - public static readonly int _HeightFogBaseScattering = Shader.PropertyToID("_HeightFogBaseScattering"); - public static readonly int _HeightFogBaseHeight = Shader.PropertyToID("_HeightFogBaseHeight"); - public static readonly int _HeightFogExponents = Shader.PropertyToID("_HeightFogExponents"); - public static readonly int _EnableVolumetricFog = Shader.PropertyToID("_EnableVolumetricFog"); - public static readonly int _GlobalFogAnisotropy = Shader.PropertyToID("_GlobalFogAnisotropy"); - public static readonly int _CornetteShanksConstant = Shader.PropertyToID("_CornetteShanksConstant"); - public static readonly int _VBufferViewportSize = Shader.PropertyToID("_VBufferViewportSize"); - public static readonly int _VBufferSliceCount = Shader.PropertyToID("_VBufferSliceCount"); - public static readonly int _VBufferRcpSliceCount = Shader.PropertyToID("_VBufferRcpSliceCount"); - public static readonly int _VBufferRcpInstancedViewCount = Shader.PropertyToID("_VBufferRcpInstancedViewCount"); - public static readonly int _VBufferSharedUvScaleAndLimit = Shader.PropertyToID("_VBufferSharedUvScaleAndLimit"); - public static readonly int _VBufferDistanceEncodingParams = Shader.PropertyToID("_VBufferDistanceEncodingParams"); - public static readonly int _VBufferDistanceDecodingParams = Shader.PropertyToID("_VBufferDistanceDecodingParams"); - public static readonly int _VBufferPrevViewportSize = Shader.PropertyToID("_VBufferPrevViewportSize"); - public static readonly int _VBufferHistoryPrevUvScaleAndLimit = Shader.PropertyToID("_VBufferHistoryPrevUvScaleAndLimit"); - public static readonly int _VBufferPrevDepthEncodingParams = Shader.PropertyToID("_VBufferPrevDepthEncodingParams"); - public static readonly int _VBufferPrevDepthDecodingParams = Shader.PropertyToID("_VBufferPrevDepthDecodingParams"); - public static readonly int _VBufferLastSliceDist = Shader.PropertyToID("_VBufferLastSliceDist"); - public static readonly int _VBufferCoordToViewDirWS = Shader.PropertyToID("_VBufferCoordToViewDirWS"); - public static readonly int _VBufferUnitDepthTexelSpacing = Shader.PropertyToID("_VBufferUnitDepthTexelSpacing"); public static readonly int _VBufferDensity = Shader.PropertyToID("_VBufferDensity"); public static readonly int _VBufferLighting = Shader.PropertyToID("_VBufferLighting"); public static readonly int _VBufferLightingIntegral = Shader.PropertyToID("_VBufferLightingIntegral"); public static readonly int _VBufferLightingHistory = Shader.PropertyToID("_VBufferLightingHistory"); - public static readonly int _VBufferLightingHistoryIsValid = Shader.PropertyToID("_VBufferLightingHistoryIsValid"); public static readonly int _VBufferLightingFeedback = Shader.PropertyToID("_VBufferLightingFeedback"); - public static readonly int _VBufferSampleOffset = Shader.PropertyToID("_VBufferSampleOffset"); public static readonly int _VolumeBounds = Shader.PropertyToID("_VolumeBounds"); public static readonly int _VolumeData = Shader.PropertyToID("_VolumeData"); - public static readonly int _NumVisibleDensityVolumes = Shader.PropertyToID("_NumVisibleDensityVolumes"); public static readonly int _VolumeMaskAtlas = Shader.PropertyToID("_VolumeMaskAtlas"); - public static readonly int _VolumeMaskDimensions = Shader.PropertyToID("_VolumeMaskDimensions"); public static readonly int _EnableLightLayers = Shader.PropertyToID("_EnableLightLayers"); public static readonly int _ReplaceDiffuseForIndirect = Shader.PropertyToID("_ReplaceDiffuseForIndirect"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl index fb72ababb0f..8d27401af8c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl @@ -150,17 +150,6 @@ TEXTURE2D(_PrevExposureTexture); // ---------------------------------------------------------------------------- #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl" -// TODO: these are only used for reprojection. -// Once reprojection is performed in a separate pass, we should probably -// move these to a dedicated CBuffer to avoid polluting the global one. -// $$$ Volumetric only? -float4 _AmbientProbeCoeffs[7]; // 3 bands of SH, packed, rescaled and convolved with the phase function - -float4 _VBufferPrevViewportSize; -float4 _VBufferHistoryPrevUvScaleAndLimit; -float4 _VBufferPrevDepthEncodingParams; -float4 _VBufferPrevDepthDecodingParams; - // Custom generated by HDRP, not from Unity Engine (passed in via HDCamera) #if defined(USING_STEREO_MATRICES) CBUFFER_START(UnityXRViewConstants) From d5421128a3d8d7c8a9f2cd02273f304dac89be87 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 10 Mar 2020 17:59:48 +0100 Subject: [PATCH 37/92] Fix ambient occlusion --- .../Runtime/RenderPipeline/HDRenderPipeline.cs | 1 + .../Runtime/RenderPipeline/HDStringConstants.cs | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index e9639e92d2f..e83d777bf6d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -974,6 +974,7 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) UpdateShaderVariablesGlobalVolumetrics(m_ShaderVariablesGlobalCB, RTHandles.rtHandleProperties, hdCamera); m_ShadowManager.UpdateShaderVariablesGlobalCB(m_ShaderVariablesGlobalCB); UpdateShaderVariablesGlobalLightLoop(m_ShaderVariablesGlobalCB, hdCamera); + m_AmbientOcclusionSystem.UpdateShaderVariableGlobalCB(m_ShaderVariablesGlobalCB, hdCamera); // Misc MicroShadowing microShadowingSettings = hdCamera.volumeStack.GetComponent(); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 99dfe1313b4..8016ba6d122 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -217,7 +217,6 @@ static class HDShaderIDs public static readonly int _LastTimeParameters = Shader.PropertyToID("_LastTimeParameters"); public static readonly int _EnvLightSkyEnabled = Shader.PropertyToID("_EnvLightSkyEnabled"); - public static readonly int _AmbientOcclusionParam = Shader.PropertyToID("_AmbientOcclusionParam"); public static readonly int _SkyTexture = Shader.PropertyToID("_SkyTexture"); public static readonly int specularLightingUAV = Shader.PropertyToID("specularLightingUAV"); From 5a75d006877c358bfcd377f004a60cf5c2e5052a Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 11 Mar 2020 17:46:20 +0100 Subject: [PATCH 38/92] Removed redundant SetGlobalXXX --- .../Shadow/ScreenSpaceShadowManager.cs | 17 +----- .../SubsurfaceScatteringManager.cs | 2 - .../PostProcessing/PostProcessSystem.cs | 2 - .../RenderPipeline/HDStringConstants.cs | 58 ------------------- .../HDRaytracingAmbientOcclusion.cs | 3 - .../Raytracing/HDRaytracingIndirectDiffuse.cs | 7 --- .../HDRaytracingRecursiveRenderer.cs | 3 +- .../Raytracing/HDRaytracingReflection.cs | 9 +-- .../Raytracing/HDReflectionDenoiser.cs | 2 - .../Raytracing/HDSimpleDenoiser.cs | 3 - .../Raytracing/HDTemporalFilter.cs | 8 +-- .../Runtime/RenderPipeline/Utility/HDUtils.cs | 3 - 12 files changed, 6 insertions(+), 111 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs index 53f78300541..f943fb8018a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs @@ -312,10 +312,6 @@ void RenderDirectionalLightScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamer // Inject the ray-tracing sampling data m_BlueNoise.BindDitheredRNGData8SPP(cmd); - // Compute the current frame index - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingFrameIndex, frameIndex); - // Inject the ray generation data RayTracingSettings rayTracingSettings = hdCamera.volumeStack.GetComponent(); cmd.SetRayTracingFloatParam(m_ScreenSpaceShadowsRT, HDShaderIDs._RaytracingRayBias, rayTracingSettings.rayBias.value); @@ -331,7 +327,6 @@ void RenderDirectionalLightScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamer { // Bind the light & sampling data cmd.SetComputeBufferParam(m_ScreenSpaceShadowsCS, m_RaytracingDirectionalShadowSample, HDShaderIDs._DirectionalLightDatas, m_LightLoopLightData.directionalLightData); - cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._DirectionalShadowIndex, m_CurrentShadowSortedSunLightIndex); cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingSampleIndex, sampleIdx); cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingNumSamples, m_CurrentSunLightAdditionalLightData.numRayTracingSamples); @@ -396,7 +391,7 @@ void RenderDirectionalLightScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamer #endif // We need to check if something invalidated the history buffers historyValidity *= ValidRayTracingHistory(hdCamera) ? 1.0f : 0.0f; - + // Apply the temporal denoiser HDTemporalFilter temporalFilter = GetTemporalFilter(); temporalFilter.DenoiseBuffer(cmd, hdCamera, intermediateBuffer0, shadowHistoryArray, shadowHistoryValidityArray, velocityBuffer, intermediateBuffer1, dirShadowIndex / 4, m_ShadowChannelMask0, singleChannel: !m_CurrentSunLightAdditionalLightData.colorShadow, historyValidity: historyValidity); @@ -517,8 +512,6 @@ void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera cmd.SetComputeMatrixParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingAreaWorldToLocal, m_WorldToLocalArea); cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingTargetAreaLight, lightIndex); cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingNumSamples, additionalLightData.numRayTracingSamples); - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingFrameIndex, frameIndex); // Bind the input buffers cmd.SetComputeTextureParam(m_ScreenSpaceShadowsCS, m_AreaRaytracingAreaShadowPrepassKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); @@ -641,10 +634,6 @@ void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera cmd.SetComputeVectorParam(m_ScreenSpaceShadowsFilterCS, HDShaderIDs._DenoisingHistoryMaskSn, m_ShadowChannelMask1); cmd.SetComputeVectorParam(m_ScreenSpaceShadowsFilterCS, HDShaderIDs._DenoisingHistoryMaskUn, m_ShadowChannelMask2); - // Apply a vectorized temporal filtering pass and store it back in the denoisebuffer0 with the analytic value in the third channel - var historyScale = new Vector2(hdCamera.actualWidth / (float)shadowHistoryArray.rt.width, hdCamera.actualHeight / (float)shadowHistoryArray.rt.height); - cmd.SetComputeVectorParam(m_ScreenSpaceShadowsFilterCS, HDShaderIDs._RTHandleScaleHistory, historyScale); - float historyValidity = 1.0f; #if UNITY_HDRP_DXR_TESTS_DEFINE if (Application.isPlaying) @@ -764,8 +753,6 @@ void RenderPunctualScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingSampleIndex, sampleIdx); cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingNumSamples, additionalLightData.numRayTracingSamples); cmd.SetComputeFloatParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingLightRadius, additionalLightData.shapeRadius); - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingFrameIndex, frameIndex); // If this is a spot light, inject the spot angle in radians if (lightData.lightType == GPULightType.Spot) @@ -813,7 +800,7 @@ void RenderPunctualScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera GetShadowChannelMask(lightData.screenSpaceShadowIndex, ScreenSpaceShadowType.GrayScale, ref m_ShadowChannelMask0); if (additionalLightData.filterTracedShadow) { - // We need to set the history as invalid if the light has moved (rotated or translated), + // We need to set the history as invalid if the light has moved (rotated or translated), float historyValidity = 1.0f; if (additionalLightData.previousTransform != additionalLightData.transform.localToWorldMatrix || !hdCamera.ValidShadowHistory(additionalLightData, lightData.screenSpaceShadowIndex, lightData.lightType)) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index ef456c1bd33..53a2b5e79f6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -336,8 +336,6 @@ void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle c cmd.SetRayTracingFloatParams(subSurfaceShader, HDShaderIDs._RaytracingRayBias, rayTracingSettings.rayBias.value); cmd.SetRayTracingIntParams(subSurfaceShader, HDShaderIDs._RaytracingNumSamples, settings.sampleCount.value); cmd.SetRayTracingIntParams(subSurfaceShader, HDShaderIDs._RaytracingSampleIndex, sampleIndex); - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetRayTracingIntParam(subSurfaceShader, HDShaderIDs._RaytracingFrameIndex, frameIndex); // Bind the textures for ray generation cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._DepthTexture, sharedRTManager.GetDepthStencilBuffer()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs index 7c6520f7f84..29be1ea3bb8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs @@ -923,13 +923,11 @@ void DoTemporalAntialiasing(CommandBuffer cmd, HDCamera camera, RTHandle source, m_TAAPropertyBlock.SetInt(HDShaderIDs._StencilMask, (int)StencilUsage.ExcludeFromTAA); m_TAAPropertyBlock.SetInt(HDShaderIDs._StencilRef, (int)StencilUsage.ExcludeFromTAA); - m_TAAPropertyBlock.SetVector(HDShaderIDs._RTHandleScaleHistory, camera.historyRTHandleProperties.rtHandleScale); m_TAAPropertyBlock.SetTexture(HDShaderIDs._InputTexture, source); m_TAAPropertyBlock.SetTexture(HDShaderIDs._InputHistoryTexture, prevHistory); CoreUtils.SetRenderTarget(cmd, destination, depthBuffer); cmd.SetRandomWriteTarget(1, nextHistory); - cmd.SetGlobalVector(HDShaderIDs._RTHandleScale, destination.rtHandleProperties.rtHandleScale); // <- above blits might have changed the scale cmd.DrawProcedural(Matrix4x4.identity, m_TemporalAAMaterial, 0, MeshTopology.Triangles, 3, 1, m_TAAPropertyBlock); cmd.DrawProcedural(Matrix4x4.identity, m_TemporalAAMaterial, 1, MeshTopology.Triangles, 3, 1, m_TAAPropertyBlock); cmd.ClearRandomWriteTargets(); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 0473410955a..798b05597fc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -81,10 +81,6 @@ static class HDShaderIDs public static readonly int _AreaLightShadowmapAtlas = Shader.PropertyToID("_AreaShadowmapAtlas"); public static readonly int _AreaShadowmapMomentAtlas = Shader.PropertyToID("_AreaShadowmapMomentAtlas"); public static readonly int _ShadowmapCascadeAtlas = Shader.PropertyToID("_ShadowmapCascadeAtlas"); - public static readonly int _AreaShadowAtlasSize = Shader.PropertyToID("_AreaShadowAtlasSize"); - public static readonly int _ShadowAtlasSize = Shader.PropertyToID("_ShadowAtlasSize"); - public static readonly int _CascadeShadowAtlasSize = Shader.PropertyToID("_CascadeShadowAtlasSize"); - public static readonly int _CascadeShadowCount = Shader.PropertyToID("_CascadeShadowCount"); // Moment shadow map data public static readonly int _MomentShadowAtlas = Shader.PropertyToID("_MomentShadowAtlas"); @@ -108,13 +104,7 @@ static class HDShaderIDs public static readonly int g_mScrProjectionArr = Shader.PropertyToID("g_mScrProjectionArr"); public static readonly int g_mInvScrProjectionArr = Shader.PropertyToID("g_mInvScrProjectionArr"); - public static readonly int g_iLog2NumClusters = Shader.PropertyToID("g_iLog2NumClusters"); - public static readonly int g_screenSize = Shader.PropertyToID("g_screenSize"); public static readonly int g_iNumSamplesMSAA = Shader.PropertyToID("g_iNumSamplesMSAA"); - public static readonly int g_fNearPlane = Shader.PropertyToID("g_fNearPlane"); - public static readonly int g_fFarPlane = Shader.PropertyToID("g_fFarPlane"); - public static readonly int g_fClustScale = Shader.PropertyToID("g_fClustScale"); - public static readonly int g_fClustBase = Shader.PropertyToID("g_fClustBase"); public static readonly int g_depth_tex = Shader.PropertyToID("g_depth_tex"); public static readonly int g_vLayeredLightList = Shader.PropertyToID("g_vLayeredLightList"); public static readonly int g_LayeredOffset = Shader.PropertyToID("g_LayeredOffset"); @@ -141,33 +131,15 @@ static class HDShaderIDs public static readonly int _NumTiles = Shader.PropertyToID("_NumTiles"); public static readonly int _CookieAtlas = Shader.PropertyToID("_CookieAtlas"); - public static readonly int _CookieAtlasSize = Shader.PropertyToID("_CookieAtlasSize"); - public static readonly int _CookieAtlasData = Shader.PropertyToID("_CookieAtlasData"); public static readonly int _CookieCubeTextures = Shader.PropertyToID("_CookieCubeTextures"); - public static readonly int _PlanarAtlasData = Shader.PropertyToID("_PlanarAtlasData"); public static readonly int _EnvCubemapTextures = Shader.PropertyToID("_EnvCubemapTextures"); - public static readonly int _EnvSliceSize = Shader.PropertyToID("_EnvSliceSize"); public static readonly int _Env2DTextures = Shader.PropertyToID("_Env2DTextures"); - public static readonly int _Env2DCaptureVP = Shader.PropertyToID("_Env2DCaptureVP"); - public static readonly int _Env2DCaptureForward = Shader.PropertyToID("_Env2DCaptureForward"); - public static readonly int _Env2DAtlasScaleOffset = Shader.PropertyToID("_Env2DAtlasScaleOffset"); public static readonly int _DirectionalLightDatas = Shader.PropertyToID("_DirectionalLightDatas"); - public static readonly int _DirectionalLightCount = Shader.PropertyToID("_DirectionalLightCount"); public static readonly int _LightDatas = Shader.PropertyToID("_LightDatas"); - public static readonly int _PunctualLightCount = Shader.PropertyToID("_PunctualLightCount"); - public static readonly int _AreaLightCount = Shader.PropertyToID("_AreaLightCount"); public static readonly int _EnvLightDatas = Shader.PropertyToID("_EnvLightDatas"); - public static readonly int _EnvLightCount = Shader.PropertyToID("_EnvLightCount"); public static readonly int _NumTileBigTileX = Shader.PropertyToID("_NumTileBigTileX"); public static readonly int _NumTileBigTileY = Shader.PropertyToID("_NumTileBigTileY"); - public static readonly int _NumTileFtplX = Shader.PropertyToID("_NumTileFtplX"); - public static readonly int _NumTileFtplY = Shader.PropertyToID("_NumTileFtplY"); - public static readonly int _NumTileClusteredX = Shader.PropertyToID("_NumTileClusteredX"); - public static readonly int _NumTileClusteredY = Shader.PropertyToID("_NumTileClusteredY"); - public static readonly int _IndirectLightingMultiplier = Shader.PropertyToID("_IndirectLightingMultiplier"); - - public static readonly int g_isLogBaseBufferEnabled = Shader.PropertyToID("g_isLogBaseBufferEnabled"); public static readonly int g_vLayeredOffsetsBuffer = Shader.PropertyToID("g_vLayeredOffsetsBuffer"); public static readonly int _LightListToClear = Shader.PropertyToID("_LightListToClear"); @@ -208,15 +180,6 @@ static class HDShaderIDs public static readonly int _UseTileLightList = Shader.PropertyToID("_UseTileLightList"); - public static readonly int _FrameCount = Shader.PropertyToID("_FrameCount"); - public static readonly int _Time = Shader.PropertyToID("_Time"); - public static readonly int _SinTime = Shader.PropertyToID("_SinTime"); - public static readonly int _CosTime = Shader.PropertyToID("_CosTime"); - public static readonly int unity_DeltaTime = Shader.PropertyToID("unity_DeltaTime"); - public static readonly int _TimeParameters = Shader.PropertyToID("_TimeParameters"); - public static readonly int _LastTimeParameters = Shader.PropertyToID("_LastTimeParameters"); - - public static readonly int _EnvLightSkyEnabled = Shader.PropertyToID("_EnvLightSkyEnabled"); public static readonly int _SkyTexture = Shader.PropertyToID("_SkyTexture"); public static readonly int specularLightingUAV = Shader.PropertyToID("specularLightingUAV"); @@ -234,13 +197,9 @@ static class HDShaderIDs public static readonly int _ScreenSpaceShadowsTexture = Shader.PropertyToID("_ScreenSpaceShadowsTexture"); public static readonly int _ContactShadowTexture = Shader.PropertyToID("_ContactShadowTexture"); public static readonly int _ContactShadowTextureUAV = Shader.PropertyToID("_ContactShadowTextureUAV"); - public static readonly int _DirectionalShadowIndex = Shader.PropertyToID("_DirectionalShadowIndex"); - public static readonly int _ContactShadowOpacity = Shader.PropertyToID("_ContactShadowOpacity"); public static readonly int _ContactShadowParamsParameters = Shader.PropertyToID("_ContactShadowParamsParameters"); public static readonly int _ContactShadowParamsParameters2 = Shader.PropertyToID("_ContactShadowParamsParameters2"); public static readonly int _DirectionalContactShadowSampleCount = Shader.PropertyToID("_SampleCount"); - public static readonly int _MicroShadowOpacity = Shader.PropertyToID("_MicroShadowOpacity"); - public static readonly int _DirectionalTransmissionMultiplier = Shader.PropertyToID("_DirectionalTransmissionMultiplier"); public static readonly int _ShadowClipPlanes = Shader.PropertyToID("_ShadowClipPlanes"); public static readonly int _StencilMask = Shader.PropertyToID("_StencilMask"); @@ -267,7 +226,6 @@ static class HDShaderIDs public static readonly int _DecalAtlas2DID = Shader.PropertyToID("_DecalAtlas2D"); public static readonly int _DecalHTileTexture = Shader.PropertyToID("_DecalHTileTexture"); public static readonly int _DecalIndexShift = Shader.PropertyToID("_DecalIndexShift"); - public static readonly int _DecalCount = Shader.PropertyToID("_DecalCount"); public static readonly int _DecalDatas = Shader.PropertyToID("_DecalDatas"); public static readonly int _DecalNormalBufferStencilReadMask = Shader.PropertyToID("_DecalNormalBufferStencilReadMask"); public static readonly int _DecalNormalBufferStencilRef = Shader.PropertyToID("_DecalNormalBufferStencilRef"); @@ -278,7 +236,6 @@ static class HDShaderIDs public static readonly int _ViewMatrix1 = Shader.PropertyToID("_ViewMatrix1"); // XR View Constants - public static readonly int _XRViewCount = Shader.PropertyToID("_XRViewCount"); public static readonly int _XRViewMatrix = Shader.PropertyToID("_XRViewMatrix"); public static readonly int _XRInvViewMatrix = Shader.PropertyToID("_XRInvViewMatrix"); public static readonly int _XRProjMatrix = Shader.PropertyToID("_XRProjMatrix"); @@ -303,9 +260,6 @@ static class HDShaderIDs public static readonly int _CameraFilteringBuffer = Shader.PropertyToID("_CameraFilteringTexture"); public static readonly int _IrradianceSource = Shader.PropertyToID("_IrradianceSource"); - public static readonly int _EnableDecals = Shader.PropertyToID("_EnableDecals"); - public static readonly int _DecalAtlasResolution = Shader.PropertyToID("_DecalAtlasResolution"); - // MSAA shader properties public static readonly int _ColorTextureMS = Shader.PropertyToID("_ColorTextureMS"); public static readonly int _DepthTextureMS = Shader.PropertyToID("_DepthTextureMS"); @@ -351,9 +305,6 @@ static class HDShaderIDs public static readonly int _SSSBufferTexture = Shader.PropertyToID("_SSSBufferTexture"); public static readonly int _NormalBufferTexture = Shader.PropertyToID("_NormalBufferTexture"); - public static readonly int _EnableSSRefraction = Shader.PropertyToID("_EnableSSRefraction"); - public static readonly int _SSRefractionInvScreenWeightDistance = Shader.PropertyToID("_SSRefractionInvScreenWeightDistance"); - public static readonly int _SsrIterLimit = Shader.PropertyToID("_SsrIterLimit"); public static readonly int _SsrThicknessScale = Shader.PropertyToID("_SsrThicknessScale"); public static readonly int _SsrThicknessBias = Shader.PropertyToID("_SsrThicknessBias"); @@ -399,7 +350,6 @@ static class HDShaderIDs public static readonly int _BlitPaddingSize = Shader.PropertyToID("_BlitPaddingSize"); public static readonly int _BlitTexArraySlice = Shader.PropertyToID("_BlitTexArraySlice"); - public static readonly int _WorldScales = Shader.PropertyToID("_WorldScales"); public static readonly int _FilterKernels = Shader.PropertyToID("_FilterKernels"); public static readonly int _FilterKernelsBasic = Shader.PropertyToID("_FilterKernelsBasic"); public static readonly int _HalfRcpWeightedVariances = Shader.PropertyToID("_HalfRcpWeightedVariances"); @@ -457,10 +407,6 @@ static class HDShaderIDs public static readonly int _VolumeData = Shader.PropertyToID("_VolumeData"); public static readonly int _VolumeMaskAtlas = Shader.PropertyToID("_VolumeMaskAtlas"); - public static readonly int _EnableLightLayers = Shader.PropertyToID("_EnableLightLayers"); - public static readonly int _ReplaceDiffuseForIndirect = Shader.PropertyToID("_ReplaceDiffuseForIndirect"); - public static readonly int _EnableSkyReflection = Shader.PropertyToID("_EnableSkyReflection"); - public static readonly int _GroundIrradianceTexture = Shader.PropertyToID("_GroundIrradianceTexture"); public static readonly int _GroundIrradianceTable = Shader.PropertyToID("_GroundIrradianceTable"); public static readonly int _GroundIrradianceTableOrder = Shader.PropertyToID("_GroundIrradianceTableOrder"); @@ -528,7 +474,6 @@ static class HDShaderIDs public static readonly int _RaytracingSampleIndex = Shader.PropertyToID("_RaytracingSampleIndex"); public static readonly int _RaytracingRayMaxLength = Shader.PropertyToID("_RaytracingRayMaxLength"); public static readonly int _PixelSpreadAngleTangent = Shader.PropertyToID("_PixelSpreadAngleTangent"); - public static readonly int _RaytracingFrameIndex = Shader.PropertyToID("_RaytracingFrameIndex"); public static readonly int _RaytracingPixelSpreadAngle = Shader.PropertyToID("_RaytracingPixelSpreadAngle"); public static readonly string _RaytracingAccelerationStructureName = "_RaytracingAccelerationStructure"; @@ -580,7 +525,6 @@ static class HDShaderIDs public static readonly int _RaytracingReflectionSmoothnessFadeStart = Shader.PropertyToID("_RaytracingReflectionSmoothnessFadeStart"); public static readonly int _RaytracingVSNormalTexture = Shader.PropertyToID("_RaytracingVSNormalTexture"); public static readonly int _RaytracingIncludeSky = Shader.PropertyToID("_RaytracingIncludeSky"); - public static readonly int _UseRayTracedReflections = Shader.PropertyToID("_UseRayTracedReflections"); // Shadows public static readonly int _RaytracingTargetAreaLight = Shader.PropertyToID("_RaytracingTargetAreaLight"); @@ -628,7 +572,6 @@ static class HDShaderIDs public static readonly int _RaytracingCameraClearColor = Shader.PropertyToID("_RaytracingCameraClearColor"); // Indirect diffuse - public static readonly int _RaytracedIndirectDiffuse = Shader.PropertyToID("_RaytracedIndirectDiffuse"); public static readonly int _IndirectDiffuseTexture = Shader.PropertyToID("_IndirectDiffuseTexture"); public static readonly int _IndirectDiffuseTextureRW = Shader.PropertyToID("_IndirectDiffuseTextureRW"); public static readonly int _IndirectDiffuseHitPointTextureRW = Shader.PropertyToID("_IndirectDiffuseHitPointTextureRW"); @@ -660,7 +603,6 @@ static class HDShaderIDs public static readonly int _ExposureParams = Shader.PropertyToID("_ExposureParams"); public static readonly int _AdaptationParams = Shader.PropertyToID("_AdaptationParams"); public static readonly int _ExposureCurveTexture = Shader.PropertyToID("_ExposureCurveTexture"); - public static readonly int _ProbeExposureScale = Shader.PropertyToID("_ProbeExposureScale"); public static readonly int _Variants = Shader.PropertyToID("_Variants"); public static readonly int _InputTexture = Shader.PropertyToID("_InputTexture"); public static readonly int _OutputTexture = Shader.PropertyToID("_OutputTexture"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs index 4c6c876685d..28c0afce6dd 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs @@ -94,8 +94,6 @@ public void RenderAO(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputTextur // Set the data for the ray generation cmd.SetRayTracingTextureParam(aoShader, HDShaderIDs._DepthTexture, m_RenderPipeline.sharedRTManager.GetDepthStencilBuffer()); cmd.SetRayTracingTextureParam(aoShader, HDShaderIDs._NormalBufferTexture, m_RenderPipeline.sharedRTManager.GetNormalBuffer()); - int frameIndex = m_RenderPipeline.RayTracingFrameIndex(hdCamera); - cmd.SetRayTracingIntParam(aoShader, HDShaderIDs._RaytracingFrameIndex, frameIndex); // Inject the ray-tracing sampling data BlueNoise blueNoise = m_RenderPipeline.GetBlueNoiseManager(); @@ -148,7 +146,6 @@ public void RenderAO(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputTextur // Bind the textures and the params cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, outputTexture); - cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, new Vector4(0f, 0f, 0f, hdCamera.volumeStack.GetComponent().directLightingStrength.value)); // TODO: All the push-debug stuff should be centralized somewhere (RenderPipelineManager.currentPipeline as HDRenderPipeline).PushFullScreenDebugTexture(hdCamera, cmd, outputTexture, FullScreenDebugMode.SSAO); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs index 541e2e6a399..5653813af57 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs @@ -87,7 +87,6 @@ void RenderIndirectDiffuse(HDCamera hdCamera, CommandBuffer cmd, ScriptableRende // Bind the output texture cmd.SetComputeTextureParam(indirectDiffuseCS, indirectDiffuseKernel, HDShaderIDs._GBufferTexture[0], m_GbufferManager.GetBuffer(0)); cmd.SetComputeTextureParam(indirectDiffuseCS, indirectDiffuseKernel, HDShaderIDs._GBufferTexture[3], m_GbufferManager.GetBuffer(3)); - cmd.SetComputeVectorParam(indirectDiffuseCS, HDShaderIDs._IndirectLightingMultiplier, new Vector4(hdCamera.volumeStack.GetComponent().indirectDiffuseIntensity.value, 0, 0, 0)); // Evaluate the dispatch parameters int areaTileSize = 8; @@ -184,10 +183,6 @@ void RenderIndirectDiffusePerformance(HDCamera hdCamera, CommandBuffer cmd, Scri // Bind all the required scalars cmd.SetComputeFloatParam(indirectDiffuseCS, HDShaderIDs._RaytracingIntensityClamp, settings.clampValue.value); - // Bind the sampling data - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetComputeIntParam(indirectDiffuseCS, HDShaderIDs._RaytracingFrameIndex, frameIndex); - // Bind the output buffers cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._RaytracingDirectionBuffer, directionBuffer); @@ -272,8 +267,6 @@ void BindRayTracedIndirectDiffuseData(CommandBuffer cmd, HDCamera hdCamera cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rtSettings.rayBias.value); cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, settings.rayLength.value); cmd.SetRayTracingIntParams(indirectDiffuseShader, HDShaderIDs._RaytracingNumSamples, settings.sampleCount.value); - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); // Set the data for the ray generation cmd.SetRayTracingTextureParam(indirectDiffuseShader, HDShaderIDs._IndirectDiffuseTextureRW, outputLightingBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs index 52eb12c4f0a..812a7433797 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs @@ -134,7 +134,7 @@ void RaytracingRecursiveRender(HDCamera hdCamera, CommandBuffer cmd, ScriptableR RayCountManager rayCountManager = GetRayCountManager(); cmd.SetRayTracingIntParam(forwardShader, HDShaderIDs._RayCountEnabled, rayCountManager.RayCountIsEnabled()); cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._RayCountTexture, rayCountManager.GetRayCountTexture()); - + // Compute an approximate pixel spread angle value (in radians) cmd.SetGlobalFloat(HDShaderIDs._RaytracingPixelSpreadAngle, GetPixelSpreadAngle(hdCamera.camera.fieldOfView, hdCamera.actualWidth, hdCamera.actualHeight)); @@ -149,7 +149,6 @@ void RaytracingRecursiveRender(HDCamera hdCamera, CommandBuffer cmd, ScriptableR // Note: Just in case, we rebind the directional light data (in case they were not) cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, m_LightLoopLightData.directionalLightData); - cmd.SetGlobalInt(HDShaderIDs._DirectionalLightCount, m_lightList.directionalLights.Count); // Set the data for the ray miss cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._SkyTexture, m_SkyManager.GetSkyReflection(hdCamera)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs index e6e41e1fce8..2e33623f43e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs @@ -67,8 +67,6 @@ void BindRayTracedReflectionData(CommandBuffer cmd, HDCamera hdCamera, RayTracin cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rtSettings.rayBias.value); cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, settings.rayLength.value); cmd.SetRayTracingIntParams(reflectionShader, HDShaderIDs._RaytracingNumSamples, settings.sampleCount.value); - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetRayTracingIntParam(reflectionShader, HDShaderIDs._RaytracingFrameIndex, frameIndex); // Inject the ray-tracing sampling data blueNoise.BindDitheredRNGData8SPP(cmd); @@ -80,7 +78,7 @@ void BindRayTracedReflectionData(CommandBuffer cmd, HDCamera hdCamera, RayTracin cmd.SetRayTracingTextureParam(reflectionShader, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); cmd.SetGlobalTexture(HDShaderIDs._StencilTexture, sharedRTManager.GetDepthStencilBuffer(), RenderTextureSubElement.Stencil); cmd.SetRayTracingIntParams(reflectionShader, HDShaderIDs._SsrStencilBit, (int)StencilUsage.TraceReflectionRay); - + // Set ray count tex RayCountManager rayCountManager = GetRayCountManager(); cmd.SetRayTracingIntParam(reflectionShader, HDShaderIDs._RayCountEnabled, rayCountManager.RayCountIsEnabled()); @@ -94,7 +92,6 @@ void BindRayTracedReflectionData(CommandBuffer cmd, HDCamera hdCamera, RayTracin // Note: Just in case, we rebind the directional light data (in case they were not) cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, m_LightLoopLightData.directionalLightData); - cmd.SetGlobalInt(HDShaderIDs._DirectionalLightCount, m_lightList.directionalLights.Count); // Evaluate the clear coat mask texture based on the lit shader mode RenderTargetIdentifier clearCoatMaskTexture = hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred ? m_GbufferManager.GetBuffersRTI()[2] : TextureXR.GetBlackTexture(); @@ -204,10 +201,6 @@ void RenderReflectionsPerformance(HDCamera hdCamera, CommandBuffer cmd, RTHandle cmd.SetComputeFloatParam(reflectionShaderCS, HDShaderIDs._RaytracingReflectionMinSmoothness, settings.minSmoothness.value); cmd.SetComputeIntParam(reflectionShaderCS, HDShaderIDs._RaytracingIncludeSky, settings.reflectSky.value ? 1 : 0); - // Bind the sampling data - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetComputeIntParam(reflectionShaderCS, HDShaderIDs._RaytracingFrameIndex, frameIndex); - // Bind the output buffers cmd.SetComputeTextureParam(reflectionShaderCS, currentKernel, HDShaderIDs._RaytracingDirectionBuffer, intermediateBuffer1); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDReflectionDenoiser.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDReflectionDenoiser.cs index 78068d69490..01ae49b008f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDReflectionDenoiser.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDReflectionDenoiser.cs @@ -57,8 +57,6 @@ public void DenoiseBuffer(CommandBuffer cmd, HDCamera hdCamera, int maxKernelSiz RTHandle intermediateBuffer1 = m_RenderPipeline.GetRayTracingBuffer(InternalRayTracingBuffers.RGBA1); // Apply a vectorized temporal filtering pass and store it back in the denoisebuffer0 with the analytic value in the third channel - var historyScale = new Vector2(hdCamera.actualWidth / (float)historySignal.rt.width, hdCamera.actualHeight / (float)historySignal.rt.height); - cmd.SetComputeVectorParam(m_ReflectionDenoiserCS, HDShaderIDs._RTHandleScaleHistory, historyScale); cmd.SetComputeTextureParam(m_ReflectionDenoiserCS, s_TemporalAccumulationKernel, HDShaderIDs._DenoiseInputTexture, noisySignal); cmd.SetComputeTextureParam(m_ReflectionDenoiserCS, s_TemporalAccumulationKernel, HDShaderIDs._HistoryBuffer, historySignal); cmd.SetComputeTextureParam(m_ReflectionDenoiserCS, s_TemporalAccumulationKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDSimpleDenoiser.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDSimpleDenoiser.cs index 202422550c9..386def8a397 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDSimpleDenoiser.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDSimpleDenoiser.cs @@ -57,9 +57,6 @@ public void DenoiseBuffer(CommandBuffer cmd, HDCamera hdCamera, RTHandle noisySi RTHandle intermediateBuffer1 = m_RenderPipeline.GetRayTracingBuffer(InternalRayTracingBuffers.RGBA1); // Apply a vectorized temporal filtering pass and store it back in the denoisebuffer0 with the analytic value in the third channel - var historyScale = new Vector2(hdCamera.actualWidth / (float)historySignal.rt.width, hdCamera.actualHeight / (float)historySignal.rt.height); - cmd.SetComputeVectorParam(m_SimpleDenoiserCS, HDShaderIDs._RTHandleScaleHistory, historyScale); - cmd.SetComputeTextureParam(m_SimpleDenoiserCS, m_KernelFilter, HDShaderIDs._DenoiseInputTexture, noisySignal); cmd.SetComputeTextureParam(m_SimpleDenoiserCS, m_KernelFilter, HDShaderIDs._HistoryBuffer, historySignal); cmd.SetComputeTextureParam(m_SimpleDenoiserCS, m_KernelFilter, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDTemporalFilter.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDTemporalFilter.cs index d8b2472f1dc..d37dbbc6bb7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDTemporalFilter.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDTemporalFilter.cs @@ -17,7 +17,7 @@ public HDTemporalFilter() } public void Init(HDRenderPipelineRayTracingResources rpRTResources, SharedRTManager sharedRTManager, HDRenderPipeline renderPipeline) - { + { // Keep track of the resources m_TemporalFilterCS = rpRTResources.temporalFilterCS; @@ -33,7 +33,7 @@ public void Release() // Denoiser variant for non history array public void DenoiseBuffer(CommandBuffer cmd, HDCamera hdCamera, RTHandle noisySignal, RTHandle historySignal, - RTHandle outputSignal, + RTHandle outputSignal, bool singleChannel = true, float historyValidity = 1.0f) { // If we do not have a depth and normal history buffers, we can skip right away @@ -60,8 +60,6 @@ public void DenoiseBuffer(CommandBuffer cmd, HDCamera hdCamera, // First of all we need to validate the history to know where we can or cannot use the history signal int m_KernelFilter = m_TemporalFilterCS.FindKernel("ValidateHistory"); - var historyScale = new Vector2(hdCamera.actualWidth / (float)historySignal.rt.width, hdCamera.actualHeight / (float)historySignal.rt.height); - cmd.SetComputeVectorParam(m_TemporalFilterCS, HDShaderIDs._RTHandleScaleHistory, historyScale); cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._HistoryDepthTexture, historyDepthBuffer); cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); @@ -119,8 +117,6 @@ public void DenoiseBuffer(CommandBuffer cmd, HDCamera hdCamera, // First of all we need to validate the history to know where we can or cannot use the history signal int m_KernelFilter = m_TemporalFilterCS.FindKernel("ValidateHistory"); - var historyScale = new Vector2(hdCamera.actualWidth / (float)historySignal.rt.width, hdCamera.actualHeight / (float)historySignal.rt.height); - cmd.SetComputeVectorParam(m_TemporalFilterCS, HDShaderIDs._RTHandleScaleHistory, historyScale); cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._HistoryDepthTexture, historyDepthBuffer); cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs index 81baff8a80d..7296cf5355e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs @@ -335,7 +335,6 @@ public static void DrawFullScreen(CommandBuffer commandBuffer, Material material MaterialPropertyBlock properties = null, int shaderPassId = 0) { CoreUtils.SetRenderTarget(commandBuffer, colorBuffer); - commandBuffer.SetGlobalVector(HDShaderIDs._RTHandleScale, colorBuffer.rtHandleProperties.rtHandleScale); commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties); } @@ -354,7 +353,6 @@ public static void DrawFullScreen(CommandBuffer commandBuffer, Material material MaterialPropertyBlock properties = null, int shaderPassId = 0) { CoreUtils.SetRenderTarget(commandBuffer, colorBuffer, depthStencilBuffer); - commandBuffer.SetGlobalVector(HDShaderIDs._RTHandleScale, colorBuffer.rtHandleProperties.rtHandleScale); commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties); } @@ -373,7 +371,6 @@ public static void DrawFullScreen(CommandBuffer commandBuffer, Material material MaterialPropertyBlock properties = null, int shaderPassId = 0) { CoreUtils.SetRenderTarget(commandBuffer, colorBuffers, depthStencilBuffer); - commandBuffer.SetGlobalVector(HDShaderIDs._RTHandleScale, depthStencilBuffer.rtHandleProperties.rtHandleScale); commandBuffer.DrawProcedural(Matrix4x4.identity, material, shaderPassId, MeshTopology.Triangles, 3, 1, properties); } From 5f79288c14933d09c078e5a549c8e999b967e8f0 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 12 Mar 2020 16:58:20 +0100 Subject: [PATCH 39/92] Light list build global CB implementation --- .../ShaderGenerator/ShaderTypeGeneration.cs | 14 ++ .../Runtime/Lighting/LightLoop/LightLoop.cs | 220 ++++++++---------- .../Lighting/LightLoop/LightLoop.cs.hlsl | 19 ++ .../LightLoop/lightlistbuild-bigtile.compute | 12 +- .../lightlistbuild-clustered.compute | 23 +- .../Lighting/LightLoop/lightlistbuild.compute | 8 - .../Lighting/LightLoop/materialflags.compute | 5 - .../Lighting/LightLoop/scrbound.compute | 6 - .../VolumetricLighting/VolumetricLighting.cs | 15 +- .../VolumetricLighting.cs.hlsl | 2 - .../RenderPipeline/HDRenderPipeline.cs | 2 - .../RenderPipeline/HDStringConstants.cs | 14 +- .../ShaderLibrary/ShaderVariables.hlsl | 4 +- 13 files changed, 143 insertions(+), 201 deletions(-) diff --git a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs index 3ace8f04abb..3cc6d9b5d75 100644 --- a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs +++ b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs @@ -770,6 +770,10 @@ private string EmitPackedGetters() { funcSignature = "float4 " + funcSignature; } + else if (packedInfo.fieldType == typeof(Vector2Int)) + { + funcSignature = "int2 " + funcSignature; + } funcBody += "return (" + sourceName + "." + packedInfo.fieldName + ");"; break; default: @@ -856,6 +860,10 @@ private string EmitPackedSetters() { funcSignature += "float4 " + newParamName + ", inout " + type.Name + " " + sourceName + ")"; } + else if (packedInfo.fieldType == typeof(Vector2Int)) + { + funcSignature += "int2 " + newParamName + ", inout " + type.Name + " " + sourceName + ")"; + } funcBody += sourceName + "." + packedInfo.fieldName + " = " + newParamName + ";"; break; default: @@ -945,6 +953,10 @@ private string EmitPackedInit() { funcSignature += "float4 " + newParamName + ", inout " + type.Name + " " + sourceName + ")"; } + else if (packedInfo.fieldType == typeof(Vector2Int)) + { + funcSignature += "int2 " + newParamName + ", inout " + type.Name + " " + sourceName + ")"; + } funcBody += sourceName + "." + packedInfo.fieldName + " = " + newParamName + ";"; break; default: @@ -1187,6 +1199,8 @@ public bool Generate() EmitPrimitiveType(floatPrecision, 3, arraySize, field.Name, "", m_ShaderFields); else if (fieldType == typeof(Vector4)) EmitPrimitiveType(floatPrecision, 4, arraySize, field.Name, "", m_ShaderFields); + else if (fieldType == typeof(Vector2Int)) + EmitPrimitiveType(PrimitiveType.Int, 2, arraySize, field.Name, "", m_ShaderFields); else if (fieldType == typeof(ShaderGenUInt4)) EmitPrimitiveType(PrimitiveType.UInt, 4, arraySize, field.Name, "", m_ShaderFields); else if (fieldType == typeof(Matrix4x4)) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index eb2815ed18b..b3d033d72ee 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -186,6 +186,32 @@ public enum TileClusterCategoryDebug : int DensityVolumes = 16 }; + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + unsafe struct ShaderVariablesLightList + { + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float g_mInvScrProjectionArr[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float g_mScrProjectionArr[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float g_mInvProjectionArr[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float g_mProjectionArr[(int)ShaderOptions.XrMaxViews * 16]; + + public Vector4 g_screenSize; + + public Vector2Int g_viDimensions; + public int g_iNrVisibLights; + public uint g_isOrthographic; + + public uint g_BaseFeatureFlags; + public int g_iNumSamplesMSAA; + public int _EnvLightIndexShift; + public int _DecalIndexShift; + + public int _DensityVolumeIndexShift; + } + internal struct ProcessedLightData { public HDAdditionalLightData additionalLightData; @@ -449,8 +475,6 @@ void UpdateSortKeysArray(int count) } } - - static readonly Matrix4x4 s_FlipMatrixLHSRHS = Matrix4x4.Scale(new Vector3(1, 1, -1)); Matrix4x4 GetWorldToViewMatrix(HDCamera hdCamera, int viewIndex) @@ -466,10 +490,6 @@ Matrix4x4 GetWorldToViewMatrix(HDCamera hdCamera, int viewIndex) // Matrix used for LightList building, keep them around to avoid GC Matrix4x4[] m_LightListProjMatrices = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_LightListProjscrMatrices = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_LightListInvProjscrMatrices = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_LightListProjHMatrices = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_LightListInvProjHMatrices = new Matrix4x4[ShaderConfig.s_XrMaxViews]; internal class LightList { @@ -535,6 +555,7 @@ public void Allocate() Shader deferredTilePixelShader { get { return defaultResources.shaders.deferredTilePS; } } + ConstantBuffer m_ShaderVariablesLightListCB; static int s_GenAABBKernel; static int s_GenAABBKernel_Oblique; @@ -608,8 +629,6 @@ enum ClusterDepthSource : int }; // clustered light list specific buffers and data end - static int[] s_TempScreenDimArray = new int[2]; // Used to avoid GC stress when calling SetComputeIntParams - ContactShadows m_ContactShadows = null; bool m_EnableContactShadow = false; @@ -867,6 +886,8 @@ void InitializeLightLoop(IBLFilterBSDF[] iBLFilterBSDFArray) // Screen space shadow int numMaxShadows = Math.Max(m_Asset.currentPlatformRenderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots, 1); m_CurrentScreenSpaceShadowData = new ScreenSpaceShadowData[numMaxShadows]; + + m_ShaderVariablesLightListCB = new ConstantBuffer(); } void CleanupLightLoop() @@ -903,6 +924,8 @@ void CleanupLightLoop() CoreUtils.Destroy(m_DebugViewTilesMaterial); CoreUtils.Destroy(m_DebugHDShadowMapMaterial); CoreUtils.Destroy(m_DebugBlitMaterial); + + m_ShaderVariablesLightListCB.Release(); } void LightLoopNewRender() @@ -2578,10 +2601,6 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu } UpdateDataBuffers(); - - cmd.SetGlobalInt(HDShaderIDs._EnvLightIndexShift, m_lightList.lights.Count); - cmd.SetGlobalInt(HDShaderIDs._DecalIndexShift, m_lightList.lights.Count + m_lightList.envLights.Count); - cmd.SetGlobalInt(HDShaderIDs._DensityVolumeIndexShift, m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount); } m_enableBakeShadowMask = m_enableBakeShadowMask && hdCamera.frameSettings.IsEnabled(FrameSettingsField.Shadowmask); @@ -2659,7 +2678,6 @@ struct BuildGPULightListParameters { // Common public int totalLightCount; // Regular + Env + Decal + Density Volumes - public bool isOrthographic; public int viewCount; public bool runLightList; public bool clearLightLists; @@ -2668,11 +2686,6 @@ struct BuildGPULightListParameters public bool computeLightVariants; public bool skyEnabled; public LightList lightList; - public Matrix4x4[] lightListProjscrMatrices; - public Matrix4x4[] lightListInvProjscrMatrices; - public float nearClipPlane, farClipPlane; - public Vector4 screenSize; - public int msaaSamples; // Clear Light lists public ComputeShader clearLightListCS; @@ -2681,8 +2694,6 @@ struct BuildGPULightListParameters // Screen Space AABBs public ComputeShader screenSpaceAABBShader; public int screenSpaceAABBKernel; - public Matrix4x4[] lightListProjHMatrices; - public Matrix4x4[] lightListInvProjHMatrices; // Big Tile public ComputeShader bigTilePrepassShader; @@ -2703,13 +2714,14 @@ struct BuildGPULightListParameters public int buildPerVoxelLightListKernel; public int numTilesClusterX; public int numTilesClusterY; - public float clusterScale; // Build dispatch indirect public ComputeShader buildMaterialFlagsShader; public ComputeShader clearDispatchIndirectShader; public ComputeShader buildDispatchIndirectShader; public bool useComputeAsPixel; + + public ConstantBuffer lightListCB; } struct BuildGPULightListResources @@ -2745,6 +2757,9 @@ static void ClearLightLists( in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { + // ClearLightLists is the first pass, we push the global parameters for light list building here. + parameters.lightListCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesLightList, true); + if (parameters.clearLightLists && !parameters.runLightList) { // Note we clear the whole content and not just the header since it is fast enough, happens only in one frame and is a bit more robust @@ -2770,16 +2785,9 @@ static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parame { var tileAndCluster = resources.tileAndClusterData; - cmd.SetComputeIntParam(parameters.screenSpaceAABBShader, HDShaderIDs.g_isOrthographic, parameters.isOrthographic ? 1 : 0); - // With XR single-pass, we have one set of light bounds per view to iterate over (bounds are in view space for each view) - cmd.SetComputeIntParam(parameters.screenSpaceAABBShader, HDShaderIDs.g_iNrVisibLights, parameters.totalLightCount); cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_data, tileAndCluster.convexBoundsBuffer); cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_vBoundsBuffer, tileAndCluster.AABBBoundsBuffer); - - cmd.SetComputeMatrixArrayParam(parameters.screenSpaceAABBShader, HDShaderIDs.g_mProjectionArr, parameters.lightListProjHMatrices); - cmd.SetComputeMatrixArrayParam(parameters.screenSpaceAABBShader, HDShaderIDs.g_mInvProjectionArr, parameters.lightListInvProjHMatrices); - cmd.DispatchCompute(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, (parameters.totalLightCount + 7) / 8, parameters.viewCount, 1); } } @@ -2791,19 +2799,6 @@ static void BigTilePrepass(in BuildGPULightListParameters parameters, in BuildGP { var tileAndCluster = resources.tileAndClusterData; - cmd.SetComputeIntParam(parameters.bigTilePrepassShader, HDShaderIDs.g_iNrVisibLights, parameters.totalLightCount); - cmd.SetComputeIntParam(parameters.bigTilePrepassShader, HDShaderIDs.g_isOrthographic, parameters.isOrthographic ? 1 : 0); - cmd.SetComputeIntParams(parameters.bigTilePrepassShader, HDShaderIDs.g_viDimensions, s_TempScreenDimArray); - - // TODO: These two aren't actually used... - cmd.SetComputeIntParam(parameters.bigTilePrepassShader, HDShaderIDs._EnvLightIndexShift, parameters.lightList.lights.Count); - cmd.SetComputeIntParam(parameters.bigTilePrepassShader, HDShaderIDs._DecalIndexShift, parameters.lightList.lights.Count + parameters.lightList.envLights.Count); - - cmd.SetComputeMatrixArrayParam(parameters.bigTilePrepassShader, HDShaderIDs.g_mScrProjectionArr, parameters.lightListProjscrMatrices); - cmd.SetComputeMatrixArrayParam(parameters.bigTilePrepassShader, HDShaderIDs.g_mInvScrProjectionArr, parameters.lightListInvProjscrMatrices); - - cmd.SetComputeFloatParam(parameters.bigTilePrepassShader, HDShaderIDs.g_fNearPlane, parameters.nearClipPlane); - cmd.SetComputeFloatParam(parameters.bigTilePrepassShader, HDShaderIDs.g_fFarPlane, parameters.farClipPlane); cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_vLightList, tileAndCluster.bigTileLightList); cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_vBoundsBuffer, tileAndCluster.AABBBoundsBuffer); cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs._LightVolumeData, tileAndCluster.lightVolumeDataBuffer); @@ -2820,19 +2815,10 @@ static void BuildPerTileLightList(in BuildGPULightListParameters parameters, in { var tileAndCluster = resources.tileAndClusterData; - cmd.SetComputeIntParam(parameters.buildPerTileLightListShader, HDShaderIDs.g_isOrthographic, parameters.isOrthographic ? 1 : 0); - cmd.SetComputeIntParams(parameters.buildPerTileLightListShader, HDShaderIDs.g_viDimensions, s_TempScreenDimArray); - cmd.SetComputeIntParam(parameters.buildPerTileLightListShader, HDShaderIDs._EnvLightIndexShift, parameters.lightList.lights.Count); - cmd.SetComputeIntParam(parameters.buildPerTileLightListShader, HDShaderIDs._DecalIndexShift, parameters.lightList.lights.Count + parameters.lightList.envLights.Count); - cmd.SetComputeIntParam(parameters.buildPerTileLightListShader, HDShaderIDs.g_iNrVisibLights, parameters.totalLightCount); - cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_vBoundsBuffer, tileAndCluster.AABBBoundsBuffer); cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs._LightVolumeData, tileAndCluster.lightVolumeDataBuffer); cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_data, tileAndCluster.convexBoundsBuffer); - cmd.SetComputeMatrixArrayParam(parameters.buildPerTileLightListShader, HDShaderIDs.g_mScrProjectionArr, parameters.lightListProjscrMatrices); - cmd.SetComputeMatrixArrayParam(parameters.buildPerTileLightListShader, HDShaderIDs.g_mInvScrProjectionArr, parameters.lightListInvProjscrMatrices); - cmd.SetComputeTextureParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_depth_tex, resources.depthBuffer); cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_vLightList, tileAndCluster.lightList); if (parameters.runBigTilePrepass) @@ -2853,7 +2839,9 @@ static void BuildPerTileLightList(in BuildGPULightListParameters parameters, in { baseFeatureFlags |= LightDefinitions.s_MaterialFeatureMaskFlags; } - cmd.SetComputeIntParam(parameters.buildPerTileLightListShader, HDShaderIDs.g_BaseFeatureFlags, (int)baseFeatureFlags); + parameters.lightListCB.data.g_BaseFeatureFlags = baseFeatureFlags; + parameters.lightListCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesLightList, true); + cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_TileFeatureFlags, tileAndCluster.tileFeatureFlags); tileFlagsWritten = true; } @@ -2871,22 +2859,6 @@ static void VoxelLightListGeneration(in BuildGPULightListParameters parameters, cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, tileAndCluster.globalLightListAtomic); cmd.DispatchCompute(parameters.buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, 1, 1, 1); - cmd.SetComputeIntParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_isOrthographic, parameters.isOrthographic ? 1 : 0); - cmd.SetComputeIntParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_iNrVisibLights, parameters.totalLightCount); - cmd.SetComputeMatrixArrayParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_mScrProjectionArr, parameters.lightListProjscrMatrices); - cmd.SetComputeMatrixArrayParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_mInvScrProjectionArr, parameters.lightListInvProjscrMatrices); - - cmd.SetComputeIntParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_iLog2NumClusters, k_Log2NumClusters); - - cmd.SetComputeVectorParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_screenSize, parameters.screenSize); - cmd.SetComputeIntParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_iNumSamplesMSAA, parameters.msaaSamples); - - cmd.SetComputeFloatParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_fNearPlane, parameters.nearClipPlane); - cmd.SetComputeFloatParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_fFarPlane, parameters.farClipPlane); - - cmd.SetComputeFloatParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_fClustScale, parameters.clusterScale); - cmd.SetComputeFloatParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_fClustBase, k_ClustLogBase); - cmd.SetComputeTextureParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_depth_tex, resources.depthBuffer); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_vLayeredLightList, tileAndCluster.perVoxelLightLists); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_LayeredOffset, tileAndCluster.perVoxelOffset); @@ -2941,9 +2913,9 @@ static void BuildDispatchIndirectArguments(in BuildGPULightListParameters parame baseFeatureFlags |= LightDefinitions.s_MaterialFeatureMaskFlags; } } + parameters.lightListCB.data.g_BaseFeatureFlags = baseFeatureFlags; + parameters.lightListCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesLightList, true); - cmd.SetComputeIntParam(parameters.buildMaterialFlagsShader, HDShaderIDs.g_BaseFeatureFlags, (int)baseFeatureFlags); - cmd.SetComputeIntParams(parameters.buildMaterialFlagsShader, HDShaderIDs.g_viDimensions, s_TempScreenDimArray); cmd.SetComputeBufferParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, tileAndCluster.tileFeatureFlags); for (int i = 0; i < resources.gBuffer.Length; ++i) @@ -3000,7 +2972,7 @@ static bool DeferredUseComputeAsPixel(FrameSettings frameSettings) return frameSettings.IsEnabled(FrameSettingsField.DeferredTile) && (!frameSettings.IsEnabled(FrameSettingsField.ComputeLightEvaluation) || k_PreferFragment); } - BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera hdCamera) + unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera hdCamera) { BuildGPULightListParameters parameters = new BuildGPULightListParameters(); @@ -3009,55 +2981,78 @@ BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera hdCamera var w = (int)hdCamera.screenSize.x; var h = (int)hdCamera.screenSize.y; - s_TempScreenDimArray[0] = w; - s_TempScreenDimArray[1] = h; - - parameters.runLightList = m_TotalLightCount > 0; - parameters.clearLightLists = false; - - // Always build the light list in XR mode to avoid issues with multi-pass - if (hdCamera.xr.enabled) - { - parameters.runLightList = true; - } - else if(!parameters.runLightList && !m_TileAndClusterData.listsAreClear) - { - parameters.clearLightLists = true; - } - + // Fill the shared constant buffer. + var cb = m_ShaderVariablesLightListCB; var temp = new Matrix4x4(); temp.SetRow(0, new Vector4(0.5f * w, 0.0f, 0.0f, 0.5f * w)); temp.SetRow(1, new Vector4(0.0f, 0.5f * h, 0.0f, 0.5f * h)); temp.SetRow(2, new Vector4(0.0f, 0.0f, 0.5f, 0.5f)); temp.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); - parameters.lightListProjscrMatrices = m_LightListProjscrMatrices; - parameters.lightListInvProjscrMatrices = m_LightListInvProjscrMatrices; - parameters.lightListProjHMatrices = m_LightListProjHMatrices; - parameters.lightListInvProjHMatrices = m_LightListInvProjHMatrices; - // camera to screen matrix (and it's inverse) for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) { var proj = hdCamera.xr.enabled ? hdCamera.xr.GetProjMatrix(viewIndex) : camera.projectionMatrix; - m_LightListProjMatrices[viewIndex] = proj * s_FlipMatrixLHSRHS; - parameters.lightListProjscrMatrices[viewIndex] = temp * m_LightListProjMatrices[viewIndex]; - parameters.lightListInvProjscrMatrices[viewIndex] = parameters.lightListProjscrMatrices[viewIndex].inverse; + + for (int i = 0; i < 16; ++i) + { + var tempMatrix = temp * m_LightListProjMatrices[viewIndex]; + var invTempMatrix = tempMatrix.inverse; + cb.data.g_mScrProjectionArr[viewIndex * 16 + i] = tempMatrix[i]; + cb.data.g_mInvScrProjectionArr[viewIndex * 16 + i] = invTempMatrix[i]; + } } + // camera to screen matrix (and it's inverse) + for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) + { + temp.SetRow(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); + temp.SetRow(1, new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); + temp.SetRow(2, new Vector4(0.0f, 0.0f, 0.5f, 0.5f)); + temp.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); + + for (int i = 0; i < 16; ++i) + { + var tempMatrix = temp * m_LightListProjMatrices[viewIndex]; + var invTempMatrix = tempMatrix.inverse; + cb.data.g_mProjectionArr[viewIndex * 16 + i] = tempMatrix[i]; + cb.data.g_mInvProjectionArr[viewIndex * 16 + i] = invTempMatrix[i]; + } + } + + var decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); + + cb.data.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. + cb.data.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); + cb.data.g_iNrVisibLights = m_TotalLightCount; + cb.data.g_isOrthographic = camera.orthographic ? 1u : 0u; + cb.data.g_BaseFeatureFlags = 0; // Filled for each individual pass. + cb.data.g_iNumSamplesMSAA = (int)hdCamera.msaaSamples; + cb.data._EnvLightIndexShift = m_lightList.lights.Count; + cb.data._DecalIndexShift = m_lightList.lights.Count + m_lightList.envLights.Count; + cb.data._DensityVolumeIndexShift = m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount; + + parameters.lightListCB = m_ShaderVariablesLightListCB; + parameters.runLightList = m_TotalLightCount > 0; + parameters.clearLightLists = false; + + // Always build the light list in XR mode to avoid issues with multi-pass + if (hdCamera.xr.enabled) + { + parameters.runLightList = true; + } + else if (!parameters.runLightList && !m_TileAndClusterData.listsAreClear) + { + parameters.clearLightLists = true; + } parameters.totalLightCount = m_TotalLightCount; - parameters.isOrthographic = camera.orthographic; parameters.viewCount = hdCamera.viewCount; parameters.enableFeatureVariants = GetFeatureVariantsEnabled(hdCamera.frameSettings); parameters.computeMaterialVariants = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ComputeMaterialVariants); parameters.computeLightVariants = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ComputeLightVariants); - parameters.nearClipPlane = camera.nearClipPlane; - parameters.farClipPlane = camera.farClipPlane; parameters.lightList = m_lightList; parameters.skyEnabled = m_SkyManager.IsLightingSkyValid(hdCamera); - parameters.screenSize = hdCamera.screenSize; - parameters.msaaSamples = (int)hdCamera.msaaSamples; parameters.useComputeAsPixel = DeferredUseComputeAsPixel(hdCamera.frameSettings); bool isProjectionOblique = GeometryUtils.IsProjectionMatrixOblique(m_LightListProjMatrices[0]); @@ -3069,17 +3064,6 @@ BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera hdCamera // Screen space AABB parameters.screenSpaceAABBShader = buildScreenAABBShader; parameters.screenSpaceAABBKernel = isProjectionOblique ? s_GenAABBKernel_Oblique : s_GenAABBKernel; - // camera to screen matrix (and it's inverse) - for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) - { - temp.SetRow(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); - temp.SetRow(1, new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); - temp.SetRow(2, new Vector4(0.0f, 0.0f, 0.5f, 0.5f)); - temp.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); - - parameters.lightListProjHMatrices[viewIndex] = temp * m_LightListProjMatrices[viewIndex]; - parameters.lightListInvProjHMatrices[viewIndex] = parameters.lightListProjHMatrices[viewIndex].inverse; - } // Big tile prepass parameters.runBigTilePrepass = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass); @@ -3102,19 +3086,12 @@ BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera hdCamera parameters.numTilesClusterX = GetNumTileClusteredX(hdCamera); parameters.numTilesClusterY = GetNumTileClusteredY(hdCamera); - const float C = (float)(1 << k_Log2NumClusters); - var geomSeries = (1.0 - Mathf.Pow(k_ClustLogBase, C)) / (1 - k_ClustLogBase); // geometric series: sum_k=0^{C-1} base^k - // TODO: This is computed here and then passed later on as a global shader parameters. - // This will be dangerous when running RenderGraph as execution will be delayed and this can change before it's executed - m_ClusterScale = (float)(geomSeries / (parameters.farClipPlane - parameters.nearClipPlane)); - - parameters.clusterScale = m_ClusterScale; - // Build dispatch indirect parameters.buildMaterialFlagsShader = buildMaterialFlagsShader; parameters.clearDispatchIndirectShader = clearDispatchIndirectShader; parameters.buildDispatchIndirectShader = buildDispatchIndirectShader; + return parameters; } @@ -3263,10 +3240,13 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ConstantBuffer g_vBoundsBuffer : register( t1 ); StructuredBuffer _LightVolumeData : register(t2); StructuredBuffer g_data : register( t3 ); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute index efde294863a..df5ec757d63 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute @@ -17,6 +17,7 @@ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderBase.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightingConvexHullUtils.hlsl" @@ -32,28 +33,6 @@ #define PERFORM_SPHERICAL_INTERSECTION_TESTS #define CONV_HULL_TEST_ENABLED -CBUFFER_START(UnityLightListClustered) -int g_iNrVisibLights; - -float4x4 g_mInvScrProjectionArr[SHADEROPTIONS_XR_MAX_VIEWS]; -float4x4 g_mScrProjectionArr[SHADEROPTIONS_XR_MAX_VIEWS]; - -uint g_isOrthographic; -int _EnvLightIndexShift; -int _DecalIndexShift; -int _DensityVolumeIndexShift; - -float g_fClustScale; -float g_fClustBase; -float g_fNearPlane; -float g_fFarPlane; -int g_iLog2NumClusters; // numClusters = (1< g_vBoundsBuffer : register( t1 ); StructuredBuffer _LightVolumeData : register(t2); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute index 6b67169033d..3e8f44bad70 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute @@ -23,11 +23,6 @@ #define NR_THREADS 64 // default to 64 threads per group on other platforms.. #endif -CBUFFER_START(UnityMaterialFlags) -uint2 g_viDimensions; -uint g_BaseFeatureFlags; -CBUFFER_END - groupshared uint ldsFeatureFlags; RWStructuredBuffer g_TileFeatureFlags; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 6172d031181..9b55f8d600a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -12,12 +12,6 @@ #pragma only_renderers d3d11 ps4 xboxone vulkan metal switch -uniform int g_isOrthographic; -uniform int g_iNrVisibLights; - -uniform float4x4 g_mInvProjectionArr[SHADEROPTIONS_XR_MAX_VIEWS]; -uniform float4x4 g_mProjectionArr[SHADEROPTIONS_XR_MAX_VIEWS]; - StructuredBuffer g_data : register( t0 ); #define NR_THREADS 64 diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 0205c9b8434..a95280760a7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -65,8 +65,6 @@ unsafe struct ShaderVariablesVolumetric // TODO: Remove if equals to the ones in global CB? public uint _NumTileBigTileX; public uint _NumTileBigTileY; - public uint _EnvLightIndexShift; - public uint _DensityVolumeIndexShift; } @@ -568,6 +566,7 @@ struct VolumeVoxelizationParameters public Texture3D volumeAtlas; public ConstantBuffer volumetricCB; + public ConstantBuffer lightListCB; } unsafe void SetPreconvolvedAmbientLightProbe(ConstantBuffer cb, HDCamera hdCamera, Fog fog) @@ -637,11 +636,6 @@ unsafe void UpdateShaderVariableslVolumetrics(ConstantBuffer volumetricCB; + public ConstantBuffer lightListCB; } VolumetricLightingParameters PrepareVolumetricLightingParameters(HDCamera hdCamera, int frameIndex) @@ -777,6 +775,7 @@ VolumetricLightingParameters PrepareVolumetricLightingParameters(HDCamera hdCame UpdateShaderVariableslVolumetrics(m_ShaderVariablesVolumetricCB, hdCamera, parameters.resolution, frameIndex); parameters.volumetricCB = m_ShaderVariablesVolumetricCB; + parameters.lightListCB = m_ShaderVariablesLightListCB; return parameters; } @@ -802,7 +801,7 @@ static void VolumetricLightingPass( in VolumetricLightingParameters parameters, } parameters.volumetricCB.Push(cmd, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesVolumetric, true); - + parameters.lightListCB.Push(cmd, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesLightList, false); // The shader defines GROUP_SIZE_1D = 8. cmd.DispatchCompute(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, ((int)parameters.resolution.x + 7) / 8, ((int)parameters.resolution.y + 7) / 8, parameters.viewCount); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl index cb4b6f28e32..6b0fdd171ac 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl @@ -38,8 +38,6 @@ cbuffer ShaderVariablesVolumetric float4 _VBufferPrevDepthDecodingParams; uint _NumTileBigTileX; uint _NumTileBigTileY; - uint _EnvLightIndexShift; - uint _DensityVolumeIndexShift; }; // diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index e83d777bf6d..0aeea1731db 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -1965,11 +1965,9 @@ AOVRequestData aovRequest else cmd.SetGlobalTexture(HDShaderIDs._SkyTexture, CoreUtils.magentaCubeTextureArray); - // PushGlobalParams must be call after UpdateSkyEnvironment so AmbientProbe is correctly setup for volumetric PushGlobalParams(hdCamera, cmd); VFXManager.ProcessCameraCommand(camera, cmd); - if (GL.wireframe) { RenderWireFrame(cullingResults, hdCamera, target.id, renderContext, cmd); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 798b05597fc..73a93459b15 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -96,15 +96,7 @@ static class HDShaderIDs public static readonly int _BlurWeightsStorage = Shader.PropertyToID("_BlurWeightsStorage"); public static readonly int g_LayeredSingleIdxBuffer = Shader.PropertyToID("g_LayeredSingleIdxBuffer"); - public static readonly int _EnvLightIndexShift = Shader.PropertyToID("_EnvLightIndexShift"); - public static readonly int _DensityVolumeIndexShift = Shader.PropertyToID("_DensityVolumeIndexShift"); - public static readonly int g_isOrthographic = Shader.PropertyToID("g_isOrthographic"); - public static readonly int g_iNrVisibLights = Shader.PropertyToID("g_iNrVisibLights"); - public static readonly int g_mScrProjectionArr = Shader.PropertyToID("g_mScrProjectionArr"); - public static readonly int g_mInvScrProjectionArr = Shader.PropertyToID("g_mInvScrProjectionArr"); - - public static readonly int g_iNumSamplesMSAA = Shader.PropertyToID("g_iNumSamplesMSAA"); public static readonly int g_depth_tex = Shader.PropertyToID("g_depth_tex"); public static readonly int g_vLayeredLightList = Shader.PropertyToID("g_vLayeredLightList"); public static readonly int g_LayeredOffset = Shader.PropertyToID("g_LayeredOffset"); @@ -114,12 +106,8 @@ static class HDShaderIDs public static readonly int g_vBoundsBuffer = Shader.PropertyToID("g_vBoundsBuffer"); public static readonly int _LightVolumeData = Shader.PropertyToID("_LightVolumeData"); public static readonly int g_data = Shader.PropertyToID("g_data"); - public static readonly int g_mProjectionArr = Shader.PropertyToID("g_mProjectionArr"); - public static readonly int g_mInvProjectionArr = Shader.PropertyToID("g_mInvProjectionArr"); - public static readonly int g_viDimensions = Shader.PropertyToID("g_viDimensions"); public static readonly int g_vLightList = Shader.PropertyToID("g_vLightList"); - public static readonly int g_BaseFeatureFlags = Shader.PropertyToID("g_BaseFeatureFlags"); public static readonly int g_TileFeatureFlags = Shader.PropertyToID("g_TileFeatureFlags"); public static readonly int g_DispatchIndirectBuffer = Shader.PropertyToID("g_DispatchIndirectBuffer"); @@ -225,7 +213,6 @@ static class HDShaderIDs public static readonly int _NormalToWorldID = Shader.PropertyToID("_NormalToWorld"); public static readonly int _DecalAtlas2DID = Shader.PropertyToID("_DecalAtlas2D"); public static readonly int _DecalHTileTexture = Shader.PropertyToID("_DecalHTileTexture"); - public static readonly int _DecalIndexShift = Shader.PropertyToID("_DecalIndexShift"); public static readonly int _DecalDatas = Shader.PropertyToID("_DecalDatas"); public static readonly int _DecalNormalBufferStencilReadMask = Shader.PropertyToID("_DecalNormalBufferStencilReadMask"); public static readonly int _DecalNormalBufferStencilRef = Shader.PropertyToID("_DecalNormalBufferStencilRef"); @@ -301,6 +288,7 @@ static class HDShaderIDs public static readonly int _ShaderVariablesGlobal = Shader.PropertyToID("ShaderVariablesGlobal"); public static readonly int _ShaderVariablesVolumetric = Shader.PropertyToID("ShaderVariablesVolumetric"); + public static readonly int _ShaderVariablesLightList = Shader.PropertyToID("ShaderVariablesLightList"); public static readonly int _SSSBufferTexture = Shader.PropertyToID("_SSSBufferTexture"); public static readonly int _NormalBufferTexture = Shader.PropertyToID("_NormalBufferTexture"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl index 8d27401af8c..643b505beb7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl @@ -7,6 +7,7 @@ #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/TextureXR.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl" // CAUTION: // Currently the shaders compiler always include regualr Unity shaderVariables, so I get a conflict here were UNITY_SHADER_VARIABLES_INCLUDED is already define, this need to be fixed. @@ -147,9 +148,6 @@ SAMPLER(samplerunity_ProbeVolumeSH); TEXTURE2D(_ExposureTexture); TEXTURE2D(_PrevExposureTexture); -// ---------------------------------------------------------------------------- -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl" - // Custom generated by HDRP, not from Unity Engine (passed in via HDCamera) #if defined(USING_STEREO_MATRICES) CBUFFER_START(UnityXRViewConstants) From f6a8ab6b13999c3dcfac65d00f446f39ba260f5a Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 13 Mar 2020 11:00:37 +0100 Subject: [PATCH 40/92] Fixed path tracing frame index constant --- .../Runtime/RenderPipeline/HDRenderPipeline.cs | 8 +++----- .../Runtime/RenderPipeline/HDStringConstants.cs | 1 + .../Runtime/RenderPipeline/PathTracing/PathTracing.cs | 2 +- .../PathTracing/Shaders/PathTracingMain.raytrace | 6 +++--- .../Raytracing/Shaders/ShaderVariablesRaytracing.hlsl | 1 + .../RenderPipeline/ShaderPass/ShaderPassPathTracing.hlsl | 8 ++++---- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 0aeea1731db..4f00244dc27 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -997,20 +997,18 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) int coarseStencilHeight = HDUtils.DivRoundUp(hdCamera.actualHeight, 8); m_ShaderVariablesGlobalCB.data._CoarseStencilBufferSize = new Vector4(coarseStencilWidth, coarseStencilHeight, 1.0f / coarseStencilWidth, 1.0f / coarseStencilHeight); + m_ShaderVariablesGlobalCB.data._RaytracingFrameIndex = RayTracingFrameIndex(hdCamera); if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) { - m_ShaderVariablesGlobalCB.data._RaytracedIndirectDiffuse = ValidIndirectDiffuseState(hdCamera) ? 1 : 0; - m_ShaderVariablesGlobalCB.data._RaytracingFrameIndex = RayTracingFrameIndex(hdCamera); - var settings = hdCamera.volumeStack.GetComponent(); bool usesRaytracedReflections = hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value; m_ShaderVariablesGlobalCB.data._UseRayTracedReflections = usesRaytracedReflections ? 1 : 0; + m_ShaderVariablesGlobalCB.data._RaytracedIndirectDiffuse = ValidIndirectDiffuseState(hdCamera) ? 1 : 0; } else { - m_ShaderVariablesGlobalCB.data._RaytracedIndirectDiffuse = 0; - m_ShaderVariablesGlobalCB.data._RaytracingFrameIndex = RayTracingFrameIndex(hdCamera); m_ShaderVariablesGlobalCB.data._UseRayTracedReflections = 0; + m_ShaderVariablesGlobalCB.data._RaytracedIndirectDiffuse = 0; } m_ShaderVariablesGlobalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 73a93459b15..93ed02ed36a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -463,6 +463,7 @@ static class HDShaderIDs public static readonly int _RaytracingRayMaxLength = Shader.PropertyToID("_RaytracingRayMaxLength"); public static readonly int _PixelSpreadAngleTangent = Shader.PropertyToID("_PixelSpreadAngleTangent"); public static readonly int _RaytracingPixelSpreadAngle = Shader.PropertyToID("_RaytracingPixelSpreadAngle"); + public static readonly int _PathtracingIteration = Shader.PropertyToID("_PathtracingIteration"); public static readonly string _RaytracingAccelerationStructureName = "_RaytracingAccelerationStructure"; // Light Cluster diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs index 75c10f6fa9d..d1ac8dedaf0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs @@ -207,7 +207,7 @@ void RenderPathTracing(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputText // Set the data for the ray generation cmd.SetRayTracingTextureParam(pathTracingShader, HDShaderIDs._CameraColorTextureRW, outputTexture); - cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, (int)m_CurrentIteration); + cmd.SetGlobalInt(HDShaderIDs._PathtracingIteration, (int)m_CurrentIteration); // Compute an approximate pixel spread angle value (in radians) cmd.SetRayTracingFloatParam(pathTracingShader, HDShaderIDs._RaytracingPixelSpreadAngle, GetPixelSpreadAngle(hdCamera.camera.fieldOfView, hdCamera.actualWidth, hdCamera.actualHeight)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingMain.raytrace b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingMain.raytrace index 8f3d291ca65..81e59d4336f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingMain.raytrace +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingMain.raytrace @@ -79,7 +79,7 @@ void RayGen() uint2 currentPixelCoord = uint2(LaunchIndex.x, LaunchIndex.y); // Have we reached max sampling? - uint sampleCount = _RaytracingFrameIndex; + uint sampleCount = _PathtracingIteration; if (sampleCount >= _RaytracingNumSamples) { _CameraColorTextureRW[currentPixelCoord] = float4(_AccumulatedFrameTexture[currentPixelCoord].xyz * GetCurrentExposureMultiplier(), 1.0); @@ -88,8 +88,8 @@ void RayGen() // Jitter them float3 jitteredPixelCoord = float3(currentPixelCoord, 1.0); - jitteredPixelCoord.x += GetSample(currentPixelCoord, _RaytracingFrameIndex, 254); - jitteredPixelCoord.y += GetSample(currentPixelCoord, _RaytracingFrameIndex, 255); + jitteredPixelCoord.x += GetSample(currentPixelCoord, _PathtracingIteration, 254); + jitteredPixelCoord.y += GetSample(currentPixelCoord, _PathtracingIteration, 255); // Compute the ray direction, from those coordinates float3 directionWS = -normalize(mul(jitteredPixelCoord, (float3x3)_PixelCoordToViewDirWS)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.hlsl index 367f34a5743..e729b4502ea 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.hlsl @@ -20,4 +20,5 @@ int _RayCountEnabled; float _RaytracingCameraNearPlane; uint _RaytracingDiffuseRay; int _RaytracingPreExposition; +int _PathtracingIteration; RW_TEXTURE2D_ARRAY(uint, _RayCountTexture); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassPathTracing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassPathTracing.hlsl index 94efa53225a..c4e950042eb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassPathTracing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassPathTracing.hlsl @@ -97,9 +97,9 @@ void ClosestHit(inout PathIntersection pathIntersection : SV_RayPayload, Attribu // Generate the new sample (following values of the sequence) float3 inputSample = 0.0; - inputSample.x = GetSample(pathIntersection.pixelCoord, _RaytracingFrameIndex, 4 * currentDepth); - inputSample.y = GetSample(pathIntersection.pixelCoord, _RaytracingFrameIndex, 4 * currentDepth + 1); - inputSample.z = GetSample(pathIntersection.pixelCoord, _RaytracingFrameIndex, 4 * currentDepth + 2); + inputSample.x = GetSample(pathIntersection.pixelCoord, _PathtracingIteration, 4 * currentDepth); + inputSample.y = GetSample(pathIntersection.pixelCoord, _PathtracingIteration, 4 * currentDepth + 1); + inputSample.z = GetSample(pathIntersection.pixelCoord, _PathtracingIteration, 4 * currentDepth + 2); // Get current path throughput float3 pathThroughput = pathIntersection.color; @@ -167,7 +167,7 @@ void ClosestHit(inout PathIntersection pathIntersection : SV_RayPayload, Attribu float russianRouletteValue = Luminance(pathThroughput); float russianRouletteFactor = 1.0; - float rand = GetSample(pathIntersection.pixelCoord, _RaytracingFrameIndex, 4 * currentDepth + 3); + float rand = GetSample(pathIntersection.pixelCoord, _PathtracingIteration, 4 * currentDepth + 3); if (RussianRouletteTest(russianRouletteValue, rand, russianRouletteFactor, !currentDepth)) { bool isSampleBelow = IsBelow(mtlData, rayDescriptor.Direction); From 1a36c4c8d04064c5f7d8d0ddffa0b1757f613fa7 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 13 Mar 2020 11:11:56 +0100 Subject: [PATCH 41/92] Fixed ao constant w/ raytracing --- .../Lighting/ScreenSpaceLighting/AmbientOcclusion.cs | 11 +++++++++++ .../Raytracing/HDRaytracingAmbientOcclusion.cs | 1 - 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs index d2e913e8dcc..297b6d56112 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs @@ -595,7 +595,18 @@ internal void Dispatch(CommandBuffer cmd, HDCamera camera, int frameCount) internal void UpdateShaderVariableGlobalCB(ConstantBuffer cb, HDCamera hdCamera) { var settings = hdCamera.volumeStack.GetComponent(); + bool aoEnabled = false; if (IsActive(hdCamera, settings)) + { + aoEnabled = true; + // If raytraced AO is enabled but raytracing state is wrong then we disable it. + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value && !HDRenderPipeline.currentPipeline.GetRayTracingState()) + { + aoEnabled = false; + } + } + + if (aoEnabled) cb.data._AmbientOcclusionParam = new Vector4(0f, 0f, 0f, settings.directLightingStrength.value); else cb.data._AmbientOcclusionParam = Vector4.zero; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs index 28c0afce6dd..6011fc3b42a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs @@ -59,7 +59,6 @@ static RTHandle AmbientOcclusionHistoryBufferAllocatorFunction(string viewName, public void SetDefaultAmbientOcclusionTexture(CommandBuffer cmd) { cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, TextureXR.GetBlackTexture()); - cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, Vector4.zero); } public void RenderAO(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputTexture, ScriptableRenderContext renderContext, int frameCount) From 6bbeaa1f37c012d9c6c44bf9c2e2dee7bd130265 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 13 Mar 2020 11:48:37 +0100 Subject: [PATCH 42/92] Better path tracing fix. --- .../Runtime/RenderPipeline/HDStringConstants.cs | 1 - .../Runtime/RenderPipeline/PathTracing/PathTracing.cs | 2 +- .../PathTracing/Shaders/PathTracingMain.raytrace | 6 +++--- .../Raytracing/Shaders/ShaderVariablesRaytracing.hlsl | 1 - .../RenderPipeline/ShaderPass/ShaderPassPathTracing.hlsl | 8 ++++---- 5 files changed, 8 insertions(+), 10 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 93ed02ed36a..73a93459b15 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -463,7 +463,6 @@ static class HDShaderIDs public static readonly int _RaytracingRayMaxLength = Shader.PropertyToID("_RaytracingRayMaxLength"); public static readonly int _PixelSpreadAngleTangent = Shader.PropertyToID("_PixelSpreadAngleTangent"); public static readonly int _RaytracingPixelSpreadAngle = Shader.PropertyToID("_RaytracingPixelSpreadAngle"); - public static readonly int _PathtracingIteration = Shader.PropertyToID("_PathtracingIteration"); public static readonly string _RaytracingAccelerationStructureName = "_RaytracingAccelerationStructure"; // Light Cluster diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs index d1ac8dedaf0..e81f39f830f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs @@ -207,7 +207,7 @@ void RenderPathTracing(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputText // Set the data for the ray generation cmd.SetRayTracingTextureParam(pathTracingShader, HDShaderIDs._CameraColorTextureRW, outputTexture); - cmd.SetGlobalInt(HDShaderIDs._PathtracingIteration, (int)m_CurrentIteration); + cmd.SetGlobalInt(HDShaderIDs._RaytracingSampleIndex, (int)m_CurrentIteration); // Compute an approximate pixel spread angle value (in radians) cmd.SetRayTracingFloatParam(pathTracingShader, HDShaderIDs._RaytracingPixelSpreadAngle, GetPixelSpreadAngle(hdCamera.camera.fieldOfView, hdCamera.actualWidth, hdCamera.actualHeight)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingMain.raytrace b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingMain.raytrace index 81e59d4336f..a08f212aa30 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingMain.raytrace +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingMain.raytrace @@ -79,7 +79,7 @@ void RayGen() uint2 currentPixelCoord = uint2(LaunchIndex.x, LaunchIndex.y); // Have we reached max sampling? - uint sampleCount = _PathtracingIteration; + uint sampleCount = _RaytracingSampleIndex; if (sampleCount >= _RaytracingNumSamples) { _CameraColorTextureRW[currentPixelCoord] = float4(_AccumulatedFrameTexture[currentPixelCoord].xyz * GetCurrentExposureMultiplier(), 1.0); @@ -88,8 +88,8 @@ void RayGen() // Jitter them float3 jitteredPixelCoord = float3(currentPixelCoord, 1.0); - jitteredPixelCoord.x += GetSample(currentPixelCoord, _PathtracingIteration, 254); - jitteredPixelCoord.y += GetSample(currentPixelCoord, _PathtracingIteration, 255); + jitteredPixelCoord.x += GetSample(currentPixelCoord, _RaytracingSampleIndex, 254); + jitteredPixelCoord.y += GetSample(currentPixelCoord, _RaytracingSampleIndex, 255); // Compute the ray direction, from those coordinates float3 directionWS = -normalize(mul(jitteredPixelCoord, (float3x3)_PixelCoordToViewDirWS)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.hlsl index e729b4502ea..367f34a5743 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.hlsl @@ -20,5 +20,4 @@ int _RayCountEnabled; float _RaytracingCameraNearPlane; uint _RaytracingDiffuseRay; int _RaytracingPreExposition; -int _PathtracingIteration; RW_TEXTURE2D_ARRAY(uint, _RayCountTexture); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassPathTracing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassPathTracing.hlsl index c4e950042eb..f2c5ed3f293 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassPathTracing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassPathTracing.hlsl @@ -97,9 +97,9 @@ void ClosestHit(inout PathIntersection pathIntersection : SV_RayPayload, Attribu // Generate the new sample (following values of the sequence) float3 inputSample = 0.0; - inputSample.x = GetSample(pathIntersection.pixelCoord, _PathtracingIteration, 4 * currentDepth); - inputSample.y = GetSample(pathIntersection.pixelCoord, _PathtracingIteration, 4 * currentDepth + 1); - inputSample.z = GetSample(pathIntersection.pixelCoord, _PathtracingIteration, 4 * currentDepth + 2); + inputSample.x = GetSample(pathIntersection.pixelCoord, _RaytracingSampleIndex, 4 * currentDepth); + inputSample.y = GetSample(pathIntersection.pixelCoord, _RaytracingSampleIndex, 4 * currentDepth + 1); + inputSample.z = GetSample(pathIntersection.pixelCoord, _RaytracingSampleIndex, 4 * currentDepth + 2); // Get current path throughput float3 pathThroughput = pathIntersection.color; @@ -167,7 +167,7 @@ void ClosestHit(inout PathIntersection pathIntersection : SV_RayPayload, Attribu float russianRouletteValue = Luminance(pathThroughput); float russianRouletteFactor = 1.0; - float rand = GetSample(pathIntersection.pixelCoord, _PathtracingIteration, 4 * currentDepth + 3); + float rand = GetSample(pathIntersection.pixelCoord, _RaytracingSampleIndex, 4 * currentDepth + 3); if (RussianRouletteTest(russianRouletteValue, rand, russianRouletteFactor, !currentDepth)) { bool isSampleBelow = IsBelow(mtlData, rayDescriptor.Direction); From 75c2096e3687efe09b0d0672a7f9c430c1e9e2bd Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 19 Mar 2020 15:59:15 +0100 Subject: [PATCH 43/92] Refactored CB API to comply with Render Graph specificities --- .../Direct3D11/None/2203_PlanarProbes.png | 4 +- .../Runtime/Common/ConstantBuffer.cs | 109 +++++++++++++--- .../Lighting/AtmosphericScattering/Fog.cs | 48 +++---- .../Runtime/Lighting/LightLoop/LightLoop.cs | 106 ++++++++-------- .../ScreenSpaceLighting/AmbientOcclusion.cs | 6 +- .../Runtime/Lighting/Shadow/HDShadowAtlas.cs | 49 ++++---- .../Shadow/HDShadowManager.RenderGraph.cs | 4 +- .../Lighting/Shadow/HDShadowManager.cs | 12 +- .../VolumetricLighting/VolumetricLighting.cs | 119 +++++++++--------- .../SubsurfaceScatteringManager.cs | 20 +-- .../Runtime/RenderPipeline/Camera/HDCamera.cs | 68 +++++----- .../HDRenderPipeline.LightLoop.cs | 10 +- .../HDRenderPipeline.RenderGraph.cs | 18 +-- .../RenderPipeline/HDRenderPipeline.cs | 106 +++++++--------- 14 files changed, 370 insertions(+), 309 deletions(-) diff --git a/TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/None/2203_PlanarProbes.png b/TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/None/2203_PlanarProbes.png index d4288f64bf7..65a4bb37eeb 100644 --- a/TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/None/2203_PlanarProbes.png +++ b/TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/None/2203_PlanarProbes.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:093b992c30a5cc9104c116e0ec30a25bb7d8e4a9207579fd7c49669e04b9fdab -size 257625 +oid sha256:9c66daf9b663889178fa230c66cbd1ba0d9cde82582a23d8868a8d9371220bb1 +size 257728 diff --git a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs index cdeed682f0e..6a80e273a94 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs @@ -2,50 +2,127 @@ namespace UnityEngine.Rendering { + /// + /// Constant Buffer management class. + /// + /// Type of the structure that represent the constant buffer data. public class ConstantBuffer where CBType : struct { - CBType[] m_Data = new CBType[1]; // Array is required by the ComputeBuffer SetData API - ComputeBuffer m_GPUConstantBuffer = null; + CBType[] m_Data = new CBType[1]; // Array is required by the ComputeBuffer SetData API + ComputeBuffer m_GPUConstantBuffer = null; + static ConstantBuffer m_TypedConstantBuffer = new ConstantBuffer(); - public ref CBType data => ref m_Data[0]; - - public ConstantBuffer() + internal ConstantBuffer() { m_GPUConstantBuffer = new ComputeBuffer(1, UnsafeUtility.SizeOf(), ComputeBufferType.Constant); } - public void Commit(CommandBuffer cmd) + internal void UpdateDataInternal(CommandBuffer cmd, in CBType data) { + m_Data[0] = data; cmd.SetComputeBufferData(m_GPUConstantBuffer, m_Data); } - public void PushGlobal(CommandBuffer cmd, int shaderId, bool commitData = false) + internal void SetGlobalInternal(CommandBuffer cmd, int shaderId) { - if (commitData) - Commit(cmd); cmd.SetGlobalConstantBuffer(m_GPUConstantBuffer, shaderId, 0, m_GPUConstantBuffer.stride); } - public void Push(CommandBuffer cmd, ComputeShader cs, int shaderId, bool commitData = false) + internal void SetInternal(CommandBuffer cmd, ComputeShader cs, int shaderId) { - if (commitData) - Commit(cmd); cmd.SetComputeConstantBufferParam(cs, shaderId, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); } - public void Push(CommandBuffer cmd, Material mat, int shaderId, bool commitData = false) + internal void SetInternal(Material mat, int shaderId) { - if (commitData) - Commit(cmd); // This isn't done via command buffer because as long as the buffer itself is not destroyed, // the binding stays valid. Only the commit of data needs to go through the command buffer. // We do it here anyway for now to simplify user API. mat.SetConstantBuffer(shaderId, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); } - public void Release() + internal void Release() { CoreUtils.SafeRelease(m_GPUConstantBuffer); } + + /// + /// Update the GPU data of the constant buffer and bind it globally. + /// + /// Command Buffer used to execute the graphic commands. + /// Input data of the constant buffer. + /// Shader porperty id to bind the constant buffer to. + public static void PushGlobal(CommandBuffer cmd, in CBType data, int shaderId) + { + m_TypedConstantBuffer.UpdateDataInternal(cmd, data); + m_TypedConstantBuffer.SetGlobalInternal(cmd, shaderId); + } + + /// + /// Update the GPU data of the constant buffer and bind it to a compute shader. + /// + /// Command Buffer used to execute the graphic commands. + /// Input data of the constant buffer. + /// Compute shader to which the constant buffer should be bound. + /// Shader porperty id to bind the constant buffer to. + public static void Push(CommandBuffer cmd, in CBType data, ComputeShader cs, int shaderId) + { + m_TypedConstantBuffer.UpdateDataInternal(cmd, data); + m_TypedConstantBuffer.SetInternal(cmd, cs, shaderId); + } + + /// + /// Update the GPU data of the constant buffer and bind it to a material. + /// + /// Command Buffer used to execute the graphic commands. + /// Input data of the constant buffer. + /// Material to which the constant buffer should be bound. + /// Shader porperty id to bind the constant buffer to. + public static void Push(CommandBuffer cmd, in CBType data, Material mat, int shaderId) + { + m_TypedConstantBuffer.UpdateDataInternal(cmd, data); + m_TypedConstantBuffer.SetInternal(mat, shaderId); + } + + /// + /// Update the GPU data of the constant buffer. + /// + /// Command Buffer used to execute the graphic commands. + /// Input data of the constant buffer. + public static void UpdateData(CommandBuffer cmd, in CBType data) + { + m_TypedConstantBuffer.UpdateDataInternal(cmd, data); + } + + /// + /// Bind the constant buffer globally. + /// + /// Command Buffer used to execute the graphic commands. + /// Shader porperty id to bind the constant buffer to. + public static void SetGlobal(CommandBuffer cmd, int shaderId) + { + m_TypedConstantBuffer.SetGlobalInternal(cmd, shaderId); + } + + /// + /// Bind the constant buffer to a compute shader. + /// + /// Command Buffer used to execute the graphic commands. + /// Compute shader to which the constant buffer should be bound. + /// Shader porperty id to bind the constant buffer to. + public static void Set(CommandBuffer cmd, ComputeShader cs, int shaderId) + { + m_TypedConstantBuffer.SetInternal(cmd, cs, shaderId); + } + + /// + /// Bind the constant buffer to a material. + /// + /// Material to which the constant buffer should be bound. + /// Shader porperty id to bind the constant buffer to. + public static void Set(Material mat, int shaderId) + { + m_TypedConstantBuffer.SetInternal(mat, shaderId); + } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs index 0e753b41bfd..cdf05918aec 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs @@ -97,51 +97,51 @@ static float ScaleHeightFromLayerDepth(float d) return d * 0.144765f; } - static void UpdateShaderVariablesGlobalCBNeutralParameters(ConstantBuffer cb) + static void UpdateShaderVariablesGlobalCBNeutralParameters(ref ShaderVariablesGlobal cb) { - cb.data._FogEnabled = 0; - cb.data._EnableVolumetricFog = 0; - cb.data._HeightFogBaseScattering = Vector3.zero; - cb.data._HeightFogBaseExtinction = 0.0f; - cb.data._HeightFogExponents = Vector2.one; - cb.data._HeightFogBaseHeight = 0.0f; - cb.data._GlobalFogAnisotropy = 0.0f; + cb._FogEnabled = 0; + cb._EnableVolumetricFog = 0; + cb._HeightFogBaseScattering = Vector3.zero; + cb._HeightFogBaseExtinction = 0.0f; + cb._HeightFogExponents = Vector2.one; + cb._HeightFogBaseHeight = 0.0f; + cb._GlobalFogAnisotropy = 0.0f; } - internal static void UpdateShaderVariablesGlobalCB(ConstantBuffer cb, HDCamera hdCamera) + internal static void UpdateShaderVariablesGlobalCB(ref ShaderVariablesGlobal cb, HDCamera hdCamera) { // TODO Handle user override var fogSettings = hdCamera.volumeStack.GetComponent(); if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.AtmosphericScattering) || !fogSettings.enabled.value) { - UpdateShaderVariablesGlobalCBNeutralParameters(cb); + UpdateShaderVariablesGlobalCBNeutralParameters(ref cb); } else { - fogSettings.UpdateShaderVariablesGlobalCBFogParameters(cb, hdCamera); + fogSettings.UpdateShaderVariablesGlobalCBFogParameters(ref cb, hdCamera); } } - void UpdateShaderVariablesGlobalCBFogParameters(ConstantBuffer cb, HDCamera hdCamera) + void UpdateShaderVariablesGlobalCBFogParameters(ref ShaderVariablesGlobal cb, HDCamera hdCamera) { bool enableVolumetrics = enableVolumetricFog.value && hdCamera.frameSettings.IsEnabled(FrameSettingsField.Volumetrics); - cb.data._FogEnabled = 1; - cb.data._PBRFogEnabled = IsPBRFogEnabled(hdCamera) ? 1 : 0; - cb.data._EnableVolumetricFog = enableVolumetrics ? 1 : 0; - cb.data._MaxFogDistance = maxFogDistance.value; + cb._FogEnabled = 1; + cb._PBRFogEnabled = IsPBRFogEnabled(hdCamera) ? 1 : 0; + cb._EnableVolumetricFog = enableVolumetrics ? 1 : 0; + cb._MaxFogDistance = maxFogDistance.value; Color fogColor = (colorMode.value == FogColorMode.ConstantColor) ? color.value : tint.value; - cb.data._FogColorMode = (float)colorMode.value; - cb.data._FogColor = new Color(fogColor.r, fogColor.g, fogColor.b, 0.0f); - cb.data._MipFogParameters = new Vector4(mipFogNear.value, mipFogFar.value, mipFogMaxMip.value, 0.0f); + cb._FogColorMode = (float)colorMode.value; + cb._FogColor = new Color(fogColor.r, fogColor.g, fogColor.b, 0.0f); + cb._MipFogParameters = new Vector4(mipFogNear.value, mipFogFar.value, mipFogMaxMip.value, 0.0f); DensityVolumeArtistParameters param = new DensityVolumeArtistParameters(albedo.value, meanFreePath.value, anisotropy.value); DensityVolumeEngineData data = param.ConvertToEngineData(); - cb.data._HeightFogBaseScattering = data.scattering; - cb.data._HeightFogBaseExtinction = data.extinction; + cb._HeightFogBaseScattering = data.scattering; + cb._HeightFogBaseExtinction = data.extinction; float crBaseHeight = baseHeight.value; @@ -152,9 +152,9 @@ void UpdateShaderVariablesGlobalCBFogParameters(ConstantBuffer m_ShaderVariablesLightListCB; + ShaderVariablesLightList m_ShaderVariablesLightListCB = new ShaderVariablesLightList(); static int s_GenAABBKernel; static int s_GenAABBKernel_Oblique; @@ -886,8 +886,6 @@ void InitializeLightLoop(IBLFilterBSDF[] iBLFilterBSDFArray) // Screen space shadow int numMaxShadows = Math.Max(m_Asset.currentPlatformRenderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots, 1); m_CurrentScreenSpaceShadowData = new ScreenSpaceShadowData[numMaxShadows]; - - m_ShaderVariablesLightListCB = new ConstantBuffer(); } void CleanupLightLoop() @@ -924,8 +922,6 @@ void CleanupLightLoop() CoreUtils.Destroy(m_DebugViewTilesMaterial); CoreUtils.Destroy(m_DebugHDShadowMapMaterial); CoreUtils.Destroy(m_DebugBlitMaterial); - - m_ShaderVariablesLightListCB.Release(); } void LightLoopNewRender() @@ -2719,7 +2715,7 @@ struct BuildGPULightListParameters public ComputeShader buildDispatchIndirectShader; public bool useComputeAsPixel; - public ConstantBuffer lightListCB; + public ShaderVariablesLightList lightListCB; } struct BuildGPULightListResources @@ -2756,7 +2752,7 @@ static void ClearLightLists( in BuildGPULightListParameters parameters, CommandBuffer cmd) { // ClearLightLists is the first pass, we push the global parameters for light list building here. - parameters.lightListCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesLightList, true); + ConstantBuffer.PushGlobal(cmd, parameters.lightListCB, HDShaderIDs._ShaderVariablesLightList); if (parameters.clearLightLists && !parameters.runLightList) { @@ -2837,8 +2833,10 @@ static void BuildPerTileLightList(in BuildGPULightListParameters parameters, in { baseFeatureFlags |= LightDefinitions.s_MaterialFeatureMaskFlags; } - parameters.lightListCB.data.g_BaseFeatureFlags = baseFeatureFlags; - parameters.lightListCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesLightList, true); + + var localLightListCB = parameters.lightListCB; + localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; + ConstantBuffer.PushGlobal(cmd, localLightListCB, HDShaderIDs._ShaderVariablesLightList); cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_TileFeatureFlags, tileAndCluster.tileFeatureFlags); tileFlagsWritten = true; @@ -2911,8 +2909,10 @@ static void BuildDispatchIndirectArguments(in BuildGPULightListParameters parame baseFeatureFlags |= LightDefinitions.s_MaterialFeatureMaskFlags; } } - parameters.lightListCB.data.g_BaseFeatureFlags = baseFeatureFlags; - parameters.lightListCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesLightList, true); + + var localLightListCB = parameters.lightListCB; + localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; + ConstantBuffer.PushGlobal(cmd, localLightListCB, HDShaderIDs._ShaderVariablesLightList); cmd.SetComputeBufferParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, tileAndCluster.tileFeatureFlags); @@ -2980,7 +2980,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera h var h = (int)hdCamera.screenSize.y; // Fill the shared constant buffer. - var cb = m_ShaderVariablesLightListCB; + ref var cb = ref m_ShaderVariablesLightListCB; var temp = new Matrix4x4(); temp.SetRow(0, new Vector4(0.5f * w, 0.0f, 0.0f, 0.5f * w)); temp.SetRow(1, new Vector4(0.0f, 0.5f * h, 0.0f, 0.5f * h)); @@ -2997,8 +2997,8 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera h { var tempMatrix = temp * m_LightListProjMatrices[viewIndex]; var invTempMatrix = tempMatrix.inverse; - cb.data.g_mScrProjectionArr[viewIndex * 16 + i] = tempMatrix[i]; - cb.data.g_mInvScrProjectionArr[viewIndex * 16 + i] = invTempMatrix[i]; + cb.g_mScrProjectionArr[viewIndex * 16 + i] = tempMatrix[i]; + cb.g_mInvScrProjectionArr[viewIndex * 16 + i] = invTempMatrix[i]; } } @@ -3014,22 +3014,22 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera h { var tempMatrix = temp * m_LightListProjMatrices[viewIndex]; var invTempMatrix = tempMatrix.inverse; - cb.data.g_mProjectionArr[viewIndex * 16 + i] = tempMatrix[i]; - cb.data.g_mInvProjectionArr[viewIndex * 16 + i] = invTempMatrix[i]; + cb.g_mProjectionArr[viewIndex * 16 + i] = tempMatrix[i]; + cb.g_mInvProjectionArr[viewIndex * 16 + i] = invTempMatrix[i]; } } var decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); - cb.data.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. - cb.data.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); - cb.data.g_iNrVisibLights = m_TotalLightCount; - cb.data.g_isOrthographic = camera.orthographic ? 1u : 0u; - cb.data.g_BaseFeatureFlags = 0; // Filled for each individual pass. - cb.data.g_iNumSamplesMSAA = (int)hdCamera.msaaSamples; - cb.data._EnvLightIndexShift = m_lightList.lights.Count; - cb.data._DecalIndexShift = m_lightList.lights.Count + m_lightList.envLights.Count; - cb.data._DensityVolumeIndexShift = m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount; + cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. + cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); + cb.g_iNrVisibLights = m_TotalLightCount; + cb.g_isOrthographic = camera.orthographic ? 1u : 0u; + cb.g_BaseFeatureFlags = 0; // Filled for each individual pass. + cb.g_iNumSamplesMSAA = (int)hdCamera.msaaSamples; + cb._EnvLightIndexShift = m_lightList.lights.Count; + cb._DecalIndexShift = m_lightList.lights.Count + m_lightList.envLights.Count; + cb._DensityVolumeIndexShift = m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount; parameters.lightListCB = m_ShaderVariablesLightListCB; parameters.runLightList = m_TotalLightCount > 0; @@ -3205,56 +3205,56 @@ LightLoopGlobalParameters PrepareLightLoopGlobalParameters(HDCamera hdCamera) return parameters; } - unsafe void UpdateShaderVariablesGlobalLightLoop(ConstantBuffer cb, HDCamera hdCamera) + unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, HDCamera hdCamera) { // Atlases - cb.data._CookieAtlasSize = m_TextureCaches.lightCookieManager.GetCookieAtlasSize(); - cb.data._CookieAtlasData = m_TextureCaches.lightCookieManager.GetCookieAtlasDatas(); - cb.data._PlanarAtlasData = m_TextureCaches.reflectionPlanarProbeCache.GetAtlasDatas(); - cb.data._EnvSliceSize = m_TextureCaches.reflectionProbeCache.GetEnvSliceSize(); + cb._CookieAtlasSize = m_TextureCaches.lightCookieManager.GetCookieAtlasSize(); + cb._CookieAtlasData = m_TextureCaches.lightCookieManager.GetCookieAtlasDatas(); + cb._PlanarAtlasData = m_TextureCaches.reflectionPlanarProbeCache.GetAtlasDatas(); + cb._EnvSliceSize = m_TextureCaches.reflectionProbeCache.GetEnvSliceSize(); // Planar reflections for (int i = 0; i < asset.currentPlatformRenderPipelineSettings.lightLoopSettings.maxPlanarReflectionOnScreen; ++i) { for (int j = 0; j < 16; ++j) - cb.data._Env2DCaptureVP[i * 16 + j] = m_TextureCaches.env2DCaptureVP[i][j]; + cb._Env2DCaptureVP[i * 16 + j] = m_TextureCaches.env2DCaptureVP[i][j]; for (int j = 0; j < 4; ++j) - cb.data._Env2DCaptureForward[i * 4 + j] = m_TextureCaches.env2DCaptureForward[i][j]; + cb._Env2DCaptureForward[i * 4 + j] = m_TextureCaches.env2DCaptureForward[i][j]; for (int j = 0; j < 4; ++j) - cb.data._Env2DAtlasScaleOffset[i * 4 + j] = m_TextureCaches.env2DAtlasScaleOffset[i][j]; + cb._Env2DAtlasScaleOffset[i * 4 + j] = m_TextureCaches.env2DAtlasScaleOffset[i][j]; } // Light info - cb.data._PunctualLightCount = (uint)m_lightList.punctualLightCount; - cb.data._AreaLightCount = (uint)m_lightList.areaLightCount; - cb.data._EnvLightCount = (uint)m_lightList.envLights.Count; - cb.data._DirectionalLightCount = (uint)m_lightList.directionalLights.Count; - cb.data._DecalCount = (uint)DecalSystem.m_DecalDatasCount; + cb._PunctualLightCount = (uint)m_lightList.punctualLightCount; + cb._AreaLightCount = (uint)m_lightList.areaLightCount; + cb._EnvLightCount = (uint)m_lightList.envLights.Count; + cb._DirectionalLightCount = (uint)m_lightList.directionalLights.Count; + cb._DecalCount = (uint)DecalSystem.m_DecalDatasCount; HDAdditionalLightData sunLightData = GetHDAdditionalLightData(m_CurrentSunLight); bool sunLightShadow = sunLightData != null && m_CurrentShadowSortedSunLightIndex >= 0; - cb.data._DirectionalShadowIndex = sunLightShadow ? m_CurrentShadowSortedSunLightIndex : -1; - cb.data._EnableLightLayers = hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers) ? 1u : 0u; - cb.data._EnvLightSkyEnabled = m_SkyManager.IsLightingSkyValid(hdCamera) ? 1 : 0; + cb._DirectionalShadowIndex = sunLightShadow ? m_CurrentShadowSortedSunLightIndex : -1; + cb._EnableLightLayers = hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers) ? 1u : 0u; + cb._EnvLightSkyEnabled = m_SkyManager.IsLightingSkyValid(hdCamera) ? 1 : 0; const float C = (float)(1 << k_Log2NumClusters); var geomSeries = (1.0 - Mathf.Pow(k_ClustLogBase, C)) / (1 - k_ClustLogBase); // geometric series: sum_k=0^{C-1} base^k // Tile/Cluster - cb.data._NumTileFtplX = (uint)GetNumTileFtplX(hdCamera); - cb.data._NumTileFtplY = (uint)GetNumTileFtplY(hdCamera); - cb.data.g_fClustScale = (float)(geomSeries / (hdCamera.camera.farClipPlane - hdCamera.camera.nearClipPlane)); ; - cb.data.g_fClustBase = k_ClustLogBase; - cb.data.g_fNearPlane = hdCamera.camera.nearClipPlane; - cb.data.g_fFarPlane = hdCamera.camera.farClipPlane; - cb.data.g_iLog2NumClusters = k_Log2NumClusters; - cb.data.g_isLogBaseBufferEnabled = k_UseDepthBuffer ? 1 : 0; - cb.data._NumTileClusteredX = (uint)GetNumTileClusteredX(hdCamera); - cb.data._NumTileClusteredY = (uint)GetNumTileClusteredY(hdCamera); + cb._NumTileFtplX = (uint)GetNumTileFtplX(hdCamera); + cb._NumTileFtplY = (uint)GetNumTileFtplY(hdCamera); + cb.g_fClustScale = (float)(geomSeries / (hdCamera.camera.farClipPlane - hdCamera.camera.nearClipPlane)); ; + cb.g_fClustBase = k_ClustLogBase; + cb.g_fNearPlane = hdCamera.camera.nearClipPlane; + cb.g_fFarPlane = hdCamera.camera.farClipPlane; + cb.g_iLog2NumClusters = k_Log2NumClusters; + cb.g_isLogBaseBufferEnabled = k_UseDepthBuffer ? 1 : 0; + cb._NumTileClusteredX = (uint)GetNumTileClusteredX(hdCamera); + cb._NumTileClusteredY = (uint)GetNumTileClusteredY(hdCamera); // Misc - cb.data._EnableSSRefraction = hdCamera.frameSettings.IsEnabled(FrameSettingsField.Refraction) ? 1u : 0u; + cb._EnableSSRefraction = hdCamera.frameSettings.IsEnabled(FrameSettingsField.Refraction) ? 1u : 0u; } static void PushLightDataGlobalParams(in LightDataGlobalParameters param, CommandBuffer cmd) @@ -3314,7 +3314,7 @@ static void PushLightLoopGlobalParams(in LightLoopGlobalParameters param, Comman } - void RenderShadowMaps(ScriptableRenderContext renderContext, CommandBuffer cmd, ConstantBuffer globalCB, CullingResults cullResults, HDCamera hdCamera) + void RenderShadowMaps(ScriptableRenderContext renderContext, CommandBuffer cmd, in ShaderVariablesGlobal globalCB, CullingResults cullResults, HDCamera hdCamera) { // kick off the shadow jobs here m_ShadowManager.RenderShadows(renderContext, cmd, globalCB, cullResults, hdCamera); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs index 297b6d56112..395f322a4d2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs @@ -592,7 +592,7 @@ internal void Dispatch(CommandBuffer cmd, HDCamera camera, int frameCount) } } - internal void UpdateShaderVariableGlobalCB(ConstantBuffer cb, HDCamera hdCamera) + internal void UpdateShaderVariableGlobalCB(ref ShaderVariablesGlobal cb, HDCamera hdCamera) { var settings = hdCamera.volumeStack.GetComponent(); bool aoEnabled = false; @@ -607,9 +607,9 @@ internal void UpdateShaderVariableGlobalCB(ConstantBuffer } if (aoEnabled) - cb.data._AmbientOcclusionParam = new Vector4(0f, 0f, 0f, settings.directLightingStrength.value); + cb._AmbientOcclusionParam = new Vector4(0f, 0f, 0f, settings.directLightingStrength.value); else - cb.data._AmbientOcclusionParam = Vector4.zero; + cb._AmbientOcclusionParam = Vector4.zero; } internal void PostDispatchWork(CommandBuffer cmd, HDCamera camera) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs index 4be43ab6ed7..f8565738f95 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs @@ -439,7 +439,7 @@ void LayoutResize() atlasShapeID++; } - public void RenderShadows(CullingResults cullResults, ConstantBuffer globalCB, FrameSettings frameSettings, ScriptableRenderContext renderContext, CommandBuffer cmd) + public void RenderShadows(CullingResults cullResults, in ShaderVariablesGlobal globalCB, FrameSettings frameSettings, ScriptableRenderContext renderContext, CommandBuffer cmd) { if (m_ShadowRequests.Count == 0) return; @@ -462,22 +462,22 @@ public void RenderShadows(CullingResults cullResults, ConstantBuffer globalCB; - public List shadowRequests; - public Material clearMaterial; - public bool debugClearAtlas; - public int atlasShaderID; - public BlurAlgorithm blurAlgorithm; + public ShaderVariablesGlobal globalCB; + public List shadowRequests; + public Material clearMaterial; + public bool debugClearAtlas; + public int atlasShaderID; + public BlurAlgorithm blurAlgorithm; // EVSM - public ComputeShader evsmShadowBlurMomentsCS; - public int momentAtlasShaderID; + public ComputeShader evsmShadowBlurMomentsCS; + public int momentAtlasShaderID; // IM - public ComputeShader imShadowBlurMomentsCS; + public ComputeShader imShadowBlurMomentsCS; } - RenderShadowsParameters PrepareRenderShadowsParameters(ConstantBuffer globalCB) + RenderShadowsParameters PrepareRenderShadowsParameters(in ShaderVariablesGlobal globalCB) { var parameters = new RenderShadowsParameters(); parameters.globalCB = globalCB; @@ -497,11 +497,11 @@ RenderShadowsParameters PrepareRenderShadowsParameters(ConstantBuffer.PushGlobal(cmd, globalCB, HDShaderIDs._ShaderVariablesGlobal); cmd.SetGlobalVectorArray(HDShaderIDs._ShadowClipPlanes, shadowRequest.frustumPlanes); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs index 1694d44ddb0..f3bf3abfe3b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs @@ -26,7 +26,7 @@ internal static ShadowResult ReadShadowResult(ShadowResult shadowResult, RenderG return result; } - internal ShadowResult RenderShadows(RenderGraph renderGraph, ConstantBuffer globalCB, HDCamera hdCamera, CullingResults cullResults) + internal ShadowResult RenderShadows(RenderGraph renderGraph, in ShaderVariablesGlobal globalCB, HDCamera hdCamera, CullingResults cullResults) { var result = new ShadowResult(); // Avoid to do any commands if there is no shadow to draw @@ -61,7 +61,7 @@ TextureHandle AllocateMomentAtlas(RenderGraph renderGraph, string name, int shad { colorFormat = GraphicsFormat.R32G32_SFloat, useMipMap = true, autoGenerateMips = false, name = name, enableRandomWrite = true }, shaderID); } - internal TextureHandle RenderShadows(RenderGraph renderGraph, CullingResults cullResults, ConstantBuffer globalCB, FrameSettings frameSettings, string shadowPassName) + internal TextureHandle RenderShadows(RenderGraph renderGraph, CullingResults cullResults, in ShaderVariablesGlobal globalCB, FrameSettings frameSettings, string shadowPassName) { TextureHandle result = new TextureHandle(); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs index 425e7f9139d..aa4a98c0dcc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs @@ -316,13 +316,13 @@ public static DirectionalShadowAlgorithm GetDirectionalShadowAlgorithm() return DirectionalShadowAlgorithm.PCF5x5; } - public void UpdateShaderVariablesGlobalCB(ConstantBuffer cb) + public void UpdateShaderVariablesGlobalCB(ref ShaderVariablesGlobal cb) { - cb.data._CascadeShadowCount = (uint)(m_CascadeCount + 1); - cb.data._ShadowAtlasSize = new Vector4(m_Atlas.width, m_Atlas.height, 1.0f / m_Atlas.width, 1.0f / m_Atlas.height); - cb.data._CascadeShadowAtlasSize = new Vector4(m_CascadeAtlas.width, m_CascadeAtlas.height, 1.0f / m_CascadeAtlas.width, 1.0f / m_CascadeAtlas.height); + cb._CascadeShadowCount = (uint)(m_CascadeCount + 1); + cb._ShadowAtlasSize = new Vector4(m_Atlas.width, m_Atlas.height, 1.0f / m_Atlas.width, 1.0f / m_Atlas.height); + cb._CascadeShadowAtlasSize = new Vector4(m_CascadeAtlas.width, m_CascadeAtlas.height, 1.0f / m_CascadeAtlas.width, 1.0f / m_CascadeAtlas.height); if (ShaderConfig.s_AreaLights == 1) - cb.data._AreaShadowAtlasSize = new Vector4(m_AreaLightShadowAtlas.width, m_AreaLightShadowAtlas.height, 1.0f / m_AreaLightShadowAtlas.width, 1.0f / m_AreaLightShadowAtlas.height); + cb._AreaShadowAtlasSize = new Vector4(m_AreaLightShadowAtlas.width, m_AreaLightShadowAtlas.height, 1.0f / m_AreaLightShadowAtlas.width, 1.0f / m_AreaLightShadowAtlas.height); } public void UpdateDirectionalShadowResolution(int resolution, int cascadeCount) @@ -685,7 +685,7 @@ unsafe public void PrepareGPUShadowDatas(CullingResults cullResults, HDCamera ca m_DirectionalShadowData.cascadeDirection.w = camera.volumeStack.GetComponent().cascadeShadowSplitCount.value; } - public void RenderShadows(ScriptableRenderContext renderContext, CommandBuffer cmd, ConstantBuffer globalCB, CullingResults cullResults, HDCamera hdCamera) + public void RenderShadows(ScriptableRenderContext renderContext, CommandBuffer cmd, in ShaderVariablesGlobal globalCB, CullingResults cullResults, HDCamera hdCamera) { // Avoid to do any commands if there is no shadow to draw if (m_ShadowRequestCount == 0) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index a95280760a7..9a168b47e77 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -206,7 +206,7 @@ public partial class HDRenderPipeline RTHandle m_DensityBufferHandle; RTHandle m_LightingBufferHandle; - ConstantBuffer m_ShaderVariablesVolumetricCB; + ShaderVariablesVolumetric m_ShaderVariablesVolumetricCB = new ShaderVariablesVolumetric(); // Is the feature globally disabled? bool m_SupportVolumetrics = false; @@ -254,8 +254,6 @@ void InitializeVolumetricLighting() m_PixelCoordToViewDirWS = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - m_ShaderVariablesVolumetricCB = new ConstantBuffer(); - CreateVolumetricLightingBuffers(); } @@ -400,8 +398,6 @@ void CleanupVolumetricLighting() // Note: No need to test for support volumetric here, we do saferelease and null assignation DestroyVolumetricLightingBuffers(); - m_ShaderVariablesVolumetricCB.Release(); - m_VolumeVoxelizationCS = null; m_VolumetricLightingCS = null; } @@ -463,7 +459,7 @@ static float CornetteShanksPhasePartConstant(float anisotropy) return (3.0f / (8.0f * Mathf.PI)) * (1.0f - g * g) / (2.0f + g * g); } - void UpdateShaderVariablesGlobalVolumetrics(ConstantBuffer cb, in RTHandleProperties sharedRTHandleProperties, HDCamera hdCamera) + void UpdateShaderVariablesGlobalVolumetrics(ref ShaderVariablesGlobal cb, in RTHandleProperties sharedRTHandleProperties, HDCamera hdCamera) { if (!Fog.IsVolumetricFogEnabled(hdCamera)) { @@ -475,14 +471,14 @@ void UpdateShaderVariablesGlobalVolumetrics(ConstantBuffer volumetricCB; - public ConstantBuffer lightListCB; + public ShaderVariablesVolumetric volumetricCB; + public ShaderVariablesLightList lightListCB; } - unsafe void SetPreconvolvedAmbientLightProbe(ConstantBuffer cb, HDCamera hdCamera, Fog fog) + unsafe void SetPreconvolvedAmbientLightProbe(ref ShaderVariablesVolumetric cb, HDCamera hdCamera, Fog fog) { SphericalHarmonicsL2 probeSH = SphericalHarmonicMath.UndoCosineRescaling(m_SkyManager.GetAmbientProbe(hdCamera)); probeSH = SphericalHarmonicMath.RescaleCoefficients(probeSH, fog.globalLightProbeDimmer.value); @@ -579,10 +575,10 @@ unsafe void SetPreconvolvedAmbientLightProbe(ConstantBuffer cb, HDCamera hdCamera, in Vector4 resolution, int frameIndex) + unsafe void UpdateShaderVariableslVolumetrics(ref ShaderVariablesVolumetric cb, HDCamera hdCamera, in Vector4 resolution, int frameIndex) { var fog = hdCamera.volumeStack.GetComponent(); var vFoV = hdCamera.camera.GetGateFittedFieldOfView() * Mathf.Deg2Rad; @@ -593,11 +589,11 @@ unsafe void UpdateShaderVariableslVolumetrics(ConstantBuffer.Push(cmd, parameters.volumetricCB, parameters.voxelizationCS, HDShaderIDs._ShaderVariablesVolumetric); + ConstantBuffer.Set(cmd, parameters.voxelizationCS, HDShaderIDs._ShaderVariablesLightList); // The shader defines GROUP_SIZE_1D = 8. cmd.DispatchCompute(parameters.voxelizationCS, parameters.voxelizationKernel, ((int)parameters.resolution.x + 7) / 8, ((int)parameters.resolution.y + 7) / 8, parameters.viewCount); @@ -737,17 +733,17 @@ static void GetHexagonalClosePackedSpheres7(Vector2[] coords) struct VolumetricLightingParameters { - public ComputeShader volumetricLightingCS; - public int volumetricLightingKernel; - public int volumetricFilteringKernelX; - public int volumetricFilteringKernelY; - public bool tiledLighting; - public Vector4 resolution; - public bool enableReprojection; - public int viewCount; - public bool filterVolume; - public ConstantBuffer volumetricCB; - public ConstantBuffer lightListCB; + public ComputeShader volumetricLightingCS; + public int volumetricLightingKernel; + public int volumetricFilteringKernelX; + public int volumetricFilteringKernelY; + public bool tiledLighting; + public Vector4 resolution; + public bool enableReprojection; + public int viewCount; + public bool filterVolume; + public ShaderVariablesVolumetric volumetricCB; + public ShaderVariablesLightList lightListCB; } VolumetricLightingParameters PrepareVolumetricLightingParameters(HDCamera hdCamera, int frameIndex) @@ -773,7 +769,7 @@ VolumetricLightingParameters PrepareVolumetricLightingParameters(HDCamera hdCame parameters.viewCount = hdCamera.viewCount; parameters.filterVolume = fog.filter.value; - UpdateShaderVariableslVolumetrics(m_ShaderVariablesVolumetricCB, hdCamera, parameters.resolution, frameIndex); + UpdateShaderVariableslVolumetrics(ref m_ShaderVariablesVolumetricCB, hdCamera, parameters.resolution, frameIndex); parameters.volumetricCB = m_ShaderVariablesVolumetricCB; parameters.lightListCB = m_ShaderVariablesLightListCB; @@ -800,8 +796,9 @@ static void VolumetricLightingPass( in VolumetricLightingParameters parameters, cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, HDShaderIDs._VBufferLightingFeedback, feedbackRT); // Write } - parameters.volumetricCB.Push(cmd, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesVolumetric, true); - parameters.lightListCB.Push(cmd, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesLightList, false); + ConstantBuffer.Push(cmd, parameters.volumetricCB, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesVolumetric); + ConstantBuffer.Set(cmd, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesLightList); + // The shader defines GROUP_SIZE_1D = 8. cmd.DispatchCompute(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, ((int)parameters.resolution.x + 7) / 8, ((int)parameters.resolution.y + 7) / 8, parameters.viewCount); } @@ -810,7 +807,7 @@ static void FilterVolumetricLighting(in VolumetricLightingParameters parameters, { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.VolumetricLightingFiltering))) { - parameters.volumetricCB.Push(cmd, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesVolumetric); + ConstantBuffer.Push(cmd, parameters.volumetricCB, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesVolumetric); // The shader defines GROUP_SIZE_1D = 8. cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricFilteringKernelX, HDShaderIDs._VBufferLightingFeedback, inputBuffer); // Read diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index 53a2b5e79f6..770ec38eb60 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -192,27 +192,27 @@ void SetDiffusionProfileAtIndex(DiffusionProfileSettings settings, int index) m_SSSDiffusionProfileUpdate[index] = settings.updateCount; } - unsafe void UpdateShaderVariablesGlobalSubsurface(ConstantBuffer cb, HDCamera hdCamera) + unsafe void UpdateShaderVariablesGlobalSubsurface(ref ShaderVariablesGlobal cb, HDCamera hdCamera) { UpdateCurrentDiffusionProfileSettings(hdCamera); - cb.data._DiffusionProfileCount = (uint)m_SSSActiveDiffusionProfileCount; - cb.data._EnableSubsurfaceScattering = hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering) ? 1u : 0u; - cb.data._TexturingModeFlags = m_SSSTexturingModeFlags; - cb.data._TransmissionFlags = m_SSSTransmissionFlags; + cb._DiffusionProfileCount = (uint)m_SSSActiveDiffusionProfileCount; + cb._EnableSubsurfaceScattering = hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering) ? 1u : 0u; + cb._TexturingModeFlags = m_SSSTexturingModeFlags; + cb._TransmissionFlags = m_SSSTransmissionFlags; for (int i = 0; i < m_SSSActiveDiffusionProfileCount; ++i) { for (int c = 0; c < 4; ++c) // Vector4 component { - cb.data._ThicknessRemaps[i * 4 + c] = m_SSSThicknessRemaps[i][c]; - cb.data._ShapeParams[i * 4 + c] = m_SSSShapeParams[i][c]; + cb._ThicknessRemaps[i * 4 + c] = m_SSSThicknessRemaps[i][c]; + cb._ShapeParams[i * 4 + c] = m_SSSShapeParams[i][c]; // To disable transmission, we simply nullify the transmissionTint - cb.data._TransmissionTintsAndFresnel0[i * 4 + c] = hdCamera.frameSettings.IsEnabled(FrameSettingsField.Transmission) ? m_SSSTransmissionTintsAndFresnel0[i][c] : m_SSSDisabledTransmissionTintsAndFresnel0[i][c]; - cb.data._WorldScales[i * 4 + c] = m_SSSWorldScales[i][c]; + cb._TransmissionTintsAndFresnel0[i * 4 + c] = hdCamera.frameSettings.IsEnabled(FrameSettingsField.Transmission) ? m_SSSTransmissionTintsAndFresnel0[i][c] : m_SSSDisabledTransmissionTintsAndFresnel0[i][c]; + cb._WorldScales[i * 4 + c] = m_SSSWorldScales[i][c]; } - cb.data._DiffusionProfileHashTable[i * 4] = m_SSSDiffusionProfileHashes[i]; + cb._DiffusionProfileHashTable[i * 4] = m_SSSDiffusionProfileHashes[i]; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs index f409557393b..3cb50e74246 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs @@ -561,57 +561,57 @@ internal static void CleanUnused() s_Cleanup.Clear(); } - unsafe internal void UpdateShaderVariableGlobalCB(ConstantBuffer cb, int frameCount) + unsafe internal void UpdateShaderVariableGlobalCB(ref ShaderVariablesGlobal cb, int frameCount) { bool taaEnabled = frameSettings.IsEnabled(FrameSettingsField.Postprocess) && antialiasing == AntialiasingMode.TemporalAntialiasing && camera.cameraType == CameraType.Game; - cb.data._ViewMatrix = mainViewConstants.viewMatrix; - cb.data._InvViewMatrix = mainViewConstants.invViewMatrix; - cb.data._ProjMatrix = mainViewConstants.projMatrix; - cb.data._InvProjMatrix = mainViewConstants.invProjMatrix; - cb.data._ViewProjMatrix = mainViewConstants.viewProjMatrix; - cb.data._CameraViewProjMatrix = mainViewConstants.viewProjMatrix; - cb.data._InvViewProjMatrix = mainViewConstants.invViewProjMatrix; - cb.data._NonJitteredViewProjMatrix = mainViewConstants.nonJitteredViewProjMatrix; - cb.data._PrevViewProjMatrix = mainViewConstants.prevViewProjMatrix; - cb.data._PrevInvViewProjMatrix = mainViewConstants.prevInvViewProjMatrix; - cb.data._WorldSpaceCameraPos_Internal = mainViewConstants.worldSpaceCameraPos; - cb.data._PrevCamPosRWS_Internal = mainViewConstants.prevWorldSpaceCameraPos; - cb.data._ScreenSize = screenSize; - cb.data._RTHandleScale = RTHandles.rtHandleProperties.rtHandleScale; - cb.data._RTHandleScaleHistory = m_HistoryRTSystem.rtHandleProperties.rtHandleScale; - cb.data._ZBufferParams = zBufferParams; - cb.data._ProjectionParams = projectionParams; - cb.data.unity_OrthoParams = unity_OrthoParams; - cb.data._ScreenParams = screenParams; + cb._ViewMatrix = mainViewConstants.viewMatrix; + cb._InvViewMatrix = mainViewConstants.invViewMatrix; + cb._ProjMatrix = mainViewConstants.projMatrix; + cb._InvProjMatrix = mainViewConstants.invProjMatrix; + cb._ViewProjMatrix = mainViewConstants.viewProjMatrix; + cb._CameraViewProjMatrix = mainViewConstants.viewProjMatrix; + cb._InvViewProjMatrix = mainViewConstants.invViewProjMatrix; + cb._NonJitteredViewProjMatrix = mainViewConstants.nonJitteredViewProjMatrix; + cb._PrevViewProjMatrix = mainViewConstants.prevViewProjMatrix; + cb._PrevInvViewProjMatrix = mainViewConstants.prevInvViewProjMatrix; + cb._WorldSpaceCameraPos_Internal = mainViewConstants.worldSpaceCameraPos; + cb._PrevCamPosRWS_Internal = mainViewConstants.prevWorldSpaceCameraPos; + cb._ScreenSize = screenSize; + cb._RTHandleScale = RTHandles.rtHandleProperties.rtHandleScale; + cb._RTHandleScaleHistory = m_HistoryRTSystem.rtHandleProperties.rtHandleScale; + cb._ZBufferParams = zBufferParams; + cb._ProjectionParams = projectionParams; + cb.unity_OrthoParams = unity_OrthoParams; + cb._ScreenParams = screenParams; for (int i = 0; i < 6; ++i) for (int j = 0; j < 4; ++j) - cb.data._FrustumPlanes[i * 4 + j] = frustumPlaneEquations[i][j]; - cb.data._TaaFrameInfo = new Vector4(taaSharpenStrength, 0, taaFrameIndex, taaEnabled ? 1 : 0); - cb.data._TaaJitterStrength = taaJitter; - cb.data._ColorPyramidLodCount = colorPyramidHistoryMipCount; + cb._FrustumPlanes[i * 4 + j] = frustumPlaneEquations[i][j]; + cb._TaaFrameInfo = new Vector4(taaSharpenStrength, 0, taaFrameIndex, taaEnabled ? 1 : 0); + cb._TaaJitterStrength = taaJitter; + cb._ColorPyramidLodCount = colorPyramidHistoryMipCount; float ct = time; float pt = lastTime; float dt = Time.deltaTime; float sdt = Time.smoothDeltaTime; - cb.data._Time = new Vector4(ct * 0.05f, ct, ct * 2.0f, ct * 3.0f); - cb.data._SinTime = new Vector4(Mathf.Sin(ct * 0.125f), Mathf.Sin(ct * 0.25f), Mathf.Sin(ct * 0.5f), Mathf.Sin(ct)); - cb.data._CosTime = new Vector4(Mathf.Cos(ct * 0.125f), Mathf.Cos(ct * 0.25f), Mathf.Cos(ct * 0.5f), Mathf.Cos(ct)); - cb.data.unity_DeltaTime = new Vector4(dt, 1.0f / dt, sdt, 1.0f / sdt); - cb.data._TimeParameters = new Vector4(ct, Mathf.Sin(ct), Mathf.Cos(ct), 0.0f); - cb.data._LastTimeParameters = new Vector4(pt, Mathf.Sin(pt), Mathf.Cos(pt), 0.0f); - cb.data._FrameCount = frameCount; - cb.data._XRViewCount = (uint)viewCount; + cb._Time = new Vector4(ct * 0.05f, ct, ct * 2.0f, ct * 3.0f); + cb._SinTime = new Vector4(Mathf.Sin(ct * 0.125f), Mathf.Sin(ct * 0.25f), Mathf.Sin(ct * 0.5f), Mathf.Sin(ct)); + cb._CosTime = new Vector4(Mathf.Cos(ct * 0.125f), Mathf.Cos(ct * 0.25f), Mathf.Cos(ct * 0.5f), Mathf.Cos(ct)); + cb.unity_DeltaTime = new Vector4(dt, 1.0f / dt, sdt, 1.0f / sdt); + cb._TimeParameters = new Vector4(ct, Mathf.Sin(ct), Mathf.Cos(ct), 0.0f); + cb._LastTimeParameters = new Vector4(pt, Mathf.Sin(pt), Mathf.Cos(pt), 0.0f); + cb._FrameCount = frameCount; + cb._XRViewCount = (uint)viewCount; float exposureMultiplierForProbes = 1.0f / Mathf.Max(probeRangeCompressionFactor, 1e-6f); - cb.data._ProbeExposureScale = exposureMultiplierForProbes; + cb._ProbeExposureScale = exposureMultiplierForProbes; } - + // Set up UnityPerView CBuffer. internal void SetupGlobalParams(CommandBuffer cmd, int frameCount) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 6aa95db8c26..2206c500011 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -93,9 +93,9 @@ void BuildGPULightList(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle class PushGlobalCameraParamPassData { - public HDCamera hdCamera; - public int frameCount; - public ConstantBuffer globalCB; + public HDCamera hdCamera; + public int frameCount; + public ShaderVariablesGlobal globalCB; } @@ -110,9 +110,9 @@ void PushGlobalCameraParams(RenderGraph renderGraph, HDCamera hdCamera) builder.SetRenderFunc( (PushGlobalCameraParamPassData data, RenderGraphContext context) => { - data.hdCamera.UpdateShaderVariableGlobalCB(data.globalCB, data.frameCount); + data.hdCamera.UpdateShaderVariableGlobalCB(ref data.globalCB, data.frameCount); data.hdCamera.SetupGlobalParams(context.cmd, data.frameCount); - data.globalCB.PushGlobal(context.cmd, HDShaderIDs._ShaderVariablesGlobal, true); + ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); }); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index e043894290e..ead0a02ee55 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -582,11 +582,11 @@ TextureHandle DownsampleDepthForLowResTransparency(RenderGraph renderGraph, HDCa class RenderLowResTransparentPassData { - public ConstantBuffer globalCB; - public FrameSettings frameSettings; - public RendererListHandle rendererList; - public TextureHandle lowResBuffer; - public TextureHandle downsampledDepthBuffer; + public ShaderVariablesGlobal globalCB; + public FrameSettings frameSettings; + public RendererListHandle rendererList; + public TextureHandle lowResBuffer; + public TextureHandle downsampledDepthBuffer; } TextureHandle RenderLowResTransparent(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle downsampledDepth, CullingResults cullingResults) @@ -607,13 +607,13 @@ TextureHandle RenderLowResTransparent(RenderGraph renderGraph, HDCamera hdCamera builder.SetRenderFunc( (RenderLowResTransparentPassData data, RenderGraphContext context) => { - UpdateOffscreenRenderingConstants(data.globalCB, true, 2u); - data.globalCB.PushGlobal(context.cmd, HDShaderIDs._ShaderVariablesGlobal, true); + UpdateOffscreenRenderingConstants(ref data.globalCB, true, 2u); + ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, context.resources.GetRendererList(data.rendererList)); - UpdateOffscreenRenderingConstants(data.globalCB, false, 1u); - data.globalCB.PushGlobal(context.cmd, HDShaderIDs._ShaderVariablesGlobal, true); + UpdateOffscreenRenderingConstants(ref data.globalCB, false, 1u); + ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); }); return passData.lowResBuffer; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index c16bba09dad..9565c9a1e9d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -168,7 +168,7 @@ internal static Volume GetOrCreateDefaultVolume() Lazy m_CustomPassDepthBuffer; // Constant Buffers - ConstantBuffer m_ShaderVariablesGlobalCB; + ShaderVariablesGlobal m_ShaderVariablesGlobalCB = new ShaderVariablesGlobal(); // The current MSAA count MSAASamples m_MSAASamples; @@ -484,8 +484,6 @@ public HDRenderPipeline(HDRenderPipelineAsset asset, HDRenderPipelineAsset defau InitializePrepass(m_Asset); m_ColorResolveMaterial = CoreUtils.CreateEngineMaterial(asset.renderPipelineResources.shaders.colorResolvePS); - - InitializeConstantBuffers(); } #if UNITY_EDITOR @@ -800,16 +798,6 @@ void InitializeRenderStateBlocks() }; } - void InitializeConstantBuffers() - { - m_ShaderVariablesGlobalCB = new ConstantBuffer(); - } - - void DestroyConstantBuffers() - { - m_ShaderVariablesGlobalCB.Release(); - } - /// /// Disposable pattern implementation. /// @@ -900,8 +888,6 @@ protected override void Dispose(bool disposing) CleanupPrepass(); CoreUtils.Destroy(m_ColorResolveMaterial); - DestroyConstantBuffers(); - #if UNITY_EDITOR SceneViewDrawMode.ResetDrawMode(); @@ -967,51 +953,51 @@ void Resize(HDCamera hdCamera) void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) { - hdCamera.UpdateShaderVariableGlobalCB(m_ShaderVariablesGlobalCB, m_FrameCount); - Fog.UpdateShaderVariablesGlobalCB(m_ShaderVariablesGlobalCB, hdCamera); - UpdateShaderVariablesGlobalSubsurface(m_ShaderVariablesGlobalCB, hdCamera); - UpdateShaderVariablesGlobalDecal(m_ShaderVariablesGlobalCB, hdCamera); - UpdateShaderVariablesGlobalVolumetrics(m_ShaderVariablesGlobalCB, RTHandles.rtHandleProperties, hdCamera); - m_ShadowManager.UpdateShaderVariablesGlobalCB(m_ShaderVariablesGlobalCB); - UpdateShaderVariablesGlobalLightLoop(m_ShaderVariablesGlobalCB, hdCamera); - m_AmbientOcclusionSystem.UpdateShaderVariableGlobalCB(m_ShaderVariablesGlobalCB, hdCamera); + hdCamera.UpdateShaderVariableGlobalCB(ref m_ShaderVariablesGlobalCB, m_FrameCount); + Fog.UpdateShaderVariablesGlobalCB(ref m_ShaderVariablesGlobalCB, hdCamera); + UpdateShaderVariablesGlobalSubsurface(ref m_ShaderVariablesGlobalCB, hdCamera); + UpdateShaderVariablesGlobalDecal(ref m_ShaderVariablesGlobalCB, hdCamera); + UpdateShaderVariablesGlobalVolumetrics(ref m_ShaderVariablesGlobalCB, RTHandles.rtHandleProperties, hdCamera); + m_ShadowManager.UpdateShaderVariablesGlobalCB(ref m_ShaderVariablesGlobalCB); + UpdateShaderVariablesGlobalLightLoop(ref m_ShaderVariablesGlobalCB, hdCamera); + m_AmbientOcclusionSystem.UpdateShaderVariableGlobalCB(ref m_ShaderVariablesGlobalCB, hdCamera); // Misc MicroShadowing microShadowingSettings = hdCamera.volumeStack.GetComponent(); - m_ShaderVariablesGlobalCB.data._MicroShadowOpacity = microShadowingSettings.enable.value ? microShadowingSettings.opacity.value : 0.0f; + m_ShaderVariablesGlobalCB._MicroShadowOpacity = microShadowingSettings.enable.value ? microShadowingSettings.opacity.value : 0.0f; HDShadowSettings shadowSettings = hdCamera.volumeStack.GetComponent(); - m_ShaderVariablesGlobalCB.data._DirectionalTransmissionMultiplier = shadowSettings.directionalTransmissionMultiplier.value; + m_ShaderVariablesGlobalCB._DirectionalTransmissionMultiplier = shadowSettings.directionalTransmissionMultiplier.value; ScreenSpaceRefraction ssRefraction = hdCamera.volumeStack.GetComponent(); - m_ShaderVariablesGlobalCB.data._SSRefractionInvScreenWeightDistance = 1.0f / ssRefraction.screenFadeDistance.value; + m_ShaderVariablesGlobalCB._SSRefractionInvScreenWeightDistance = 1.0f / ssRefraction.screenFadeDistance.value; - m_ShaderVariablesGlobalCB.data._IndirectLightingMultiplier = new Vector4(hdCamera.volumeStack.GetComponent().indirectDiffuseIntensity.value, 0, 0, 0); - m_ShaderVariablesGlobalCB.data._OffScreenRendering = 0; - m_ShaderVariablesGlobalCB.data._OffScreenDownsampleFactor = 1; - m_ShaderVariablesGlobalCB.data._ReplaceDiffuseForIndirect = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ReplaceDiffuseForIndirect) ? 1.0f : 0.0f; - m_ShaderVariablesGlobalCB.data._EnableSkyReflection = hdCamera.frameSettings.IsEnabled(FrameSettingsField.SkyReflection) ? 1u : 0u; - m_ShaderVariablesGlobalCB.data._ContactShadowOpacity = m_ContactShadows.opacity.value; + m_ShaderVariablesGlobalCB._IndirectLightingMultiplier = new Vector4(hdCamera.volumeStack.GetComponent().indirectDiffuseIntensity.value, 0, 0, 0); + m_ShaderVariablesGlobalCB._OffScreenRendering = 0; + m_ShaderVariablesGlobalCB._OffScreenDownsampleFactor = 1; + m_ShaderVariablesGlobalCB._ReplaceDiffuseForIndirect = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ReplaceDiffuseForIndirect) ? 1.0f : 0.0f; + m_ShaderVariablesGlobalCB._EnableSkyReflection = hdCamera.frameSettings.IsEnabled(FrameSettingsField.SkyReflection) ? 1u : 0u; + m_ShaderVariablesGlobalCB._ContactShadowOpacity = m_ContactShadows.opacity.value; int coarseStencilWidth = HDUtils.DivRoundUp(hdCamera.actualWidth, 8); int coarseStencilHeight = HDUtils.DivRoundUp(hdCamera.actualHeight, 8); - m_ShaderVariablesGlobalCB.data._CoarseStencilBufferSize = new Vector4(coarseStencilWidth, coarseStencilHeight, 1.0f / coarseStencilWidth, 1.0f / coarseStencilHeight); + m_ShaderVariablesGlobalCB._CoarseStencilBufferSize = new Vector4(coarseStencilWidth, coarseStencilHeight, 1.0f / coarseStencilWidth, 1.0f / coarseStencilHeight); - m_ShaderVariablesGlobalCB.data._RaytracingFrameIndex = RayTracingFrameIndex(hdCamera); + m_ShaderVariablesGlobalCB._RaytracingFrameIndex = RayTracingFrameIndex(hdCamera); if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) { var settings = hdCamera.volumeStack.GetComponent(); bool usesRaytracedReflections = hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value; - m_ShaderVariablesGlobalCB.data._UseRayTracedReflections = usesRaytracedReflections ? 1 : 0; - m_ShaderVariablesGlobalCB.data._RaytracedIndirectDiffuse = ValidIndirectDiffuseState(hdCamera) ? 1 : 0; + m_ShaderVariablesGlobalCB._UseRayTracedReflections = usesRaytracedReflections ? 1 : 0; + m_ShaderVariablesGlobalCB._RaytracedIndirectDiffuse = ValidIndirectDiffuseState(hdCamera) ? 1 : 0; } else { - m_ShaderVariablesGlobalCB.data._UseRayTracedReflections = 0; - m_ShaderVariablesGlobalCB.data._RaytracedIndirectDiffuse = 0; + m_ShaderVariablesGlobalCB._UseRayTracedReflections = 0; + m_ShaderVariablesGlobalCB._RaytracedIndirectDiffuse = 0; } - m_ShaderVariablesGlobalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); } void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd) @@ -2151,9 +2137,9 @@ void AsyncSSAODispatch(CommandBuffer c, HDGPUAsyncTaskParams a) // This call overwrites camera properties passed to the shader system. RenderShadowMaps(renderContext, cmd, m_ShaderVariablesGlobalCB, cullingResults, hdCamera); - hdCamera.UpdateShaderVariableGlobalCB(m_ShaderVariablesGlobalCB, m_FrameCount); - m_ShaderVariablesGlobalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); - } + hdCamera.UpdateShaderVariableGlobalCB(ref m_ShaderVariablesGlobalCB, m_FrameCount); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); + } hdCamera.xr.StartSinglePass(cmd); @@ -3167,16 +3153,16 @@ RendererListDesc PrepareMeshDecalsRendererList(CullingResults cullingResults, HD return desc; } - void UpdateShaderVariablesGlobalDecal(ConstantBuffer cb, HDCamera hdCamera) + void UpdateShaderVariablesGlobalDecal(ref ShaderVariablesGlobal cb, HDCamera hdCamera) { if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.Decals)) { - cb.data._EnableDecals = 1; - cb.data._DecalAtlasResolution = new Vector2(HDUtils.hdrpSettings.decalSettings.atlasWidth, HDUtils.hdrpSettings.decalSettings.atlasHeight); + cb._EnableDecals = 1; + cb._DecalAtlasResolution = new Vector2(HDUtils.hdrpSettings.decalSettings.atlasWidth, HDUtils.hdrpSettings.decalSettings.atlasHeight); } else { - cb.data._EnableDecals = 0; + cb._EnableDecals = 0; } } @@ -3671,8 +3657,8 @@ void RenderLowResTransparent(CullingResults cullResults, HDCamera hdCamera, Scri using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.LowResTransparent))) { - UpdateOffscreenRenderingConstants(m_ShaderVariablesGlobalCB, true, 2u); - m_ShaderVariablesGlobalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); + UpdateOffscreenRenderingConstants(ref m_ShaderVariablesGlobalCB, true, 2u); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); CoreUtils.SetRenderTarget(cmd, m_LowResTransparentBuffer, m_SharedRTManager.GetLowResDepthBuffer(), clearFlag: ClearFlag.Color, Color.black); RenderQueueRange transparentRange = HDRenderQueue.k_RenderQueue_LowTransparent; @@ -3680,8 +3666,8 @@ void RenderLowResTransparent(CullingResults cullResults, HDCamera hdCamera, Scri var rendererList = RendererList.Create(CreateTransparentRendererListDesc(cullResults, hdCamera.camera, passNames, m_CurrentRendererConfigurationBakedLighting, HDRenderQueue.k_RenderQueue_LowTransparent)); DrawTransparentRendererList(renderContext, cmd, hdCamera.frameSettings, rendererList); - UpdateOffscreenRenderingConstants(m_ShaderVariablesGlobalCB, false, 1u); - m_ShaderVariablesGlobalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); + UpdateOffscreenRenderingConstants(ref m_ShaderVariablesGlobalCB, false, 1u); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); } } @@ -4421,9 +4407,9 @@ void ClearBuffers(HDCamera hdCamera, CommandBuffer cmd) struct PostProcessParameters { - public ConstantBuffer globalCB; + public ShaderVariablesGlobal globalCB; - public HDCamera hdCamera; + public HDCamera hdCamera; public bool postProcessIsFinalPass; public bool flipYInPostProcess; public BlueNoise blueNoise; @@ -4508,10 +4494,10 @@ RTHandle GetAfterPostProcessOffScreenBuffer() return m_GbufferManager.GetBuffer(0); } - static void UpdateOffscreenRenderingConstants(ConstantBuffer cb, bool enabled, uint factor) + static void UpdateOffscreenRenderingConstants(ref ShaderVariablesGlobal cb, bool enabled, uint factor) { - cb.data._OffScreenRendering = enabled ? 1u : 0u; - cb.data._OffScreenDownsampleFactor = factor; + cb._OffScreenRendering = enabled ? 1u : 0u; + cb._OffScreenDownsampleFactor = factor; } static void RenderAfterPostProcess( PostProcessParameters parameters, @@ -4528,17 +4514,17 @@ static void RenderAfterPostProcess( PostProcessParameters parameters, // The issue is that the only available depth buffer is jittered so pixels would wobble around depth tested edges. // In order to avoid that we decide that objects rendered after Post processes while TAA is active will not benefit from the depth buffer so we disable it. parameters.hdCamera.UpdateAllViewConstants(false); - parameters.hdCamera.UpdateShaderVariableGlobalCB(parameters.globalCB, parameters.frameCount); + parameters.hdCamera.UpdateShaderVariableGlobalCB(ref parameters.globalCB, parameters.frameCount); - UpdateOffscreenRenderingConstants(parameters.globalCB, true, 1); - parameters.globalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); + UpdateOffscreenRenderingConstants(ref parameters.globalCB, true, 1); + ConstantBuffer.PushGlobal(cmd, parameters.globalCB, HDShaderIDs._ShaderVariablesGlobal); DrawOpaqueRendererList(renderContext, cmd, parameters.hdCamera.frameSettings, opaqueAfterPostProcessRendererList); // Setup off-screen transparency here DrawTransparentRendererList(renderContext, cmd, parameters.hdCamera.frameSettings, transparentAfterPostProcessRendererList); - UpdateOffscreenRenderingConstants(parameters.globalCB, false, 1); - parameters.globalCB.PushGlobal(cmd, HDShaderIDs._ShaderVariablesGlobal, true); + UpdateOffscreenRenderingConstants(ref parameters.globalCB, false, 1); + ConstantBuffer.PushGlobal(cmd, parameters.globalCB, HDShaderIDs._ShaderVariablesGlobal); } } From 1a00f9a4e50d443172074ccc1f69b3115d07a317 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 20 Mar 2020 11:53:02 +0100 Subject: [PATCH 44/92] Update test screenshot --- .../WindowsEditor/Direct3D11/None/2203_PlanarProbes.png | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/None/2203_PlanarProbes.png b/TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/None/2203_PlanarProbes.png index 65a4bb37eeb..165ef79ea3c 100644 --- a/TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/None/2203_PlanarProbes.png +++ b/TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/None/2203_PlanarProbes.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9c66daf9b663889178fa230c66cbd1ba0d9cde82582a23d8868a8d9371220bb1 -size 257728 +oid sha256:60c1060c81f32c243029cdbec19c825ae19b8316d8973d3035b249109f29fcdc +size 256035 From 235415ed3501bab8f66ca2953ad4e4eef484d940 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 20 Mar 2020 12:45:17 +0100 Subject: [PATCH 45/92] Fixed constant buffer generation to use macros. --- .../Editor/ShaderGenerator/ShaderTypeGeneration.cs | 9 ++++++--- .../Runtime/Lighting/LightLoop/LightLoop.cs.hlsl | 5 ++--- .../Lighting/LightLoop/cleardispatchindirect.compute | 1 + .../VolumetricLighting/VolumetricLighting.cs.hlsl | 5 ++--- .../Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl | 5 ++--- 5 files changed, 13 insertions(+), 12 deletions(-) diff --git a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs index 3cc6d9b5d75..38aab2df435 100644 --- a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs +++ b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs @@ -410,8 +410,7 @@ public string EmitTypeDecl() if (attr.generateCBuffer) { - shaderText += "cbuffer " + type.Name + "\n"; - shaderText += "{\n"; + shaderText += "CBUFFER_START(" + type.Name + ")\n"; } else if (!attr.omitStructDeclaration) { @@ -424,7 +423,11 @@ public string EmitTypeDecl() shaderText += " " + shaderFieldInfo.ToString() + "\n"; } - if (attr.generateCBuffer || !attr.omitStructDeclaration) + if (attr.generateCBuffer) + { + shaderText += "CBUFFER_END\n"; + } + else if (!attr.omitStructDeclaration) { shaderText += "};\n"; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index f8762970055..720ac576265 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -90,8 +90,7 @@ struct LightVolumeData // Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesLightList // PackingRules = Exact -cbuffer ShaderVariablesLightList -{ +CBUFFER_START(ShaderVariablesLightList) float4x4 g_mInvScrProjectionArr[2]; float4x4 g_mScrProjectionArr[2]; float4x4 g_mInvProjectionArr[2]; @@ -105,7 +104,7 @@ cbuffer ShaderVariablesLightList int _EnvLightIndexShift; int _DecalIndexShift; int _DensityVolumeIndexShift; -}; +CBUFFER_END // // Accessors for UnityEngine.Rendering.HighDefinition.SFiniteLightBound diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/cleardispatchindirect.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/cleardispatchindirect.compute index bab8796f4e1..08c687da314 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/cleardispatchindirect.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/cleardispatchindirect.compute @@ -4,6 +4,7 @@ RWBuffer g_DispatchIndirectBuffer : register( u0 ); // Indirect arguments have to be in a _buffer_, not a structured buffer +#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #ifdef PLATFORM_LANE_COUNT diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl index 6b0fdd171ac..7394831c232 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl @@ -22,8 +22,7 @@ struct DensityVolumeEngineData // Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesVolumetric // PackingRules = Exact -cbuffer ShaderVariablesVolumetric -{ +CBUFFER_START(ShaderVariablesVolumetric) float4x4 _VBufferCoordToViewDirWS[2]; float _VBufferUnitDepthTexelSpacing; uint _NumVisibleDensityVolumes; @@ -38,7 +37,7 @@ cbuffer ShaderVariablesVolumetric float4 _VBufferPrevDepthDecodingParams; uint _NumTileBigTileX; uint _NumTileBigTileY; -}; +CBUFFER_END // // Accessors for UnityEngine.Rendering.HighDefinition.DensityVolumeEngineData diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 074401ea57d..1e8ad26f53e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -12,8 +12,7 @@ // Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesGlobal // PackingRules = Exact -cbuffer ShaderVariablesGlobal -{ +CBUFFER_START(ShaderVariablesGlobal) float4x4 _ViewMatrix; float4x4 _InvViewMatrix; float4x4 _ProjMatrix; @@ -130,7 +129,7 @@ cbuffer ShaderVariablesGlobal int _UseRayTracedReflections; int _RaytracingFrameIndex; float _Pad7; -}; +CBUFFER_END #endif From f839e59d88eb458fcab47edf7fbaa1434cb7ca34 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 20 Mar 2020 16:41:46 +0100 Subject: [PATCH 46/92] Implemented XR global constant buffer. --- .../Runtime/RenderPipeline/Camera/HDCamera.cs | 73 ++++++------------- .../HDRenderPipeline.LightLoop.cs | 7 +- .../RenderPipeline/HDRenderPipeline.cs | 13 ++-- .../RenderPipeline/HDStringConstants.cs | 21 +----- .../ShaderLibrary/ShaderVariables.hlsl | 21 +----- .../ShaderLibrary/ShaderVariablesXR.cs | 38 ++++++++++ .../ShaderLibrary/ShaderVariablesXR.cs.hlsl | 27 +++++++ .../ShaderVariablesXR.cs.hlsl.meta | 9 +++ .../ShaderLibrary/ShaderVariablesXR.cs.meta | 11 +++ 9 files changed, 122 insertions(+), 98 deletions(-) create mode 100644 com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs create mode 100644 com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl create mode 100644 com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl.meta create mode 100644 com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.meta diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs index ad51e3ff6a9..16390d28c11 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs @@ -560,7 +560,7 @@ internal static void CleanUnused() s_Cleanup.Clear(); } - unsafe internal void UpdateShaderVariableGlobalCB(ref ShaderVariablesGlobal cb, int frameCount) + unsafe internal void UpdateShaderVariablesGlobalCB(ref ShaderVariablesGlobal cb, int frameCount) { bool taaEnabled = frameSettings.IsEnabled(FrameSettingsField.Postprocess) && antialiasing == AntialiasingMode.TemporalAntialiasing @@ -611,48 +611,32 @@ unsafe internal void UpdateShaderVariableGlobalCB(ref ShaderVariablesGlobal cb, } - // Set up UnityPerView CBuffer. - internal void SetupGlobalParams(CommandBuffer cmd, int frameCount) + unsafe internal void UpdateShaderVariablesXRCB(ref ShaderVariablesXR cb) { - // XRTODO: qualify this code with xr.singlePassEnabled when compute shaders can use keywords - if (true) + for (int i = 0; i < viewCount; i++) { - // Convert AoS to SoA for GPU constant buffer until we can use StructuredBuffer via command buffer - // XRTODO: use the new API and remove this code - for (int i = 0; i < viewCount; i++) + for (int j = 0; j < 16; ++j) { - m_XRViewMatrix[i] = m_XRViewConstants[i].viewMatrix; - m_XRInvViewMatrix[i] = m_XRViewConstants[i].invViewMatrix; - m_XRProjMatrix[i] = m_XRViewConstants[i].projMatrix; - m_XRInvProjMatrix[i] = m_XRViewConstants[i].invProjMatrix; - m_XRViewProjMatrix[i] = m_XRViewConstants[i].viewProjMatrix; - m_XRInvViewProjMatrix[i] = m_XRViewConstants[i].invViewProjMatrix; - m_XRNonJitteredViewProjMatrix[i] = m_XRViewConstants[i].nonJitteredViewProjMatrix; - m_XRPrevViewProjMatrix[i] = m_XRViewConstants[i].prevViewProjMatrix; - m_XRPrevInvViewProjMatrix[i] = m_XRViewConstants[i].prevInvViewProjMatrix; - m_XRPrevViewProjMatrixNoCameraTrans[i] = m_XRViewConstants[i].prevViewProjMatrixNoCameraTrans; - m_XRPixelCoordToViewDirWS[i] = m_XRViewConstants[i].pixelCoordToViewDirWS; - m_XRWorldSpaceCameraPos[i] = m_XRViewConstants[i].worldSpaceCameraPos; - m_XRWorldSpaceCameraPosViewOffset[i] = m_XRViewConstants[i].worldSpaceCameraPosViewOffset; - m_XRPrevWorldSpaceCameraPos[i] = m_XRViewConstants[i].prevWorldSpaceCameraPos; + cb._XRViewMatrix[i * 16 + j] = m_XRViewConstants[i].viewMatrix[j]; + cb._XRInvViewMatrix[i * 16 + j] = m_XRViewConstants[i].invViewMatrix[j]; + cb._XRProjMatrix[i * 16 + j] = m_XRViewConstants[i].projMatrix[j]; + cb._XRInvProjMatrix[i * 16 + j] = m_XRViewConstants[i].invProjMatrix[j]; + cb._XRViewProjMatrix[i * 16 + j] = m_XRViewConstants[i].viewProjMatrix[j]; + cb._XRInvViewProjMatrix[i * 16 + j] = m_XRViewConstants[i].invViewProjMatrix[j]; + cb._XRNonJitteredViewProjMatrix[i * 16 + j] = m_XRViewConstants[i].nonJitteredViewProjMatrix[j]; + cb._XRPrevViewProjMatrix[i * 16 + j] = m_XRViewConstants[i].prevViewProjMatrix[j]; + cb._XRPrevInvViewProjMatrix[i * 16 + j] = m_XRViewConstants[i].prevInvViewProjMatrix[j]; + cb._XRPrevViewProjMatrixNoCameraTrans[i * 16 + j] = m_XRViewConstants[i].prevViewProjMatrixNoCameraTrans[j]; + cb._XRPixelCoordToViewDirWS[i * 16 + j] = m_XRViewConstants[i].pixelCoordToViewDirWS[j]; } - cmd.SetGlobalMatrixArray(HDShaderIDs._XRViewMatrix, m_XRViewMatrix); - cmd.SetGlobalMatrixArray(HDShaderIDs._XRInvViewMatrix, m_XRInvViewMatrix); - cmd.SetGlobalMatrixArray(HDShaderIDs._XRProjMatrix, m_XRProjMatrix); - cmd.SetGlobalMatrixArray(HDShaderIDs._XRInvProjMatrix, m_XRInvProjMatrix); - cmd.SetGlobalMatrixArray(HDShaderIDs._XRViewProjMatrix, m_XRViewProjMatrix); - cmd.SetGlobalMatrixArray(HDShaderIDs._XRInvViewProjMatrix, m_XRInvViewProjMatrix); - cmd.SetGlobalMatrixArray(HDShaderIDs._XRNonJitteredViewProjMatrix, m_XRNonJitteredViewProjMatrix); - cmd.SetGlobalMatrixArray(HDShaderIDs._XRPrevViewProjMatrix, m_XRPrevViewProjMatrix); - cmd.SetGlobalMatrixArray(HDShaderIDs._XRPrevInvViewProjMatrix, m_XRPrevInvViewProjMatrix); - cmd.SetGlobalMatrixArray(HDShaderIDs._XRPrevViewProjMatrixNoCameraTrans, m_XRPrevViewProjMatrixNoCameraTrans); - cmd.SetGlobalMatrixArray(HDShaderIDs._XRPixelCoordToViewDirWS, m_XRPixelCoordToViewDirWS); - cmd.SetGlobalVectorArray(HDShaderIDs._XRWorldSpaceCameraPos, m_XRWorldSpaceCameraPos); - cmd.SetGlobalVectorArray(HDShaderIDs._XRWorldSpaceCameraPosViewOffset, m_XRWorldSpaceCameraPosViewOffset); - cmd.SetGlobalVectorArray(HDShaderIDs._XRPrevWorldSpaceCameraPos, m_XRPrevWorldSpaceCameraPos); + for (int j = 0; j < 3; ++j) // Inputs are vec3 but we align CB on float4 + { + cb._XRWorldSpaceCameraPos[i * 4 + j] = m_XRViewConstants[i].worldSpaceCameraPos[j]; + cb._XRWorldSpaceCameraPosViewOffset[i * 4 + j] = m_XRViewConstants[i].worldSpaceCameraPosViewOffset[j]; + cb._XRPrevWorldSpaceCameraPos[i * 4 + j] = m_XRViewConstants[i].prevWorldSpaceCameraPos[j]; + } } - } internal void AllocateAmbientOcclusionHistoryBuffer(float scaleFactor) @@ -806,21 +790,6 @@ public RTHandle Allocator(string id, int frameIndex, RTHandleSystem rtHandleSyst float m_AmbientOcclusionResolutionScale = 0.0f; // Factor used to track if history should be reallocated for Ambient Occlusion ViewConstants[] m_XRViewConstants; - // XR View Constants arrays (required due to limitations of API for StructuredBuffer) - Matrix4x4[] m_XRViewMatrix = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_XRInvViewMatrix = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_XRProjMatrix = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_XRInvProjMatrix = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_XRViewProjMatrix = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_XRInvViewProjMatrix = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_XRNonJitteredViewProjMatrix = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_XRPrevViewProjMatrix = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_XRPrevInvViewProjMatrix = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_XRPrevViewProjMatrixNoCameraTrans = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Matrix4x4[] m_XRPixelCoordToViewDirWS = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - Vector4[] m_XRWorldSpaceCameraPos = new Vector4[ShaderConfig.s_XrMaxViews]; - Vector4[] m_XRWorldSpaceCameraPosViewOffset = new Vector4[ShaderConfig.s_XrMaxViews]; - Vector4[] m_XRPrevWorldSpaceCameraPos = new Vector4[ShaderConfig.s_XrMaxViews]; // Recorder specific IEnumerator> m_RecorderCaptureActions; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 2206c500011..16ab26b3381 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -96,6 +96,7 @@ class PushGlobalCameraParamPassData public HDCamera hdCamera; public int frameCount; public ShaderVariablesGlobal globalCB; + public ShaderVariablesXR xrCB; } @@ -106,13 +107,15 @@ void PushGlobalCameraParams(RenderGraph renderGraph, HDCamera hdCamera) passData.hdCamera = hdCamera; passData.frameCount = m_FrameCount; passData.globalCB = m_ShaderVariablesGlobalCB; + passData.xrCB = m_ShaderVariablesXRCB; builder.SetRenderFunc( (PushGlobalCameraParamPassData data, RenderGraphContext context) => { - data.hdCamera.UpdateShaderVariableGlobalCB(ref data.globalCB, data.frameCount); - data.hdCamera.SetupGlobalParams(context.cmd, data.frameCount); + data.hdCamera.UpdateShaderVariablesGlobalCB(ref data.globalCB, data.frameCount); ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); + data.hdCamera.UpdateShaderVariablesXRCB(ref data.xrCB); + ConstantBuffer.PushGlobal(context.cmd, data.xrCB, HDShaderIDs._ShaderVariablesXR); }); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 804f0038ba7..384376a5868 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -168,6 +168,7 @@ internal static Volume GetOrCreateDefaultVolume() // Constant Buffers ShaderVariablesGlobal m_ShaderVariablesGlobalCB = new ShaderVariablesGlobal(); + ShaderVariablesXR m_ShaderVariablesXRCB = new ShaderVariablesXR(); // The current MSAA count MSAASamples m_MSAASamples; @@ -952,7 +953,7 @@ void Resize(HDCamera hdCamera) void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) { - hdCamera.UpdateShaderVariableGlobalCB(ref m_ShaderVariablesGlobalCB, m_FrameCount); + hdCamera.UpdateShaderVariablesGlobalCB(ref m_ShaderVariablesGlobalCB, m_FrameCount); Fog.UpdateShaderVariablesGlobalCB(ref m_ShaderVariablesGlobalCB, hdCamera); UpdateShaderVariablesGlobalSubsurface(ref m_ShaderVariablesGlobalCB, hdCamera); UpdateShaderVariablesGlobalDecal(ref m_ShaderVariablesGlobalCB, hdCamera); @@ -997,6 +998,9 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) } ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); + + hdCamera.UpdateShaderVariablesXRCB(ref m_ShaderVariablesXRCB); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesXRCB, HDShaderIDs._ShaderVariablesXR); } void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd) @@ -1005,9 +1009,6 @@ void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd) { PushVolumetricLightingGlobalParams(hdCamera, cmd, m_FrameCount); - // Set up UnityPerView CBuffer. - hdCamera.SetupGlobalParams(cmd, m_FrameCount); - // It will be overridden for transparent pass. cmd.SetGlobalInt(HDShaderIDs._ColorMaskTransparentVel, (int)UnityEngine.Rendering.ColorWriteMask.All); @@ -2136,7 +2137,7 @@ void AsyncSSAODispatch(CommandBuffer c, HDGPUAsyncTaskParams a) // This call overwrites camera properties passed to the shader system. RenderShadowMaps(renderContext, cmd, m_ShaderVariablesGlobalCB, cullingResults, hdCamera); - hdCamera.UpdateShaderVariableGlobalCB(ref m_ShaderVariablesGlobalCB, m_FrameCount); + hdCamera.UpdateShaderVariablesGlobalCB(ref m_ShaderVariablesGlobalCB, m_FrameCount); ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); } @@ -4513,7 +4514,7 @@ static void RenderAfterPostProcess( PostProcessParameters parameters, // The issue is that the only available depth buffer is jittered so pixels would wobble around depth tested edges. // In order to avoid that we decide that objects rendered after Post processes while TAA is active will not benefit from the depth buffer so we disable it. parameters.hdCamera.UpdateAllViewConstants(false); - parameters.hdCamera.UpdateShaderVariableGlobalCB(ref parameters.globalCB, parameters.frameCount); + parameters.hdCamera.UpdateShaderVariablesGlobalCB(ref parameters.globalCB, parameters.frameCount); UpdateOffscreenRenderingConstants(ref parameters.globalCB, true, 1); ConstantBuffer.PushGlobal(cmd, parameters.globalCB, HDShaderIDs._ShaderVariablesGlobal); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index ad6143d7a3d..4db9833f9ac 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -222,22 +222,6 @@ static class HDShaderIDs public static readonly int _WorldSpaceCameraPos1 = Shader.PropertyToID("_WorldSpaceCameraPos1"); public static readonly int _ViewMatrix1 = Shader.PropertyToID("_ViewMatrix1"); - // XR View Constants - public static readonly int _XRViewMatrix = Shader.PropertyToID("_XRViewMatrix"); - public static readonly int _XRInvViewMatrix = Shader.PropertyToID("_XRInvViewMatrix"); - public static readonly int _XRProjMatrix = Shader.PropertyToID("_XRProjMatrix"); - public static readonly int _XRInvProjMatrix = Shader.PropertyToID("_XRInvProjMatrix"); - public static readonly int _XRViewProjMatrix = Shader.PropertyToID("_XRViewProjMatrix"); - public static readonly int _XRInvViewProjMatrix = Shader.PropertyToID("_XRInvViewProjMatrix"); - public static readonly int _XRNonJitteredViewProjMatrix = Shader.PropertyToID("_XRNonJitteredViewProjMatrix"); - public static readonly int _XRPrevViewProjMatrix = Shader.PropertyToID("_XRPrevViewProjMatrix"); - public static readonly int _XRPrevInvViewProjMatrix = Shader.PropertyToID("_XRPrevInvViewProjMatrix"); - public static readonly int _XRPrevViewProjMatrixNoCameraTrans = Shader.PropertyToID("_XRPrevViewProjMatrixNoCameraTrans"); - public static readonly int _XRPixelCoordToViewDirWS = Shader.PropertyToID("_XRPixelCoordToViewDirWS"); - public static readonly int _XRWorldSpaceCameraPos = Shader.PropertyToID("_XRWorldSpaceCameraPos"); - public static readonly int _XRWorldSpaceCameraPosViewOffset = Shader.PropertyToID("_XRWorldSpaceCameraPosViewOffset"); - public static readonly int _XRPrevWorldSpaceCameraPos = Shader.PropertyToID("_XRPrevWorldSpaceCameraPos"); - public static readonly int _ColorTexture = Shader.PropertyToID("_ColorTexture"); public static readonly int _DepthTexture = Shader.PropertyToID("_DepthTexture"); public static readonly int _DepthValuesTexture = Shader.PropertyToID("_DepthValuesTexture"); @@ -287,6 +271,7 @@ static class HDShaderIDs }; public static readonly int _ShaderVariablesGlobal = Shader.PropertyToID("ShaderVariablesGlobal"); + public static readonly int _ShaderVariablesXR = Shader.PropertyToID("_ShaderVariablesXR"); public static readonly int _ShaderVariablesVolumetric = Shader.PropertyToID("ShaderVariablesVolumetric"); public static readonly int _ShaderVariablesLightList = Shader.PropertyToID("ShaderVariablesLightList"); @@ -500,7 +485,7 @@ static class HDShaderIDs public static readonly int _VelocityBuffer = Shader.PropertyToID("_VelocityBuffer"); public static readonly int _ShadowFilterMapping = Shader.PropertyToID("_ShadowFilterMapping"); public static readonly int _DistanceTexture = Shader.PropertyToID("_DistanceTexture"); - + // Reflections public static readonly int _ReflectionHistorybufferRW = Shader.PropertyToID("_ReflectionHistorybufferRW"); public static readonly int _CurrentFrameTexture = Shader.PropertyToID("_CurrentFrameTexture"); @@ -525,7 +510,7 @@ static class HDShaderIDs public static readonly int _RaytracedAreaShadowIntegration = Shader.PropertyToID("_RaytracedAreaShadowIntegration"); public static readonly int _RaytracingDirectionBuffer = Shader.PropertyToID("_RaytracingDirectionBuffer"); public static readonly int _RaytracingDistanceBuffer = Shader.PropertyToID("_RaytracingDistanceBuffer"); - public static readonly int _RaytracingDistanceBufferRW = Shader.PropertyToID("_RaytracingDistanceBufferRW"); + public static readonly int _RaytracingDistanceBufferRW = Shader.PropertyToID("_RaytracingDistanceBufferRW"); public static readonly int _AreaShadowTexture = Shader.PropertyToID("_AreaShadowTexture"); public static readonly int _AreaShadowTextureRW = Shader.PropertyToID("_AreaShadowTextureRW"); public static readonly int _ScreenSpaceShadowsTextureRW = Shader.PropertyToID("_ScreenSpaceShadowsTextureRW"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl index e9ea4efa5c1..181bd0bfc8c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl @@ -148,26 +148,7 @@ SAMPLER(samplerunity_ProbeVolumeSH); TEXTURE2D(_ExposureTexture); TEXTURE2D(_PrevExposureTexture); -// Custom generated by HDRP, not from Unity Engine (passed in via HDCamera) -#if defined(USING_STEREO_MATRICES) -CBUFFER_START(UnityXRViewConstants) - float4x4 _XRViewMatrix[SHADEROPTIONS_XR_MAX_VIEWS]; - float4x4 _XRInvViewMatrix[SHADEROPTIONS_XR_MAX_VIEWS]; - float4x4 _XRProjMatrix[SHADEROPTIONS_XR_MAX_VIEWS]; - float4x4 _XRInvProjMatrix[SHADEROPTIONS_XR_MAX_VIEWS]; - float4x4 _XRViewProjMatrix[SHADEROPTIONS_XR_MAX_VIEWS]; - float4x4 _XRInvViewProjMatrix[SHADEROPTIONS_XR_MAX_VIEWS]; - float4x4 _XRNonJitteredViewProjMatrix[SHADEROPTIONS_XR_MAX_VIEWS]; - float4x4 _XRPrevViewProjMatrix[SHADEROPTIONS_XR_MAX_VIEWS]; - float4x4 _XRPrevInvViewProjMatrix[SHADEROPTIONS_XR_MAX_VIEWS]; - float4x4 _XRPrevViewProjMatrixNoCameraTrans[SHADEROPTIONS_XR_MAX_VIEWS]; - float4x4 _XRPixelCoordToViewDirWS[SHADEROPTIONS_XR_MAX_VIEWS]; - - float4 _XRWorldSpaceCameraPos[SHADEROPTIONS_XR_MAX_VIEWS]; - float4 _XRWorldSpaceCameraPosViewOffset[SHADEROPTIONS_XR_MAX_VIEWS]; - float4 _XRPrevWorldSpaceCameraPos[SHADEROPTIONS_XR_MAX_VIEWS]; -CBUFFER_END -#endif +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl" // Note: To sample camera depth in HDRP we provide these utils functions because the way we store the depth mips can change // Currently it's an atlas and it's layout can be found at ComputePackedMipChainInfo in HDUtils.cs diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs new file mode 100644 index 00000000000..c3cbe289eb2 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs @@ -0,0 +1,38 @@ +namespace UnityEngine.Rendering.HighDefinition +{ + // Custom generated by HDRP, not from Unity Engine (passed in via HDCamera) + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + unsafe struct ShaderVariablesXR + { + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float _XRViewMatrix[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float _XRInvViewMatrix[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float _XRProjMatrix[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float _XRInvProjMatrix[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float _XRViewProjMatrix[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float _XRInvViewProjMatrix[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float _XRNonJitteredViewProjMatrix[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float _XRPrevViewProjMatrix[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float _XRPrevInvViewProjMatrix[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float _XRPrevViewProjMatrixNoCameraTrans[(int)ShaderOptions.XrMaxViews * 16]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] + public fixed float _XRPixelCoordToViewDirWS[(int)ShaderOptions.XrMaxViews * 16]; + + + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Vector4))] + public fixed float _XRWorldSpaceCameraPos[(int)ShaderOptions.XrMaxViews * 4]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Vector4))] + public fixed float _XRWorldSpaceCameraPosViewOffset[(int)ShaderOptions.XrMaxViews * 4]; + [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Vector4))] + public fixed float _XRPrevWorldSpaceCameraPos[(int)ShaderOptions.XrMaxViews * 4]; + } +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl new file mode 100644 index 00000000000..90370efba08 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl @@ -0,0 +1,27 @@ +// +// This file was automatically generated. Please don't edit by hand. +// + +#ifndef SHADERVARIABLESXR_CS_HLSL +#define SHADERVARIABLESXR_CS_HLSL +// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesXR +// PackingRules = Exact +CBUFFER_START(ShaderVariablesXR) + float4x4 _XRViewMatrix[2]; + float4x4 _XRInvViewMatrix[2]; + float4x4 _XRProjMatrix[2]; + float4x4 _XRInvProjMatrix[2]; + float4x4 _XRViewProjMatrix[2]; + float4x4 _XRInvViewProjMatrix[2]; + float4x4 _XRNonJitteredViewProjMatrix[2]; + float4x4 _XRPrevViewProjMatrix[2]; + float4x4 _XRPrevInvViewProjMatrix[2]; + float4x4 _XRPrevViewProjMatrixNoCameraTrans[2]; + float4x4 _XRPixelCoordToViewDirWS[2]; + float4 _XRWorldSpaceCameraPos[2]; + float4 _XRWorldSpaceCameraPosViewOffset[2]; + float4 _XRPrevWorldSpaceCameraPos[2]; +CBUFFER_END + + +#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl.meta new file mode 100644 index 00000000000..de81b2e0487 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: a70588104cdb44843bb61b8ad227c442 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.meta b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.meta new file mode 100644 index 00000000000..b096f1df99e --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 23ea53b0cd1fd7b4ab43203831612198 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 165ebbad3130fe9b30f0690b8a4830b722c094bf Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 20 Mar 2020 16:53:41 +0100 Subject: [PATCH 47/92] Removed useless global constant --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 3 --- .../Runtime/RenderPipeline/HDStringConstants.cs | 2 -- 2 files changed, 5 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 0537eb581c9..6d35b16f6c6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3293,9 +3293,6 @@ static void PushLightLoopGlobalParams(in LightLoopGlobalParameters param, Comman { Camera camera = param.hdCamera.camera; - cmd.SetGlobalInt(HDShaderIDs._NumTileBigTileX, GetNumTileBigTileX(param.hdCamera)); - cmd.SetGlobalInt(HDShaderIDs._NumTileBigTileY, GetNumTileBigTileY(param.hdCamera)); - if (param.hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass)) cmd.SetGlobalBuffer(HDShaderIDs.g_vBigTileLightList, param.tileAndClusterData.bigTileLightList); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 4db9833f9ac..ed856c554ee 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -125,8 +125,6 @@ static class HDShaderIDs public static readonly int _DirectionalLightDatas = Shader.PropertyToID("_DirectionalLightDatas"); public static readonly int _LightDatas = Shader.PropertyToID("_LightDatas"); public static readonly int _EnvLightDatas = Shader.PropertyToID("_EnvLightDatas"); - public static readonly int _NumTileBigTileX = Shader.PropertyToID("_NumTileBigTileX"); - public static readonly int _NumTileBigTileY = Shader.PropertyToID("_NumTileBigTileY"); public static readonly int g_vLayeredOffsetsBuffer = Shader.PropertyToID("g_vLayeredOffsetsBuffer"); From c228d3f52a33cf604399d2fa4f9a503c7492c96d Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 20 Mar 2020 18:03:32 +0100 Subject: [PATCH 48/92] Fixed XR global constant name --- .../Runtime/RenderPipeline/HDStringConstants.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index ed856c554ee..927e1b56fd0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -269,7 +269,7 @@ static class HDShaderIDs }; public static readonly int _ShaderVariablesGlobal = Shader.PropertyToID("ShaderVariablesGlobal"); - public static readonly int _ShaderVariablesXR = Shader.PropertyToID("_ShaderVariablesXR"); + public static readonly int _ShaderVariablesXR = Shader.PropertyToID("ShaderVariablesXR"); public static readonly int _ShaderVariablesVolumetric = Shader.PropertyToID("ShaderVariablesVolumetric"); public static readonly int _ShaderVariablesLightList = Shader.PropertyToID("ShaderVariablesLightList"); From 3d4d4a54a406789a0505d181534a9eeb4a4bd4b2 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Mon, 23 Mar 2020 11:03:39 +0100 Subject: [PATCH 49/92] Converted SSR to constant buffer. --- .../ScreenSpaceReflections.compute | 19 +---- .../ShaderVariablesScreenSpaceReflection.cs | 22 ++++++ ...aderVariablesScreenSpaceReflection.cs.hlsl | 25 ++++++ ...ariablesScreenSpaceReflection.cs.hlsl.meta | 9 +++ ...aderVariablesScreenSpaceReflection.cs.meta | 11 +++ .../HDRenderPipeline.LightLoop.cs | 4 +- .../RenderPipeline/HDRenderPipeline.cs | 76 +++++++------------ .../RenderPipeline/HDStringConstants.cs | 15 +--- 8 files changed, 100 insertions(+), 81 deletions(-) create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl.meta create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.meta diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceReflections.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceReflections.compute index b5e1b7f4d39..e9364f327b7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceReflections.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceReflections.compute @@ -22,6 +22,7 @@ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceLighting.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Builtin/BuiltinData.hlsl" @@ -52,24 +53,6 @@ StructuredBuffer _DepthPyramidMipLevelOffsets; StructuredBuffer _CoarseStencilBuffer; -CBUFFER_START(UnityScreenSpaceReflections) - int _SsrStencilBit; - int _SsrIterLimit; - float _SsrThicknessScale; - float _SsrThicknessBias; - - float _SsrRoughnessFadeEnd; - float _SsrRoughnessFadeRcpLength; - float _SsrRoughnessFadeEndTimesRcpLength; - float _SsrEdgeFadeRcpLength; - - float4 _ColorPyramidUvScaleAndLimitPrevFrame; - - int _SsrDepthPyramidMaxMip; - int _SsrColorPyramidMaxMip; - int _SsrReflectsSky; // bool... -CBUFFER_END - //-------------------------------------------------------------------------------------------------- // Implementation //-------------------------------------------------------------------------------------------------- diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs new file mode 100644 index 00000000000..14519878cd4 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs @@ -0,0 +1,22 @@ +namespace UnityEngine.Rendering.HighDefinition +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + unsafe struct ShaderVariablesScreenSpaceReflection + { + public float _SsrThicknessScale; + public float _SsrThicknessBias; + public int _SsrStencilBit; + public int _SsrIterLimit; + + public float _SsrRoughnessFadeEnd; + public float _SsrRoughnessFadeRcpLength; + public float _SsrRoughnessFadeEndTimesRcpLength; + public float _SsrEdgeFadeRcpLength; + + public Vector4 _ColorPyramidUvScaleAndLimitPrevFrame; + + public int _SsrDepthPyramidMaxMip; + public int _SsrColorPyramidMaxMip; + public int _SsrReflectsSky; + } +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl new file mode 100644 index 00000000000..11b4e9287f0 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl @@ -0,0 +1,25 @@ +// +// This file was automatically generated. Please don't edit by hand. +// + +#ifndef SHADERVARIABLESSCREENSPACEREFLECTION_CS_HLSL +#define SHADERVARIABLESSCREENSPACEREFLECTION_CS_HLSL +// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesScreenSpaceReflection +// PackingRules = Exact +CBUFFER_START(ShaderVariablesScreenSpaceReflection) + float _SsrThicknessScale; + float _SsrThicknessBias; + int _SsrStencilBit; + int _SsrIterLimit; + float _SsrRoughnessFadeEnd; + float _SsrRoughnessFadeRcpLength; + float _SsrRoughnessFadeEndTimesRcpLength; + float _SsrEdgeFadeRcpLength; + float4 _ColorPyramidUvScaleAndLimitPrevFrame; + int _SsrDepthPyramidMaxMip; + int _SsrColorPyramidMaxMip; + int _SsrReflectsSky; +CBUFFER_END + + +#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl.meta new file mode 100644 index 00000000000..c5049568c97 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: b9e1731972b49b84cb07e584e3cf0867 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.meta new file mode 100644 index 00000000000..ca8ef5f8173 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 61649e120aa78c04e8b44d1c5af17d35 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 16ab26b3381..0481313705a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -257,7 +257,7 @@ class RenderSSRPassData } TextureHandle RenderSSR( RenderGraph renderGraph, - HDCamera hdCamera, + HDCamera hdCamera, TextureHandle normalBuffer, TextureHandle motionVectorsBuffer, TextureHandle depthPyramid, @@ -288,7 +288,7 @@ TextureHandle RenderSSR( RenderGraph renderGraph, var colorPyramid = renderGraph.ImportTexture(hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.ColorBufferMipChain)); - passData.parameters = PrepareSSRParameters(hdCamera); + passData.parameters = PrepareSSRParameters(hdCamera, m_DepthBufferMipChainInfo); passData.depthPyramid = builder.ReadTexture(depthPyramid); passData.colorPyramid = builder.ReadTexture(colorPyramid); passData.stencilBuffer = builder.ReadTexture(stencilBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 384376a5868..3729b71f7c3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -3722,24 +3722,15 @@ struct RenderSSRParameters public int reprojectionKernel; public int width, height, viewCount; - public int maxIteration; - public bool reflectSky; - public float thicknessScale; - public float thicknessBias; - public float roughnessFadeEnd; - public float roughnessFadeEndTimesRcpLength; - public float roughnessFadeRcpLength; - public float edgeFadeRcpLength; public int depthPyramidMipCount; public ComputeBuffer offsetBufferData; public ComputeBuffer coarseStencilBuffer; - public Vector4 colorPyramidUVScaleAndLimit; - public int colorPyramidMipCount; - } + public ShaderVariablesScreenSpaceReflection cb; + } - RenderSSRParameters PrepareSSRParameters(HDCamera hdCamera) + RenderSSRParameters PrepareSSRParameters(HDCamera hdCamera, in HDUtils.PackedMipChainInfo depthPyramid) { var volumeSettings = hdCamera.volumeStack.GetComponent(); var parameters = new RenderSSRParameters(); @@ -3754,28 +3745,26 @@ RenderSSRParameters PrepareSSRParameters(HDCamera hdCamera) float n = hdCamera.camera.nearClipPlane; float f = hdCamera.camera.farClipPlane; - - parameters.maxIteration = volumeSettings.rayMaxIterations; - parameters.reflectSky = volumeSettings.reflectSky.value; - - float thickness = volumeSettings.depthBufferThickness.value; - parameters.thicknessScale = 1.0f / (1.0f + thickness); - parameters.thicknessBias = -n / (f - n) * (thickness * parameters.thicknessScale); - - var info = m_SharedRTManager.GetDepthBufferMipChainInfo(); - parameters.depthPyramidMipCount = info.mipLevelCount; - parameters.offsetBufferData = info.GetOffsetBufferData(m_DepthPyramidMipLevelOffsetsBuffer); - parameters.coarseStencilBuffer = m_SharedRTManager.GetCoarseStencilBuffer(); - + float thickness = volumeSettings.depthBufferThickness.value; + + ref var cb = ref parameters.cb; + cb._SsrThicknessScale = 1.0f / (1.0f + thickness); + cb._SsrThicknessBias = -n / (f - n) * (thickness * cb._SsrThicknessScale); + cb._SsrIterLimit = volumeSettings.rayMaxIterations; + cb._SsrReflectsSky = volumeSettings.reflectSky.value ? 1 : 0; + cb._SsrStencilBit = (int)StencilUsage.TraceReflectionRay; float roughnessFadeStart = 1 - volumeSettings.smoothnessFadeStart.value; - parameters.roughnessFadeEnd = 1 - volumeSettings.minSmoothness.value; - float roughnessFadeLength = parameters.roughnessFadeEnd - roughnessFadeStart; - parameters.roughnessFadeEndTimesRcpLength = (roughnessFadeLength != 0) ? (parameters.roughnessFadeEnd * (1.0f / roughnessFadeLength)) : 1; - parameters.roughnessFadeRcpLength = (roughnessFadeLength != 0) ? (1.0f / roughnessFadeLength) : 0; - parameters.edgeFadeRcpLength = Mathf.Min(1.0f / volumeSettings.screenFadeDistance.value, float.MaxValue); - - parameters.colorPyramidUVScaleAndLimit = HDUtils.ComputeUvScaleAndLimit(hdCamera.historyRTHandleProperties.previousViewportSize, hdCamera.historyRTHandleProperties.previousRenderTargetSize); - parameters.colorPyramidMipCount = hdCamera.colorPyramidHistoryMipCount; + cb._SsrRoughnessFadeEnd = 1 - volumeSettings.minSmoothness.value; + float roughnessFadeLength = cb._SsrRoughnessFadeEnd - roughnessFadeStart; + cb._SsrRoughnessFadeEndTimesRcpLength = (roughnessFadeLength != 0) ? (cb._SsrRoughnessFadeEnd * (1.0f / roughnessFadeLength)) : 1; + cb._SsrRoughnessFadeRcpLength = (roughnessFadeLength != 0) ? (1.0f / roughnessFadeLength) : 0; + cb._SsrEdgeFadeRcpLength = Mathf.Min(1.0f / volumeSettings.screenFadeDistance.value, float.MaxValue); + cb._ColorPyramidUvScaleAndLimitPrevFrame = HDUtils.ComputeUvScaleAndLimit(hdCamera.historyRTHandleProperties.previousViewportSize, hdCamera.historyRTHandleProperties.previousRenderTargetSize); + cb._SsrColorPyramidMaxMip = hdCamera.colorPyramidHistoryMipCount - 1; + cb._SsrDepthPyramidMaxMip = depthPyramid.mipLevelCount - 1; + + parameters.offsetBufferData = depthPyramid.GetOffsetBufferData(m_DepthPyramidMipLevelOffsetsBuffer); + parameters.coarseStencilBuffer = m_SharedRTManager.GetCoarseStencilBuffer(); return parameters; } @@ -3794,17 +3783,6 @@ static void RenderSSR( in RenderSSRParameters parameters, using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.SsrTracing))) { - cmd.SetComputeIntParam(cs, HDShaderIDs._SsrIterLimit, parameters.maxIteration); - cmd.SetComputeFloatParam(cs, HDShaderIDs._SsrThicknessScale, parameters.thicknessScale); - cmd.SetComputeFloatParam(cs, HDShaderIDs._SsrThicknessBias, parameters.thicknessBias); - cmd.SetComputeFloatParam(cs, HDShaderIDs._SsrRoughnessFadeEnd, parameters.roughnessFadeEnd); - cmd.SetComputeFloatParam(cs, HDShaderIDs._SsrRoughnessFadeRcpLength, parameters.roughnessFadeRcpLength); - cmd.SetComputeFloatParam(cs, HDShaderIDs._SsrRoughnessFadeEndTimesRcpLength, parameters.roughnessFadeEndTimesRcpLength); - cmd.SetComputeIntParam(cs, HDShaderIDs._SsrDepthPyramidMaxMip, parameters.depthPyramidMipCount - 1); - cmd.SetComputeFloatParam(cs, HDShaderIDs._SsrEdgeFadeRcpLength, parameters.edgeFadeRcpLength); - cmd.SetComputeIntParam(cs, HDShaderIDs._SsrReflectsSky, parameters.reflectSky ? 1 : 0); - cmd.SetComputeIntParam(cs, HDShaderIDs._SsrStencilBit, (int)StencilUsage.TraceReflectionRay); - // cmd.SetComputeTextureParam(cs, kernel, "_SsrDebugTexture", m_SsrDebugTexture); cmd.SetComputeTextureParam(cs, parameters.tracingKernel, HDShaderIDs._CameraDepthTexture, depthPyramid); cmd.SetComputeTextureParam(cs, parameters.tracingKernel, HDShaderIDs._SsrClearCoatMaskTexture, clearCoatMask); @@ -3820,9 +3798,10 @@ static void RenderSSR( in RenderSSRParameters parameters, } cmd.SetComputeBufferParam(cs, parameters.tracingKernel, HDShaderIDs._CoarseStencilBuffer, parameters.coarseStencilBuffer); - cmd.SetComputeBufferParam(cs, parameters.tracingKernel, HDShaderIDs._DepthPyramidMipLevelOffsets, parameters.offsetBufferData); + ConstantBuffer.Push(cmd, parameters.cb, cs, HDShaderIDs._ShaderVariablesScreenSpaceReflection); + cmd.DispatchCompute(cs, parameters.tracingKernel, HDUtils.DivRoundUp(parameters.width, 8), HDUtils.DivRoundUp(parameters.height, 8), parameters.viewCount); } @@ -3834,8 +3813,7 @@ static void RenderSSR( in RenderSSRParameters parameters, cmd.SetComputeTextureParam(cs, parameters.reprojectionKernel, HDShaderIDs._ColorPyramidTexture, previousColorPyramid); cmd.SetComputeTextureParam(cs, parameters.reprojectionKernel, HDShaderIDs._SsrClearCoatMaskTexture, clearCoatMask); - cmd.SetComputeVectorParam(cs, HDShaderIDs._ColorPyramidUvScaleAndLimitPrevFrame, parameters.colorPyramidUVScaleAndLimit); - cmd.SetComputeIntParam(cs, HDShaderIDs._SsrColorPyramidMaxMip, parameters.colorPyramidMipCount - 1); + ConstantBuffer.Push(cmd, parameters.cb, cs, HDShaderIDs._ShaderVariablesScreenSpaceReflection); cmd.DispatchCompute(cs, parameters.reprojectionKernel, HDUtils.DivRoundUp(parameters.width, 8), HDUtils.DivRoundUp(parameters.height, 8), parameters.viewCount); } @@ -3859,7 +3837,7 @@ void RenderSSR(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext ren // Evaluate the clear coat mask texture based on the lit shader mode RTHandle clearCoatMask = hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred ? m_GbufferManager.GetBuffer(2) : TextureXR.GetBlackTexture(); - var parameters = PrepareSSRParameters(hdCamera); + var parameters = PrepareSSRParameters(hdCamera, m_SharedRTManager.GetDepthBufferMipChainInfo()); RenderSSR(parameters, m_SharedRTManager.GetDepthTexture(), m_SsrHitPointTexture, m_SharedRTManager.GetStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), clearCoatMask, previousColorPyramid, m_SsrLightingTexture, cmd, renderContext); @@ -3896,7 +3874,7 @@ void RenderSSRTransparent(HDCamera hdCamera, CommandBuffer cmd, ScriptableRender // Evaluate the screen space reflection for the transparent pixels var previousColorPyramid = hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.ColorBufferMipChain); - var parameters = PrepareSSRParameters(hdCamera); + var parameters = PrepareSSRParameters(hdCamera, m_SharedRTManager.GetDepthBufferMipChainInfo()); RenderSSR(parameters, m_SharedRTManager.GetDepthTexture(), m_SsrHitPointTexture, m_SharedRTManager.GetStencilBuffer(), TextureXR.GetBlackTexture(), previousColorPyramid, m_SsrLightingTexture, cmd, renderContext); // If color pyramid was not valid, we bind a black texture diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 927e1b56fd0..220f3de8923 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -276,24 +276,15 @@ static class HDShaderIDs public static readonly int _SSSBufferTexture = Shader.PropertyToID("_SSSBufferTexture"); public static readonly int _NormalBufferTexture = Shader.PropertyToID("_NormalBufferTexture"); - public static readonly int _SsrIterLimit = Shader.PropertyToID("_SsrIterLimit"); - public static readonly int _SsrThicknessScale = Shader.PropertyToID("_SsrThicknessScale"); - public static readonly int _SsrThicknessBias = Shader.PropertyToID("_SsrThicknessBias"); - public static readonly int _SsrRoughnessFadeEnd = Shader.PropertyToID("_SsrRoughnessFadeEnd"); - public static readonly int _SsrRoughnessFadeRcpLength = Shader.PropertyToID("_SsrRoughnessFadeRcpLength"); - public static readonly int _SsrRoughnessFadeEndTimesRcpLength = Shader.PropertyToID("_SsrRoughnessFadeEndTimesRcpLength"); - public static readonly int _SsrDepthPyramidMaxMip = Shader.PropertyToID("_SsrDepthPyramidMaxMip"); - public static readonly int _SsrColorPyramidMaxMip = Shader.PropertyToID("_SsrColorPyramidMaxMip"); - public static readonly int _SsrEdgeFadeRcpLength = Shader.PropertyToID("_SsrEdgeFadeRcpLength"); + public static readonly int _ShaderVariablesScreenSpaceReflection = Shader.PropertyToID("ShaderVariablesScreenSpaceReflection"); public static readonly int _SsrLightingTexture = Shader.PropertyToID("_SsrLightingTexture"); public static readonly int _SsrLightingTextureRW = Shader.PropertyToID("_SsrLightingTextureRW"); public static readonly int _SsrHitPointTexture = Shader.PropertyToID("_SsrHitPointTexture"); public static readonly int _SsrClearCoatMaskTexture = Shader.PropertyToID("_SsrClearCoatMaskTexture"); - public static readonly int _SsrStencilBit = Shader.PropertyToID("_SsrStencilBit"); - public static readonly int _SsrReflectsSky = Shader.PropertyToID("_SsrReflectsSky"); - public static readonly int _DepthPyramidMipLevelOffsets = Shader.PropertyToID("_DepthPyramidMipLevelOffsets"); + // Still used by ray tracing. + public static readonly int _SsrStencilBit = Shader.PropertyToID("_SsrStencilBit"); public static readonly int _ShadowMaskTexture = Shader.PropertyToID("_ShadowMaskTexture"); public static readonly int _LightLayersTexture = Shader.PropertyToID("_LightLayersTexture"); From b9b08a6982200b9a2005e2980c8fd153b03afc83 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Mon, 23 Mar 2020 11:42:45 +0100 Subject: [PATCH 50/92] Converted AO to constant buffers. --- .../ScreenSpaceLighting/AmbientOcclusion.cs | 67 ++++++------------- .../ScreenSpaceLighting/GTAOCommon.hlsl | 12 +--- .../ShaderVariablesAmbientOcclusion.cs | 15 +++++ .../ShaderVariablesAmbientOcclusion.cs.hlsl | 21 ++++++ ...aderVariablesAmbientOcclusion.cs.hlsl.meta | 9 +++ .../ShaderVariablesAmbientOcclusion.cs.meta | 11 +++ .../RenderPipeline/HDStringConstants.cs | 9 +-- 7 files changed, 80 insertions(+), 64 deletions(-) create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.hlsl create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.hlsl.meta create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.meta diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs index 395f322a4d2..40adf06b2ea 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs @@ -275,14 +275,6 @@ struct RenderAOParameters public int upsampleAndBlurKernel; public int upsampleAOKernel; - public Vector4 aoParams0; - public Vector4 aoParams1; - public Vector4 aoParams2; - public Vector4 aoParams3; - public Vector4 aoParams4; - public Vector4 firstAndSecondMipOffsets; - public Vector4 aoBufferInfo; - public Vector4 toViewSpaceProj; public Vector2 runningRes; public int viewCount; public bool historyReady; @@ -290,16 +282,18 @@ struct RenderAOParameters public int outputHeight; public bool fullResolution; public bool runAsync; - public bool motionVectorDisabled; public bool temporalAccumulation; public bool bilateralUpsample; + public ShaderVariablesAmbientOcclusion cb; } RenderAOParameters PrepareRenderAOParameters(HDCamera camera, RTHandleProperties rtHandleProperties, Vector2 historySize, int frameCount) { var parameters = new RenderAOParameters(); + ref var cb = ref parameters.cb; + // Grab current settings var settings = camera.volumeStack.GetComponent(); parameters.fullResolution = settings.fullResolution; @@ -307,25 +301,25 @@ RenderAOParameters PrepareRenderAOParameters(HDCamera camera, RTHandleProperties if (parameters.fullResolution) { parameters.runningRes = new Vector2(camera.actualWidth, camera.actualHeight); - parameters.aoBufferInfo = new Vector4(camera.actualWidth, camera.actualHeight, 1.0f / camera.actualWidth, 1.0f / camera.actualHeight); + cb._AOBufferSize = new Vector4(camera.actualWidth, camera.actualHeight, 1.0f / camera.actualWidth, 1.0f / camera.actualHeight); } else { parameters.runningRes = new Vector2(camera.actualWidth, camera.actualHeight) * 0.5f; - parameters.aoBufferInfo = new Vector4(camera.actualWidth * 0.5f, camera.actualHeight * 0.5f, 2.0f / camera.actualWidth, 2.0f / camera.actualHeight); + cb._AOBufferSize = new Vector4(camera.actualWidth * 0.5f, camera.actualHeight * 0.5f, 2.0f / camera.actualWidth, 2.0f / camera.actualHeight); } float invHalfTanFOV = -camera.mainViewConstants.projMatrix[1, 1]; float aspectRatio = parameters.runningRes.y / parameters.runningRes.x; - parameters.aoParams0 = new Vector4( + cb._AOParams0 = new Vector4( parameters.fullResolution ? 0.0f : 1.0f, parameters.runningRes.y * invHalfTanFOV * 0.25f, settings.radius.value, settings.stepCount ); - parameters.aoParams1 = new Vector4( + cb._AOParams1 = new Vector4( settings.intensity.value, 1.0f / (settings.radius.value * settings.radius.value), (frameCount / 6) % 4, @@ -334,7 +328,7 @@ RenderAOParameters PrepareRenderAOParameters(HDCamera camera, RTHandleProperties // We start from screen space position, so we bake in this factor the 1 / resolution as well. - parameters.toViewSpaceProj = new Vector4( + cb._AODepthToViewParams = new Vector4( 2.0f / (invHalfTanFOV * aspectRatio * parameters.runningRes.x), 2.0f / (invHalfTanFOV * parameters.runningRes.y), 1.0f / (invHalfTanFOV * aspectRatio), @@ -344,9 +338,7 @@ RenderAOParameters PrepareRenderAOParameters(HDCamera camera, RTHandleProperties float scaleFactor = (parameters.runningRes.x * parameters.runningRes.y) / (540.0f * 960.0f); float radInPixels = Mathf.Max(16, settings.maximumRadiusInPixels * Mathf.Sqrt(scaleFactor)); - - - parameters.aoParams2 = new Vector4( + cb._AOParams2 = new Vector4( historySize.x, historySize.y, 1.0f / (settings.stepCount + 1.0f), @@ -366,7 +358,7 @@ RenderAOParameters PrepareRenderAOParameters(HDCamera camera, RTHandleProperties float uTolerance = Mathf.Pow(10f, upsampleTolerance); float noiseFilterWeight = 1f / (Mathf.Pow(10f, 0.0f) + uTolerance); - parameters.aoParams3 = new Vector4( + cb._AOParams3 = new Vector4( bTolerance, uTolerance, noiseFilterWeight, @@ -377,7 +369,7 @@ RenderAOParameters PrepareRenderAOParameters(HDCamera camera, RTHandleProperties const float maxUpperNudgeLimit = 5.0f; const float minUpperNudgeLimit = 0.25f; upperNudgeFactor = minUpperNudgeLimit + (upperNudgeFactor * (maxUpperNudgeLimit - minUpperNudgeLimit)); - parameters.aoParams4 = new Vector4( + cb._AOParams4 = new Vector4( settings.directionCount, upperNudgeFactor, minUpperNudgeLimit, @@ -386,7 +378,7 @@ RenderAOParameters PrepareRenderAOParameters(HDCamera camera, RTHandleProperties var hdrp = (RenderPipelineManager.currentPipeline as HDRenderPipeline); var depthMipInfo = hdrp.sharedRTManager.GetDepthBufferMipChainInfo(); - parameters.firstAndSecondMipOffsets = new Vector4(depthMipInfo.mipLevelOffsets[1].x, depthMipInfo.mipLevelOffsets[1].y, depthMipInfo.mipLevelOffsets[2].x, depthMipInfo.mipLevelOffsets[2].y); + cb._FirstTwoDepthMipOffsets = new Vector4(depthMipInfo.mipLevelOffsets[1].x, depthMipInfo.mipLevelOffsets[1].y, depthMipInfo.mipLevelOffsets[2].x, depthMipInfo.mipLevelOffsets[2].y); parameters.bilateralUpsample = settings.bilateralUpsample; parameters.gtaoCS = m_Resources.shaders.GTAOCS; @@ -434,24 +426,16 @@ RenderAOParameters PrepareRenderAOParameters(HDCamera camera, RTHandleProperties m_HistoryReady = true; // assumes that if this is called, then render is done as well. parameters.runAsync = camera.frameSettings.SSAORunsAsync(); - parameters.motionVectorDisabled = !camera.frameSettings.IsEnabled(FrameSettingsField.MotionVectors); return parameters; } - static void RenderAO(in RenderAOParameters parameters, - RTHandle packedDataTexture, + static void RenderAO(in RenderAOParameters parameters, + RTHandle packedDataTexture, RenderPipelineResources resources, - CommandBuffer cmd) + CommandBuffer cmd) { - cmd.SetComputeVectorParam(parameters.gtaoCS, HDShaderIDs._AOBufferSize, parameters.aoBufferInfo); - cmd.SetComputeVectorParam(parameters.gtaoCS, HDShaderIDs._AODepthToViewParams, parameters.toViewSpaceProj); - cmd.SetComputeVectorParam(parameters.gtaoCS, HDShaderIDs._AOParams0, parameters.aoParams0); - cmd.SetComputeVectorParam(parameters.gtaoCS, HDShaderIDs._AOParams1, parameters.aoParams1); - cmd.SetComputeVectorParam(parameters.gtaoCS, HDShaderIDs._AOParams2, parameters.aoParams2); - cmd.SetComputeVectorParam(parameters.gtaoCS, HDShaderIDs._AOParams4, parameters.aoParams4); - cmd.SetComputeVectorParam(parameters.gtaoCS, HDShaderIDs._FirstTwoDepthMipOffsets, parameters.firstAndSecondMipOffsets); - + ConstantBuffer.Push(cmd, parameters.cb, parameters.gtaoCS, HDShaderIDs._ShaderVariablesAmbientOcclusion); cmd.SetComputeTextureParam(parameters.gtaoCS, parameters.gtaoKernel, HDShaderIDs._AOPackedData, packedDataTexture); const int groupSizeX = 8; @@ -477,25 +461,20 @@ static void DenoiseAO( in RenderAOParameters parameters, if (parameters.temporalAccumulation || parameters.fullResolution) { - var blurCS = parameters.denoiseAOCS; - cmd.SetComputeVectorParam(parameters.denoiseAOCS, HDShaderIDs._AOParams1, parameters.aoParams1); - cmd.SetComputeVectorParam(parameters.denoiseAOCS, HDShaderIDs._AOParams2, parameters.aoParams2); - cmd.SetComputeVectorParam(parameters.denoiseAOCS, HDShaderIDs._AOParams3, parameters.aoParams3); - cmd.SetComputeVectorParam(parameters.denoiseAOCS, HDShaderIDs._AOParams4, parameters.aoParams4); - cmd.SetComputeVectorParam(parameters.denoiseAOCS, HDShaderIDs._AOBufferSize, parameters.aoBufferInfo); + ConstantBuffer.Set(cmd, parameters.denoiseAOCS, HDShaderIDs._ShaderVariablesAmbientOcclusion); // Spatial - cmd.SetComputeTextureParam(blurCS, parameters.denoiseKernelSpatial, HDShaderIDs._AOPackedData, packedDataTex); + cmd.SetComputeTextureParam(parameters.denoiseAOCS, parameters.denoiseKernelSpatial, HDShaderIDs._AOPackedData, packedDataTex); if (parameters.temporalAccumulation) { - cmd.SetComputeTextureParam(blurCS, parameters.denoiseKernelSpatial, HDShaderIDs._AOPackedBlurred, packedDataBlurredTex); + cmd.SetComputeTextureParam(parameters.denoiseAOCS, parameters.denoiseKernelSpatial, HDShaderIDs._AOPackedBlurred, packedDataBlurredTex); } else { - cmd.SetComputeTextureParam(blurCS, parameters.denoiseKernelSpatial, HDShaderIDs._OcclusionTexture, aoOutputTex); + cmd.SetComputeTextureParam(parameters.denoiseAOCS, parameters.denoiseKernelSpatial, HDShaderIDs._OcclusionTexture, aoOutputTex); } - cmd.DispatchCompute(blurCS, parameters.denoiseKernelSpatial, threadGroupX, threadGroupY, parameters.viewCount); + cmd.DispatchCompute(parameters.denoiseAOCS, parameters.denoiseKernelSpatial, threadGroupX, threadGroupY, parameters.viewCount); } if (parameters.temporalAccumulation) @@ -524,9 +503,7 @@ static void UpsampleAO( in RenderAOParameters parameters, { bool blurAndUpsample = !parameters.temporalAccumulation; - cmd.SetComputeVectorParam(parameters.upsampleAndBlurAOCS, HDShaderIDs._AOBufferSize, parameters.aoBufferInfo); - cmd.SetComputeVectorParam(parameters.upsampleAndBlurAOCS, HDShaderIDs._AOParams1, parameters.aoParams1); - cmd.SetComputeVectorParam(parameters.upsampleAndBlurAOCS, HDShaderIDs._AOParams3, parameters.aoParams3); + ConstantBuffer.Set(cmd, parameters.upsampleAndBlurAOCS, HDShaderIDs._ShaderVariablesAmbientOcclusion); if (blurAndUpsample) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOCommon.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOCommon.hlsl index 770213f9085..bd494f80341 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOCommon.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOCommon.hlsl @@ -2,17 +2,7 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Builtin/BuiltinData.hlsl" #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl" - -CBUFFER_START(GTAOUniformBuffer) -float4 _AOBufferSize; -float4 _AOParams0; -float4 _AOParams1; -float4 _AOParams2; -float4 _AOParams3; -float4 _AOParams4; -float4 _FirstTwoDepthMipOffsets; -float4 _AODepthToViewParams; -CBUFFER_END +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.hlsl" #define _AOBaseResMip (int)_AOParams0.x #define _AOFOVCorrection _AOParams0.y diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs new file mode 100644 index 00000000000..749905861ae --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs @@ -0,0 +1,15 @@ +namespace UnityEngine.Rendering.HighDefinition +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + unsafe struct ShaderVariablesAmbientOcclusion + { + public Vector4 _AOBufferSize; + public Vector4 _AOParams0; + public Vector4 _AOParams1; + public Vector4 _AOParams2; + public Vector4 _AOParams3; + public Vector4 _AOParams4; + public Vector4 _FirstTwoDepthMipOffsets; + public Vector4 _AODepthToViewParams; + } +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.hlsl new file mode 100644 index 00000000000..4b26b4190a1 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.hlsl @@ -0,0 +1,21 @@ +// +// This file was automatically generated. Please don't edit by hand. +// + +#ifndef SHADERVARIABLESAMBIENTOCCLUSION_CS_HLSL +#define SHADERVARIABLESAMBIENTOCCLUSION_CS_HLSL +// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesAmbientOcclusion +// PackingRules = Exact +CBUFFER_START(ShaderVariablesAmbientOcclusion) + float4 _AOBufferSize; + float4 _AOParams0; + float4 _AOParams1; + float4 _AOParams2; + float4 _AOParams3; + float4 _AOParams4; + float4 _FirstTwoDepthMipOffsets; + float4 _AODepthToViewParams; +CBUFFER_END + + +#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.hlsl.meta new file mode 100644 index 00000000000..5a90d52e56e --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.hlsl.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 76eeb935e3f2f6341a2ade96fccecc6c +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.meta new file mode 100644 index 00000000000..12690d4aec6 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesAmbientOcclusion.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7c03f6c0f9d8ed845a32d1b5bdc6223c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 220f3de8923..ec472492dbd 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -720,18 +720,11 @@ static class HDShaderIDs public static readonly int _LowResDepthTexture = Shader.PropertyToID("_LowResDepthTexture"); public static readonly int _LowResTransparent = Shader.PropertyToID("_LowResTransparent"); - public static readonly int _AOBufferSize = Shader.PropertyToID("_AOBufferSize"); - public static readonly int _AOParams0 = Shader.PropertyToID("_AOParams0"); - public static readonly int _AOParams1 = Shader.PropertyToID("_AOParams1"); - public static readonly int _AOParams2 = Shader.PropertyToID("_AOParams2"); - public static readonly int _AOParams3 = Shader.PropertyToID("_AOParams3"); - public static readonly int _AOParams4 = Shader.PropertyToID("_AOParams4"); - public static readonly int _FirstTwoDepthMipOffsets = Shader.PropertyToID("_FirstTwoDepthMipOffsets"); + public static readonly int _ShaderVariablesAmbientOcclusion = Shader.PropertyToID("ShaderVariablesAmbientOcclusion"); public static readonly int _OcclusionTexture = Shader.PropertyToID("_OcclusionTexture"); public static readonly int _BentNormalsTexture = Shader.PropertyToID("_BentNormalsTexture"); public static readonly int _AOPackedData = Shader.PropertyToID("_AOPackedData"); public static readonly int _AOPackedHistory = Shader.PropertyToID("_AOPackedHistory"); - public static readonly int _AODepthToViewParams = Shader.PropertyToID("_AODepthToViewParams"); public static readonly int _AOPackedBlurred = Shader.PropertyToID("_AOPackedBlurred"); public static readonly int _AOOutputHistory = Shader.PropertyToID("_AOOutputHistory"); From 0a6be8a397a8e8ed253e1fef803cb7bf4d59374a Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Mon, 23 Mar 2020 11:49:33 +0100 Subject: [PATCH 51/92] Fixed warning --- .../Runtime/RenderPipeline/HDRenderPipeline.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 3729b71f7c3..cc1ece65fc4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -3723,7 +3723,6 @@ struct RenderSSRParameters public int width, height, viewCount; - public int depthPyramidMipCount; public ComputeBuffer offsetBufferData; public ComputeBuffer coarseStencilBuffer; From 233d32c9728ef21ab162612c22c939928a988f58 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Mon, 23 Mar 2020 12:12:13 +0100 Subject: [PATCH 52/92] Removed some useless SetGlobalXXX in Light Cookie Manager --- .../Runtime/Lighting/LightCookieManager.cs | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs index 8de7e0f0406..489c9d44c28 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs @@ -159,11 +159,12 @@ Texture FilterAreaLightTexture(CommandBuffer cmd, Texture source) // Start by copying the source texture to the array slice's mip 0 { - cmd.SetGlobalTexture(s_texSource, source); - cmd.SetGlobalInt(s_sourceMipLevel, 0); + m_MPBFilterAreaLights.SetInt(s_sourceMipLevel, 0); + m_MPBFilterAreaLights.SetTexture(s_texSource, source); + cmd.SetRenderTarget(m_TempRenderTexture0, 0); cmd.SetViewport(new Rect(0, 0, viewportWidth, viewportHeight)); - cmd.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 0, MeshTopology.Triangles, 3, 1); + cmd.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 0, MeshTopology.Triangles, 3, 1, m_MPBFilterAreaLights); } // Then operate on all the remaining mip levels @@ -177,13 +178,14 @@ Texture FilterAreaLightTexture(CommandBuffer cmd, Texture source) viewportWidth = Mathf.Max(1, viewportWidth >> 1); targetWidth = Mathf.Max(1, targetWidth >> 1); + m_MPBFilterAreaLights.SetTexture(s_texSource, m_TempRenderTexture0); + m_MPBFilterAreaLights.SetInt(s_sourceMipLevel, mipIndex - 1); + m_MPBFilterAreaLights.SetVector(s_sourceSize, sourceSize); + m_MPBFilterAreaLights.SetVector(s_uvLimits, uvLimits); + cmd.SetRenderTarget(m_TempRenderTexture1, mipIndex-1); // Temp texture is already 1 mip lower than source cmd.SetViewport(new Rect(0, 0, viewportWidth, viewportHeight)); - cmd.SetGlobalTexture(s_texSource, m_TempRenderTexture0); - cmd.SetGlobalInt(s_sourceMipLevel, mipIndex-1); // Use previous mip as source - cmd.SetGlobalVector(s_sourceSize, sourceSize); - cmd.SetGlobalVector(s_uvLimits, uvLimits); - cmd.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 1, MeshTopology.Triangles, 3, 1); + cmd.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 1, MeshTopology.Triangles, 3, 1, m_MPBFilterAreaLights); } sourceWidth = targetWidth; @@ -195,13 +197,14 @@ Texture FilterAreaLightTexture(CommandBuffer cmd, Texture source) viewportHeight = Mathf.Max(1, viewportHeight >> 1); targetHeight = Mathf.Max(1, targetHeight >> 1); + m_MPBFilterAreaLights.SetTexture(s_texSource, m_TempRenderTexture1); + m_MPBFilterAreaLights.SetInt(s_sourceMipLevel, mipIndex - 1); + m_MPBFilterAreaLights.SetVector(s_sourceSize, sourceSize); + m_MPBFilterAreaLights.SetVector(s_uvLimits, uvLimits); + cmd.SetRenderTarget(m_TempRenderTexture0, mipIndex); cmd.SetViewport(new Rect(0, 0, viewportWidth, viewportHeight)); - cmd.SetGlobalTexture(s_texSource, m_TempRenderTexture1); - cmd.SetGlobalInt(s_sourceMipLevel, mipIndex-1); - cmd.SetGlobalVector(s_sourceSize, sourceSize); - cmd.SetGlobalVector(s_uvLimits, uvLimits); - cmd.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 2, MeshTopology.Triangles, 3, 1); + cmd.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 2, MeshTopology.Triangles, 3, 1, m_MPBFilterAreaLights); } sourceHeight = targetHeight; From 049a421eb7d8fa0838dea19a0f4009434cca9c34 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Mon, 23 Mar 2020 14:50:08 +0100 Subject: [PATCH 53/92] Converted debug display to use constant buffer. --- .../Runtime/Debug/DebugDisplay.cs | 36 ++++++++ .../Runtime/Debug/DebugDisplay.cs.hlsl | 30 +++++++ .../Runtime/Debug/DebugDisplay.hlsl | 32 -------- .../Runtime/Debug/DebugFullScreen.shader | 8 +- .../Debug/DebugViewMaterialGBuffer.shader | 2 +- .../Runtime/Lighting/LightLoop/LightLoop.cs | 11 --- .../RenderPipeline/HDRenderPipeline.cs | 82 ++++++++++++------- .../RenderPipeline/HDStringConstants.cs | 20 +---- .../ShaderPass/ShaderPassForward.hlsl | 6 +- .../ShaderPass/ShaderPassForwardUnlit.hlsl | 8 +- .../VFXGraph/Shaders/VFXLitPixelOutput.hlsl | 20 ++--- 11 files changed, 142 insertions(+), 113 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs index 2ea1989f55e..4b436edc709 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs @@ -5,6 +5,42 @@ namespace UnityEngine.Rendering.HighDefinition { + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + unsafe struct ShaderVariablesDebugDisplay + { + [HLSLArray(32, typeof(Vector4))] + public fixed float _DebugRenderingLayersColors[32 * 4]; + [HLSLArray(11, typeof(ShaderGenUInt4))] + public fixed int _DebugViewMaterialArray[11 * 4]; // Contain the id (define in various materialXXX.cs.hlsl) of the property to display + + public int _DebugLightingMode; // Match enum DebugLightingMode + public int _DebugLightLayersMask; + public int _DebugShadowMapMode; + public int _DebugMipMapMode; // Match enum DebugMipMapMode + + public int _DebugFullScreenMode; + public float _DebugTransparencyOverdrawWeight; + public int _DebugMipMapModeTerrainTexture; // Match enum DebugMipMapModeTerrainTexture + public int _ColorPickerMode; // Match enum ColorPickerDebugMode + + public Vector4 _DebugLightingAlbedo; // x == bool override, yzw = albedo for diffuse + public Vector4 _DebugLightingSmoothness; // x == bool override, y == override value + public Vector4 _DebugLightingNormal; // x == bool override + public Vector4 _DebugLightingAmbientOcclusion; // x == bool override, y == override value + public Vector4 _DebugLightingSpecularColor; // x == bool override, yzw = specular color + public Vector4 _DebugLightingEmissiveColor; // x == bool override, yzw = emissive color + public Vector4 _DebugLightingMaterialValidateHighColor; // user can specific the colors for the validator error conditions + public Vector4 _DebugLightingMaterialValidateLowColor; + public Vector4 _DebugLightingMaterialValidatePureMetalColor; + public Vector4 _MousePixelCoord; // xy unorm, zw norm + public Vector4 _MouseClickPixelCoord; // xy unorm, zw norm + + public float _DebugExposure; + public int _MatcapMixAlbedo; + public float _MatcapViewScale; + public int _DebugSingleShadowIndex; + } + /// /// Full Screen Debug Mode. /// diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl index 4349a804e4a..ffc2248c367 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl @@ -35,5 +35,35 @@ #define FULLSCREENDEBUGMODE_VALIDATE_SPECULAR_COLOR (25) #define FULLSCREENDEBUGMODE_MAX_MATERIAL_FULL_SCREEN_DEBUG (26) +// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesDebugDisplay +// PackingRules = Exact +CBUFFER_START(ShaderVariablesDebugDisplay) + float4 _DebugRenderingLayersColors[32]; + uint4 _DebugViewMaterialArray[11]; + int _DebugLightingMode; + int _DebugLightLayersMask; + int _DebugShadowMapMode; + int _DebugMipMapMode; + int _DebugFullScreenMode; + float _DebugTransparencyOverdrawWeight; + int _DebugMipMapModeTerrainTexture; + int _ColorPickerMode; + float4 _DebugLightingAlbedo; + float4 _DebugLightingSmoothness; + float4 _DebugLightingNormal; + float4 _DebugLightingAmbientOcclusion; + float4 _DebugLightingSpecularColor; + float4 _DebugLightingEmissiveColor; + float4 _DebugLightingMaterialValidateHighColor; + float4 _DebugLightingMaterialValidateLowColor; + float4 _DebugLightingMaterialValidatePureMetalColor; + float4 _MousePixelCoord; + float4 _MouseClickPixelCoord; + float _DebugExposure; + int _MatcapMixAlbedo; + float _MatcapViewScale; + int _DebugSingleShadowIndex; +CBUFFER_END + #endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.hlsl index d89e89f18a8..5568de444ed 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.hlsl @@ -9,38 +9,6 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Debug/MipMapDebug.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Debug/ColorPickerDebug.cs.hlsl" -CBUFFER_START(UnityDebugDisplay) -// Set of parameters available when switching to debug shader mode -int _DebugLightingMode; // Match enum DebugLightingMode -int _DebugLightLayersMask; -float4 _DebugRenderingLayersColors[32]; -int _DebugShadowMapMode; -float _DebugViewMaterialArray[11]; // Contain the id (define in various materialXXX.cs.hlsl) of the property to display -int _DebugMipMapMode; // Match enum DebugMipMapMode -int _DebugMipMapModeTerrainTexture; // Match enum DebugMipMapModeTerrainTexture -int _ColorPickerMode; // Match enum ColorPickerDebugMode -int _DebugStep; -int _DebugDepthPyramidMip; -int _DebugFullScreenMode; -float _DebugTransparencyOverdrawWeight; -float4 _DebugLightingAlbedo; // x == bool override, yzw = albedo for diffuse -float4 _DebugLightingSmoothness; // x == bool override, y == override value -float4 _DebugLightingNormal; // x == bool override -float4 _DebugLightingAmbientOcclusion; // x == bool override, y == override value -float4 _DebugLightingSpecularColor; // x == bool override, yzw = specular color -float4 _DebugLightingEmissiveColor; // x == bool override, yzw = emissive color -float4 _DebugLightingMaterialValidateHighColor; // user can specific the colors for the validator error conditions -float4 _DebugLightingMaterialValidateLowColor; -float4 _DebugLightingMaterialValidatePureMetalColor; -float4 _MousePixelCoord; // xy unorm, zw norm -float4 _MouseClickPixelCoord; // xy unorm, zw norm -float _DebugExposure; -int _MatcapMixAlbedo; -int _MatcapViewScale; -uint _DebugContactShadowLightIndex; -int _DebugSingleShadowIndex; -CBUFFER_END - // Local shader variables static DirectionalShadowType g_DebugShadowAttenuation = 0; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugFullScreen.shader b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugFullScreen.shader index f60a8c8b73c..0982435b504 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugFullScreen.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugFullScreen.shader @@ -29,6 +29,8 @@ Shader "Hidden/HDRP/DebugFullScreen" CBUFFER_START (UnityDebug) float _FullScreenDebugMode; float _TransparencyOverdrawMaxPixelCost; + uint _DebugContactShadowLightIndex; + int _DebugDepthPyramidMip; CBUFFER_END TEXTURE2D_X(_DebugFullScreenTexture); @@ -299,14 +301,14 @@ Shader "Hidden/HDRP/DebugFullScreen" float linearDepth = frac(posInput.linearDepth * 0.1); return float4(linearDepth.xxx, 1.0); } - + if (_FullScreenDebugMode == FULLSCREENDEBUGMODE_TRANSPARENCY_OVERDRAW) { float4 color = (float4)0; - + float pixelCost = SAMPLE_TEXTURE2D_X(_DebugFullScreenTexture, s_point_clamp_sampler, input.texcoord).r; if ((pixelCost > 0.001)) - color.rgb = HsvToRgb(float3(0.66 * saturate(1.0 - (1.0 / _TransparencyOverdrawMaxPixelCost) * pixelCost), 1.0, 1.0));// + color.rgb = HsvToRgb(float3(0.66 * saturate(1.0 - (1.0 / _TransparencyOverdrawMaxPixelCost) * pixelCost), 1.0, 1.0));// return color; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugViewMaterialGBuffer.shader b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugViewMaterialGBuffer.shader index cdfb24af2a7..747665e14e9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugViewMaterialGBuffer.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugViewMaterialGBuffer.shader @@ -74,7 +74,7 @@ Shader "Hidden/HDRP/DebugViewMaterialGBuffer" // - a gBufferIndex (always stored in _DebugViewMaterialArray[1] as only one supported) // - a property index which is different for each kind of material even if reflecting the same thing (see MaterialSharedProperty) // So here if the buffer is of size zero, it is the same as if we give in a 0 buffer index. - int bufferIndex = int(_DebugViewMaterialArray[0]) >= 1 ? int(_DebugViewMaterialArray[1]) : 0; + int bufferIndex = _DebugViewMaterialArray[0].x >= 1 ? _DebugViewMaterialArray[1].x : 0; if (bufferIndex == DEBUGVIEWGBUFFER_DEPTH) { float linearDepth = frac(posInput.linearDepth * 0.1); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 6d35b16f6c6..3a2c3a864af 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -2598,17 +2598,6 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu } m_enableBakeShadowMask = m_enableBakeShadowMask && hdCamera.frameSettings.IsEnabled(FrameSettingsField.Shadowmask); - - // We push this parameter here because we know that normal/deferred shadows are not yet rendered - if (debugDisplaySettings.data.lightingDebugSettings.shadowDebugMode == ShadowMapDebugMode.SingleShadow) - { - int shadowIndex = (int)debugDisplaySettings.data.lightingDebugSettings.shadowMapIndex; - - if (debugDisplaySettings.data.lightingDebugSettings.shadowDebugUseSelection) - shadowIndex = m_DebugSelectedLightShadowIndex; - cmd.SetGlobalInt(HDShaderIDs._DebugSingleShadowIndex, shadowIndex); - } - return m_enableBakeShadowMask; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index cc1ece65fc4..22c18fbbe68 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -169,6 +169,7 @@ internal static Volume GetOrCreateDefaultVolume() // Constant Buffers ShaderVariablesGlobal m_ShaderVariablesGlobalCB = new ShaderVariablesGlobal(); ShaderVariablesXR m_ShaderVariablesXRCB = new ShaderVariablesXR(); + ShaderVariablesDebugDisplay m_ShaderVariablesDebugDisplayCB = new ShaderVariablesDebugDisplay(); // The current MSAA count MSAASamples m_MSAASamples; @@ -3329,7 +3330,8 @@ void RenderTransparencyOverdraw(CullingResults cull, HDCamera hdCamera, Scriptab }; // High res transparent objects, drawing in m_DebugFullScreenTempBuffer - cmd.SetGlobalFloat(HDShaderIDs._DebugTransparencyOverdrawWeight, 1.0f); + m_ShaderVariablesDebugDisplayCB._DebugTransparencyOverdrawWeight = 1.0f; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesDebugDisplayCB, HDShaderIDs._ShaderVariablesDebugDisplay); var passNames = m_Asset.currentPlatformRenderPipelineSettings.supportTransparentBackface ? m_AllTransparentPassNames : m_TransparentNoBackfaceNames; m_DebugFullScreenPropertyBlock.SetFloat(HDShaderIDs._TransparencyOverdrawMaxPixelCost, (float)m_DebugDisplaySettings.data.transparencyDebugSettings.maxPixelCost); @@ -3339,7 +3341,8 @@ void RenderTransparencyOverdraw(CullingResults cull, HDCamera hdCamera, Scriptab DrawTransparentRendererList(renderContext, cmd, hdCamera.frameSettings, rendererList); // Low res transparent objects, copying result m_DebugTranparencyLowRes - cmd.SetGlobalFloat(HDShaderIDs._DebugTransparencyOverdrawWeight, 0.25f); + m_ShaderVariablesDebugDisplayCB._DebugTransparencyOverdrawWeight = 0.25f; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesDebugDisplayCB, HDShaderIDs._ShaderVariablesDebugDisplay); rendererList = RendererList.Create(CreateTransparentRendererListDesc(cull, hdCamera.camera, passNames, renderQueueRange: HDRenderQueue.k_RenderQueue_LowTransparent, stateBlock: stateBlock)); DrawTransparentRendererList(renderContext, cmd, hdCamera.frameSettings, rendererList); PushFullScreenDebugTexture(hdCamera, cmd, m_CameraColorBuffer, FullScreenDebugMode.TransparencyOverdraw); @@ -3980,7 +3983,7 @@ void UpsampleTransparent(HDCamera hdCamera, CommandBuffer cmd) } } - void ApplyDebugDisplaySettings(HDCamera hdCamera, CommandBuffer cmd) + unsafe void ApplyDebugDisplaySettings(HDCamera hdCamera, CommandBuffer cmd) { // See ShaderPassForward.hlsl: for forward shaders, if DEBUG_DISPLAY is enabled and no DebugLightingMode or DebugMipMapMod // modes have been set, lighting is automatically skipped (To avoid some crashed due to lighting RT not set on console). @@ -4017,39 +4020,55 @@ void ApplyDebugDisplaySettings(HDCamera hdCamera, CommandBuffer cmd) debugLightingMode = DebugLightingMode.MatcapView; } - cmd.SetGlobalFloatArray(HDShaderIDs._DebugViewMaterial, m_CurrentDebugDisplaySettings.GetDebugMaterialIndexes()); - cmd.SetGlobalInt(HDShaderIDs._DebugLightingMode, (int)debugLightingMode); - cmd.SetGlobalInt(HDShaderIDs._DebugLightLayersMask, (int)m_CurrentDebugDisplaySettings.GetDebugLightLayersMask()); - cmd.SetGlobalVectorArray(HDShaderIDs._DebugRenderingLayersColors, m_CurrentDebugDisplaySettings.data.lightingDebugSettings.debugRenderingLayersColors); - cmd.SetGlobalInt(HDShaderIDs._DebugShadowMapMode, (int)m_CurrentDebugDisplaySettings.GetDebugShadowMapMode()); - cmd.SetGlobalInt(HDShaderIDs._DebugMipMapMode, (int)m_CurrentDebugDisplaySettings.GetDebugMipMapMode()); - cmd.SetGlobalInt(HDShaderIDs._DebugMipMapModeTerrainTexture, (int)m_CurrentDebugDisplaySettings.GetDebugMipMapModeTerrainTexture()); - cmd.SetGlobalInt(HDShaderIDs._ColorPickerMode, (int)m_CurrentDebugDisplaySettings.GetDebugColorPickerMode()); - cmd.SetGlobalInt(HDShaderIDs._DebugFullScreenMode, (int)m_CurrentDebugDisplaySettings.data.fullScreenDebugMode); + ref var cb = ref m_ShaderVariablesDebugDisplayCB; + + var debugMaterialIndices = m_CurrentDebugDisplaySettings.GetDebugMaterialIndexes(); + for (int i = 0; i < 11; ++i) + { + cb._DebugViewMaterialArray[i * 4] = (int)debugMaterialIndices[i]; // Only x component is used. + } + for (int i = 0; i < 32; ++i) + { + for (int j = 0; j < 4; ++j) + cb._DebugRenderingLayersColors[i * 4 + j] = m_CurrentDebugDisplaySettings.data.lightingDebugSettings.debugRenderingLayersColors[i][j]; + } + + cb._DebugLightingMode = (int)debugLightingMode; + cb._DebugLightLayersMask = (int)m_CurrentDebugDisplaySettings.GetDebugLightLayersMask(); + cb._DebugShadowMapMode = (int)m_CurrentDebugDisplaySettings.GetDebugShadowMapMode(); + cb._DebugMipMapMode = (int)m_CurrentDebugDisplaySettings.GetDebugMipMapMode(); + cb._DebugMipMapModeTerrainTexture = (int)m_CurrentDebugDisplaySettings.GetDebugMipMapModeTerrainTexture(); + cb._ColorPickerMode = (int)m_CurrentDebugDisplaySettings.GetDebugColorPickerMode(); + cb._DebugFullScreenMode = (int)m_CurrentDebugDisplaySettings.data.fullScreenDebugMode; #if UNITY_EDITOR - cmd.SetGlobalInt(HDShaderIDs._MatcapMixAlbedo, HDRenderPipelinePreferences.matcapViewMixAlbedo ? 1 : 0); - cmd.SetGlobalFloat(HDShaderIDs._MatcapViewScale, HDRenderPipelinePreferences.matcapViewScale); + cb._MatcapMixAlbedo = HDRenderPipelinePreferences.matcapViewMixAlbedo ? 1 : 0; + cb._MatcapViewScale = HDRenderPipelinePreferences.matcapViewScale; #else - cmd.SetGlobalInt(HDShaderIDs._MatcapMixAlbedo, 0); - cmd.SetGlobalFloat(HDShaderIDs._MatcapViewScale, 1.0f); + cb._MatcapMixAlbedo = 0; + cb._MatcapViewScale = 1.0f; #endif - cmd.SetGlobalVector(HDShaderIDs._DebugLightingAlbedo, debugAlbedo); - cmd.SetGlobalVector(HDShaderIDs._DebugLightingSmoothness, debugSmoothness); - cmd.SetGlobalVector(HDShaderIDs._DebugLightingNormal, debugNormal); - cmd.SetGlobalVector(HDShaderIDs._DebugLightingAmbientOcclusion, debugAmbientOcclusion); - cmd.SetGlobalVector(HDShaderIDs._DebugLightingSpecularColor, debugSpecularColor); - cmd.SetGlobalVector(HDShaderIDs._DebugLightingEmissiveColor, debugEmissiveColor); - cmd.SetGlobalColor(HDShaderIDs._DebugLightingMaterialValidateHighColor, materialDebugSettings.materialValidateHighColor); - cmd.SetGlobalColor(HDShaderIDs._DebugLightingMaterialValidateLowColor, materialDebugSettings.materialValidateLowColor); - cmd.SetGlobalColor(HDShaderIDs._DebugLightingMaterialValidatePureMetalColor, debugTrueMetalColor); - - cmd.SetGlobalVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(hdCamera)); - cmd.SetGlobalVector(HDShaderIDs._MouseClickPixelCoord, HDUtils.GetMouseClickCoordinates(hdCamera)); - cmd.SetGlobalTexture(HDShaderIDs._DebugFont, defaultResources.textures.debugFontTex); + cb._DebugLightingAlbedo = debugAlbedo; + cb._DebugLightingSmoothness = debugSmoothness; + cb._DebugLightingNormal = debugNormal; + cb._DebugLightingAmbientOcclusion = debugAmbientOcclusion; + cb._DebugLightingSpecularColor = debugSpecularColor; + cb._DebugLightingEmissiveColor = debugEmissiveColor; + cb._DebugLightingMaterialValidateHighColor = materialDebugSettings.materialValidateHighColor; + cb._DebugLightingMaterialValidateLowColor = materialDebugSettings.materialValidateLowColor; + cb._DebugLightingMaterialValidatePureMetalColor = debugTrueMetalColor; + + cb._MousePixelCoord = HDUtils.GetMouseCoordinates(hdCamera); + cb._MouseClickPixelCoord = HDUtils.GetMouseClickCoordinates(hdCamera); // The DebugNeedsExposure test allows us to set a neutral value if exposure is not needed. This way we don't need to make various tests inside shaders but only in this function. - cmd.SetGlobalFloat(HDShaderIDs._DebugExposure, m_CurrentDebugDisplaySettings.DebugNeedsExposure() ? lightingDebugSettings.debugExposure : 0.0f); + cb._DebugExposure = m_CurrentDebugDisplaySettings.DebugNeedsExposure() ? lightingDebugSettings.debugExposure : 0.0f; + + cb._DebugSingleShadowIndex = m_CurrentDebugDisplaySettings.data.lightingDebugSettings.shadowDebugUseSelection ? m_DebugSelectedLightShadowIndex : (int)m_CurrentDebugDisplaySettings.data.lightingDebugSettings.shadowMapIndex; + + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesDebugDisplayCB, HDShaderIDs._ShaderVariablesDebugDisplay); + + cmd.SetGlobalTexture(HDShaderIDs._DebugFont, defaultResources.textures.debugFontTex); } } @@ -4195,6 +4214,9 @@ static void ResolveColorPickerDebug(in DebugParameters parameters, parameters.colorPickerMaterial.SetColor(HDShaderIDs._ColorPickerFontColor, colorPickerDebugSettings.fontColor); parameters.colorPickerMaterial.SetInt(HDShaderIDs._FalseColorEnabled, falseColorDebugSettings.falseColor ? 1 : 0); parameters.colorPickerMaterial.SetVector(HDShaderIDs._FalseColorThresholds, falseColorThresholds); + parameters.colorPickerMaterial.SetVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(parameters.hdCamera)); + parameters.colorPickerMaterial.SetVector(HDShaderIDs._MouseClickPixelCoord, HDUtils.GetMouseClickCoordinates(parameters.hdCamera)); + // The material display debug perform sRGBToLinear conversion as the final blit currently hardcodes a linearToSrgb conversion. As when we read with color picker this is not done, // we perform it inside the color picker shader. But we shouldn't do it for HDR buffer. parameters.colorPickerMaterial.SetFloat(HDShaderIDs._ApplyLinearToSRGB, parameters.debugDisplaySettings.IsDebugMaterialDisplayEnabled() ? 1.0f : 0.0f); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index ec472492dbd..412e68682ba 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -139,30 +139,11 @@ static class HDShaderIDs public static readonly int _SliceIndex = Shader.PropertyToID("_SliceIndex"); public static readonly int _DebugContactShadowLightIndex = Shader.PropertyToID("_DebugContactShadowLightIndex"); - public static readonly int _DebugViewMaterial = Shader.PropertyToID("_DebugViewMaterialArray"); - public static readonly int _DebugLightingMode = Shader.PropertyToID("_DebugLightingMode"); - public static readonly int _DebugLightLayersMask = Shader.PropertyToID("_DebugLightLayersMask"); - public static readonly int _DebugRenderingLayersColors = Shader.PropertyToID("_DebugRenderingLayersColors"); - public static readonly int _DebugShadowMapMode = Shader.PropertyToID("_DebugShadowMapMode"); - public static readonly int _DebugLightingAlbedo = Shader.PropertyToID("_DebugLightingAlbedo"); - public static readonly int _DebugLightingSmoothness = Shader.PropertyToID("_DebugLightingSmoothness"); - public static readonly int _DebugLightingNormal = Shader.PropertyToID("_DebugLightingNormal"); - public static readonly int _DebugLightingAmbientOcclusion = Shader.PropertyToID("_DebugLightingAmbientOcclusion"); - public static readonly int _DebugLightingSpecularColor = Shader.PropertyToID("_DebugLightingSpecularColor"); - public static readonly int _DebugLightingEmissiveColor = Shader.PropertyToID("_DebugLightingEmissiveColor"); public static readonly int _AmbientOcclusionTexture = Shader.PropertyToID("_AmbientOcclusionTexture"); public static readonly int _AmbientOcclusionTextureRW = Shader.PropertyToID("_AmbientOcclusionTextureRW"); public static readonly int _MultiAmbientOcclusionTexture = Shader.PropertyToID("_MultiAmbientOcclusionTexture"); - public static readonly int _DebugMipMapMode = Shader.PropertyToID("_DebugMipMapMode"); - public static readonly int _DebugMipMapModeTerrainTexture = Shader.PropertyToID("_DebugMipMapModeTerrainTexture"); - public static readonly int _DebugSingleShadowIndex = Shader.PropertyToID("_DebugSingleShadowIndex"); public static readonly int _DebugDepthPyramidMip = Shader.PropertyToID("_DebugDepthPyramidMip"); public static readonly int _DebugDepthPyramidOffsets = Shader.PropertyToID("_DebugDepthPyramidOffsets"); - public static readonly int _DebugLightingMaterialValidateHighColor = Shader.PropertyToID("_DebugLightingMaterialValidateHighColor"); - public static readonly int _DebugLightingMaterialValidateLowColor = Shader.PropertyToID("_DebugLightingMaterialValidateLowColor"); - public static readonly int _DebugLightingMaterialValidatePureMetalColor = Shader.PropertyToID("_DebugLightingMaterialValidatePureMetalColor"); - public static readonly int _DebugFullScreenMode = Shader.PropertyToID("_DebugFullScreenMode"); - public static readonly int _DebugTransparencyOverdrawWeight = Shader.PropertyToID("_DebugTransparencyOverdrawWeight"); public static readonly int _UseTileLightList = Shader.PropertyToID("_UseTileLightList"); @@ -272,6 +253,7 @@ static class HDShaderIDs public static readonly int _ShaderVariablesXR = Shader.PropertyToID("ShaderVariablesXR"); public static readonly int _ShaderVariablesVolumetric = Shader.PropertyToID("ShaderVariablesVolumetric"); public static readonly int _ShaderVariablesLightList = Shader.PropertyToID("ShaderVariablesLightList"); + public static readonly int _ShaderVariablesDebugDisplay = Shader.PropertyToID("ShaderVariablesDebugDisplay"); public static readonly int _SSSBufferTexture = Shader.PropertyToID("_SSSBufferTexture"); public static readonly int _NormalBufferTexture = Shader.PropertyToID("_NormalBufferTexture"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl index daad559f332..ad576d1c074 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl @@ -119,7 +119,7 @@ void Frag(PackedVaryingsToPS packedInput, ENCODE_INTO_SSSBUFFER(surfaceData, posInput.positionSS, outSSSBuffer); #endif - + // Same code in ShaderPassForwardUnlit.shader // Reminder: _DebugViewMaterialArray[i] @@ -129,7 +129,7 @@ void Frag(PackedVaryingsToPS packedInput, // - a gBufferIndex (always stored in _DebugViewMaterialArray[1] as only one supported) // - a property index which is different for each kind of material even if reflecting the same thing (see MaterialSharedProperty) bool viewMaterial = false; - int bufferSize = int(_DebugViewMaterialArray[0]); + int bufferSize = _DebugViewMaterialArray[0].x; if (bufferSize != 0) { bool needLinearToSRGB = false; @@ -139,7 +139,7 @@ void Frag(PackedVaryingsToPS packedInput, // Works because GetSurfaceDataDebug will do nothing if the index is not a known one for (int index = 1; index <= bufferSize; index++) { - int indexMaterialProperty = int(_DebugViewMaterialArray[index]); + int indexMaterialProperty = _DebugViewMaterialArray[index].x; // skip if not really in use if (indexMaterialProperty != 0) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForwardUnlit.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForwardUnlit.hlsl index 43d8222d98e..8ceb9ecfaa5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForwardUnlit.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForwardUnlit.hlsl @@ -58,12 +58,12 @@ float4 Frag(PackedVaryingsToPS packedInput) : SV_Target // The index stored in this buffer could either be // - a gBufferIndex (always stored in _DebugViewMaterialArray[1] as only one supported) // - a property index which is different for each kind of material even if reflecting the same thing (see MaterialSharedProperty) - int bufferSize = int(_DebugViewMaterialArray[0]); + int bufferSize = _DebugViewMaterialArray[0].x; // Loop through the whole buffer // Works because GetSurfaceDataDebug will do nothing if the index is not a known one for (int index = 1; index <= bufferSize; index++) { - int indexMaterialProperty = int(_DebugViewMaterialArray[index]); + int indexMaterialProperty = _DebugViewMaterialArray[index].x; if (indexMaterialProperty != 0) { float3 result = float3(1.0, 0.0, 1.0); @@ -74,7 +74,7 @@ float4 Frag(PackedVaryingsToPS packedInput) : SV_Target GetBuiltinDataDebug(indexMaterialProperty, builtinData, posInput, result, needLinearToSRGB); GetSurfaceDataDebug(indexMaterialProperty, surfaceData, result, needLinearToSRGB); GetBSDFDataDebug(indexMaterialProperty, bsdfData, result, needLinearToSRGB); - + // TEMP! // For now, the final blit in the backbuffer performs an sRGB write // So in the meantime we apply the inverse transform to linear data to compensate. @@ -92,6 +92,6 @@ float4 Frag(PackedVaryingsToPS packedInput) : SV_Target } #endif - + return outColor; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXLitPixelOutput.hlsl b/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXLitPixelOutput.hlsl index 1800f255452..fe43e6555a6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXLitPixelOutput.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXLitPixelOutput.hlsl @@ -41,12 +41,12 @@ float4 VFXCalcPixelOutputForward(const SurfaceData surfaceData, const BuiltinDat // The index stored in this buffer could either be // - a gBufferIndex (always stored in _DebugViewMaterialArray[1] as only one supported) // - a property index which is different for each kind of material even if reflecting the same thing (see MaterialSharedProperty) - int bufferSize = int(_DebugViewMaterialArray[0]); + int bufferSize = _DebugViewMaterialArray[0].x; // Loop through the whole buffer // Works because GetSurfaceDataDebug will do nothing if the index is not a known one for (int index = 1; index <= bufferSize; index++) { - int indexMaterialProperty = int(_DebugViewMaterialArray[index]); + int indexMaterialProperty = _DebugViewMaterialArray[index].x; if (indexMaterialProperty != 0) { float3 result = float3(1.0, 0.0, 1.0); @@ -89,14 +89,14 @@ float4 VFXGetPixelOutputForward(const VFX_VARYING_PS_INPUTS i, float3 normalWS, uint2 tileIndex = uint2(i.VFX_VARYING_POSCS.xy) / GetTileSize(); VFXGetHDRPLitData(surfaceData,builtinData,bsdfData,preLightData,i,normalWS,uvData,tileIndex); - + float3 posRWS = VFXGetPositionRWS(i); PositionInputs posInput = GetPositionInput(i.VFX_VARYING_POSCS.xy, _ScreenSize.zw, i.VFX_VARYING_POSCS.z, i.VFX_VARYING_POSCS.w, posRWS, tileIndex); - + return VFXCalcPixelOutputForward(surfaceData,builtinData,preLightData, bsdfData, posInput, posRWS); } - + #else @@ -108,19 +108,19 @@ float4 VFXGetPixelOutputForwardShaderGraph(SurfaceData surfaceData, BuiltinData float3 posRWS = VFXGetPositionRWS(i); float4 posSS = i.VFX_VARYING_POSCS; PositionInputs posInput = GetPositionInput(posSS.xy, _ScreenSize.zw, posSS.z, posSS.w, posRWS, tileIndex); - + PreLightData preLightData = (PreLightData)0; BSDFData bsdfData = (BSDFData)0; bsdfData = ConvertSurfaceDataToBSDFData(posSS.xy, surfaceData); - + preLightData = GetPreLightData(GetWorldSpaceNormalizeViewDir(posRWS),posInput,bsdfData); preLightData.diffuseFGD = 1.0f; - + float3 emissive = builtinData.emissiveColor; InitBuiltinData(posInput, builtinData.opacity, surfaceData.normalWS, -surfaceData.normalWS, (float4)0, (float4)0, builtinData); builtinData.emissiveColor = emissive; PostInitBuiltinData(GetWorldSpaceNormalizeViewDir(posInput.positionWS), posInput,surfaceData, builtinData); - + return VFXCalcPixelOutputForward(surfaceData,builtinData,preLightData, bsdfData, posInput, posRWS); } #endif @@ -157,4 +157,4 @@ void VFXSetupBuiltin(inout BuiltinData builtin,SurfaceData surface,float3 emissi EncodeIntoNormalBuffer(ConvertSurfaceDataToNormalData(surfaceData), i.VFX_VARYING_POSCS, outNormalBuffer); \ } -#endif \ No newline at end of file +#endif From 21600ed3f673faa8ccdee600dbc9f26c7faa44e8 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Mon, 23 Mar 2020 15:35:24 +0100 Subject: [PATCH 54/92] Fixed color/depth pyramid debug --- .../Runtime/Debug/DebugDisplay.cs | 52 +------------------ .../RenderPipeline/HDRenderPipeline.Debug.cs | 5 +- .../RenderPipeline/HDRenderPipeline.cs | 4 +- 3 files changed, 6 insertions(+), 55 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs index 2ea1989f55e..b371b6f23fb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs @@ -940,56 +940,8 @@ void RegisterLightingDebug() { children = { - new DebugUI.UIntField - { - displayName = "Fullscreen Debug Mip", - getter = () => - { - float lodCount = 0.0f; - switch (data.fullScreenDebugMode) - { - case FullScreenDebugMode.FinalColorPyramid: - case FullScreenDebugMode.PreRefractionColorPyramid: - //lodCount = hdCamera.colorPyramidHistoryMipCount; - break; - default: - //lodCount = depthMipChain.mipLevelCount; - break; - } - return (uint)(data.fullscreenDebugMip * lodCount); - }, - setter = value => - { - float lodCount = 0.0f; - switch (data.fullScreenDebugMode) - { - case FullScreenDebugMode.FinalColorPyramid: - case FullScreenDebugMode.PreRefractionColorPyramid: - //lodCount = hdCamera.colorPyramidHistoryMipCount; - break; - default: - //lodCount = depthMipChain.mipLevelCount; - break; - } - data.fullscreenDebugMip = (float)Convert.ChangeType(value, typeof(float)) / lodCount; - }, - min = () => 0u, - max = () => - { - float lodCount = 0.0f; - switch (data.fullScreenDebugMode) - { - case FullScreenDebugMode.FinalColorPyramid: - case FullScreenDebugMode.PreRefractionColorPyramid: - //lodCount = hdCamera.colorPyramidHistoryMipCount; - break; - default: - //lodCount = depthMipChain.mipLevelCount; - break; - } - return (uint)lodCount; - } - } + + new DebugUI.FloatField { displayName = "Fullscreen Debug Mip", getter = () => data.fullscreenDebugMip, setter = value => data.fullscreenDebugMip = value, min = () => 0f, max = () => 1f, incStep = 0.05f } } }); break; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs index c5fc337ecef..8eda7f371ca 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs @@ -293,7 +293,7 @@ void PushFullScreenDebugTextureMip(RenderGraph renderGraph, TextureHandle input, { if (debugMode == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode) { - var mipIndex = Mathf.FloorToInt(m_CurrentDebugDisplaySettings.data.fullscreenDebugMip * (lodCount)); + var mipIndex = Mathf.FloorToInt(m_CurrentDebugDisplaySettings.data.fullscreenDebugMip * lodCount); PushFullScreenDebugTexture(renderGraph, input, mipIndex); } @@ -312,9 +312,8 @@ void PushFullScreenDebugTexture(RenderGraph renderGraph, TextureHandle input, in (PushFullScreenDebugPassData data, RenderGraphContext ctx) => { var texture = ctx.resources.GetTexture(passData.input); - var scale = new Vector4(texture.rtHandleProperties.rtHandleScale.x, texture.rtHandleProperties.rtHandleScale.y, 0f, 0f); if (data.mipIndex != -1) - HDUtils.BlitCameraTexture(ctx.cmd, texture, ctx.resources.GetTexture(passData.output), scale, data.mipIndex); + HDUtils.BlitCameraTexture(ctx.cmd, texture, ctx.resources.GetTexture(passData.output), data.mipIndex); else HDUtils.BlitCameraTexture(ctx.cmd, texture, ctx.resources.GetTexture(passData.output)); }); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 804f0038ba7..36aba96cb43 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -4125,10 +4125,10 @@ void PushFullScreenDebugTextureMip(HDCamera hdCamera, CommandBuffer cmd, RTHandl { if (debugMode == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode) { - var mipIndex = Mathf.FloorToInt(m_CurrentDebugDisplaySettings.data.fullscreenDebugMip * (lodCount)); + var mipIndex = Mathf.FloorToInt(m_CurrentDebugDisplaySettings.data.fullscreenDebugMip * lodCount); m_FullScreenDebugPushed = true; // We need this flag because otherwise if no full screen debug is pushed (like for example if the corresponding pass is disabled), when we render the result in RenderDebug m_DebugFullScreenTempBuffer will contain potential garbage - HDUtils.BlitCameraTexture(cmd, texture, m_DebugFullScreenTempBuffer, texture.rtHandleProperties.rtHandleScale, mipIndex); + HDUtils.BlitCameraTexture(cmd, texture, m_DebugFullScreenTempBuffer, mipIndex); } } From 5535110492aba49c86df6ba11ca508050676874f Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Mon, 23 Mar 2020 15:49:15 +0100 Subject: [PATCH 55/92] Cleanup --- .../Editor/Material/UIBlocks/AxfSurfaceInputsUIBlock.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AxfSurfaceInputsUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AxfSurfaceInputsUIBlock.cs index 3b379fa186c..5b1949e661c 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AxfSurfaceInputsUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AxfSurfaceInputsUIBlock.cs @@ -426,7 +426,6 @@ void DrawAxfSurfaceOptionsGUI() BRDFVariants |= ((uint)wardVariant) << 2; BRDFVariants |= ((uint)blinnVariant) << 4; -// cmd.SetGlobalFloat( HDShaderIDs._TexturingModeFlags, *(float*) &texturingModeFlags ); m_SVBRDF_BRDFType.floatValue = (float)BRDFType; m_SVBRDF_BRDFVariants.floatValue = (float)BRDFVariants; @@ -488,8 +487,6 @@ void DrawAxfSurfaceOptionsGUI() clearcoatRefraction = EditorGUILayout.Toggle("Enable Refraction", clearcoatRefraction); } -// cmd.SetGlobalFloat( HDShaderIDs._TexturingModeFlags, *(float*) &texturingModeFlags ); - --EditorGUI.indentLevel; break; } From e1ab625216bab3382d1d64baa1d756cb762def9a Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Mon, 23 Mar 2020 16:24:27 +0100 Subject: [PATCH 56/92] Implemented constant buffer for PBR sky global variables. --- .../PhysicallyBasedSkyCommon.hlsl | 39 -------- .../PhysicallyBasedSkyRenderer.cs | 99 ++++++++++++++----- .../PhysicallyBasedSkyRenderer.cs.hlsl | 31 ++++++ 3 files changed, 105 insertions(+), 64 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl index 267a1bf3c3b..473de683264 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl @@ -7,45 +7,6 @@ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Sampling.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs.hlsl" -CBUFFER_START(UnityPhysicallyBasedSky) - // All the distance-related entries use SI units (meter, 1/meter, etc). - float _PlanetaryRadius; - float _RcpPlanetaryRadius; - float _AtmosphericDepth; - float _RcpAtmosphericDepth; - - float _AtmosphericRadius; - float _AerosolAnisotropy; - float _AerosolPhasePartConstant; - float _Unused; - - float _AirDensityFalloff; - float _AirScaleHeight; - float _AerosolDensityFalloff; - float _AerosolScaleHeight; - - float3 _AirSeaLevelExtinction; - float _AerosolSeaLevelExtinction; - - float3 _AirSeaLevelScattering; - float _IntensityMultiplier; - - float3 _AerosolSeaLevelScattering; - float _ColorSaturation; - - float3 _GroundAlbedo; - float _AlphaSaturation; - - float3 _PlanetCenterPosition; // Not used during the precomputation, but needed to apply the atmospheric effect - float _AlphaMultiplier; - - float3 _HorizonTint; - float _HorizonZenithShiftPower; - - float3 _ZenithTint; - float _HorizonZenithShiftScale; -CBUFFER_END - TEXTURE2D(_GroundIrradianceTexture); // Emulate a 4D texture with a "deep" 3D texture. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs index a9f1a4b69e7..9efd77086cf 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs @@ -18,6 +18,47 @@ public enum PbrSkyConfig InScatteredRadianceTableSizeW = 64, // , } + [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + unsafe struct ShaderVariablesPhysicallyBasedSky + { + // All the distance-related entries use SI units (meter, 1/meter, etc). + public float _PlanetaryRadius; + public float _RcpPlanetaryRadius; + public float _AtmosphericDepth; + public float _RcpAtmosphericDepth; + + public float _AtmosphericRadius; + public float _AerosolAnisotropy; + public float _AerosolPhasePartConstant; + public float _Unused; + + public float _AirDensityFalloff; + public float _AirScaleHeight; + public float _AerosolDensityFalloff; + public float _AerosolScaleHeight; + + public Vector3 _AirSeaLevelExtinction; + public float _AerosolSeaLevelExtinction; + + public Vector3 _AirSeaLevelScattering; + public float _IntensityMultiplier; + + public Vector3 _AerosolSeaLevelScattering; + public float _ColorSaturation; + + public Vector3 _GroundAlbedo; + public float _AlphaSaturation; + + public Vector3 _PlanetCenterPosition; // Not used during the precomputation, but needed to apply the atmospheric effect + public float _AlphaMultiplier; + + public Vector3 _HorizonTint; + public float _HorizonZenithShiftPower; + + public Vector3 _ZenithTint; + public float _HorizonZenithShiftScale; + } + // Store the hash of the parameters each time precomputation is done. // If the hash does not match, we must recompute our data. int m_LastPrecomputationParamHash; @@ -35,6 +76,9 @@ public enum PbrSkyConfig static Material s_PbrSkyMaterial; static MaterialPropertyBlock s_PbrSkyMaterialProperties; + ShaderVariablesPhysicallyBasedSky m_ConstantBuffer; + int m_ShaderVariablesPhysicallyBasedSkyID = Shader.PropertyToID("ShaderVariablesPhysicallyBasedSky"); + static GraphicsFormat s_ColorFormat = GraphicsFormat.R16G16B16A16_SFloat; RTHandle AllocateGroundIrradianceTable(int index) @@ -160,40 +204,45 @@ void UpdateGlobalConstantBuffer(CommandBuffer cmd, BuiltinSkyParameters builtinP Vector2 expParams = ComputeExponentialInterpolationParams(pbrSky.horizonZenithShift.value); - cmd.SetGlobalFloat( HDShaderIDs._PlanetaryRadius, R); - cmd.SetGlobalFloat( HDShaderIDs._RcpPlanetaryRadius, 1.0f / R); - cmd.SetGlobalFloat( HDShaderIDs._AtmosphericDepth, D); - cmd.SetGlobalFloat( HDShaderIDs._RcpAtmosphericDepth, 1.0f / D); + m_ConstantBuffer._PlanetaryRadius = R; + m_ConstantBuffer._RcpPlanetaryRadius = 1.0f / R; + m_ConstantBuffer._AtmosphericDepth = D; + m_ConstantBuffer._RcpAtmosphericDepth = 1.0f / D; + + m_ConstantBuffer._AtmosphericRadius = R + D; + m_ConstantBuffer._AerosolAnisotropy = pbrSky.aerosolAnisotropy.value; + m_ConstantBuffer._AerosolPhasePartConstant = CornetteShanksPhasePartConstant(pbrSky.aerosolAnisotropy.value); - cmd.SetGlobalFloat( HDShaderIDs._AtmosphericRadius, R + D); - cmd.SetGlobalFloat( HDShaderIDs._AerosolAnisotropy, pbrSky.aerosolAnisotropy.value); - cmd.SetGlobalFloat( HDShaderIDs._AerosolPhasePartConstant, CornetteShanksPhasePartConstant(pbrSky.aerosolAnisotropy.value)); + m_ConstantBuffer._AirDensityFalloff = 1.0f / airH; + m_ConstantBuffer._AirScaleHeight = airH; + m_ConstantBuffer._AerosolDensityFalloff = 1.0f / aerH; + m_ConstantBuffer._AerosolScaleHeight = aerH; - cmd.SetGlobalFloat( HDShaderIDs._AirDensityFalloff, 1.0f / airH); - cmd.SetGlobalFloat( HDShaderIDs._AirScaleHeight, airH); - cmd.SetGlobalFloat( HDShaderIDs._AerosolDensityFalloff, 1.0f / aerH); - cmd.SetGlobalFloat( HDShaderIDs._AerosolScaleHeight, aerH); + m_ConstantBuffer._AirSeaLevelExtinction = pbrSky.GetAirExtinctionCoefficient(); + m_ConstantBuffer._AerosolSeaLevelExtinction = pbrSky.GetAerosolExtinctionCoefficient(); - cmd.SetGlobalVector(HDShaderIDs._AirSeaLevelExtinction, pbrSky.GetAirExtinctionCoefficient()); - cmd.SetGlobalFloat( HDShaderIDs._AerosolSeaLevelExtinction, pbrSky.GetAerosolExtinctionCoefficient()); + m_ConstantBuffer._AirSeaLevelScattering = pbrSky.GetAirScatteringCoefficient(); + m_ConstantBuffer._IntensityMultiplier = iMul; - cmd.SetGlobalVector(HDShaderIDs._AirSeaLevelScattering, pbrSky.GetAirScatteringCoefficient()); - cmd.SetGlobalFloat( HDShaderIDs._IntensityMultiplier, iMul); + m_ConstantBuffer._AerosolSeaLevelScattering = pbrSky.GetAerosolScatteringCoefficient(); + m_ConstantBuffer._ColorSaturation = pbrSky.colorSaturation.value; - cmd.SetGlobalVector(HDShaderIDs._AerosolSeaLevelScattering, pbrSky.GetAerosolScatteringCoefficient()); - cmd.SetGlobalFloat( HDShaderIDs._ColorSaturation, pbrSky.colorSaturation.value); + Vector3 groundAlbedo = new Vector3(pbrSky.groundTint.value.r, pbrSky.groundTint.value.g, pbrSky.groundTint.value.b); + m_ConstantBuffer._GroundAlbedo = groundAlbedo; + m_ConstantBuffer._AlphaSaturation = pbrSky.alphaSaturation.value; - cmd.SetGlobalVector(HDShaderIDs._GroundAlbedo, pbrSky.groundTint.value); - cmd.SetGlobalFloat( HDShaderIDs._AlphaSaturation, pbrSky.alphaSaturation.value); + m_ConstantBuffer._PlanetCenterPosition = pbrSky.GetPlanetCenterPosition(builtinParams.worldSpaceCameraPos); + m_ConstantBuffer._AlphaMultiplier = pbrSky.alphaMultiplier.value; - cmd.SetGlobalVector(HDShaderIDs._PlanetCenterPosition, pbrSky.GetPlanetCenterPosition(builtinParams.worldSpaceCameraPos)); - cmd.SetGlobalFloat( HDShaderIDs._AlphaMultiplier, pbrSky.alphaMultiplier.value); + Vector3 horizonTint = new Vector3(pbrSky.horizonTint.value.r, pbrSky.horizonTint.value.g, pbrSky.horizonTint.value.b); + m_ConstantBuffer._HorizonTint = horizonTint; + m_ConstantBuffer._HorizonZenithShiftPower = expParams.x; - cmd.SetGlobalVector(HDShaderIDs._HorizonTint, pbrSky.horizonTint.value); - cmd.SetGlobalFloat( HDShaderIDs._HorizonZenithShiftPower, expParams.x); + Vector3 zenithTint = new Vector3(pbrSky.zenithTint.value.r, pbrSky.zenithTint.value.g, pbrSky.zenithTint.value.b); + m_ConstantBuffer._ZenithTint = zenithTint; + m_ConstantBuffer._HorizonZenithShiftScale = expParams.y; - cmd.SetGlobalVector(HDShaderIDs._ZenithTint, pbrSky.zenithTint.value); - cmd.SetGlobalFloat( HDShaderIDs._HorizonZenithShiftScale, expParams.y); + ConstantBuffer.PushGlobal(cmd, m_ConstantBuffer, m_ShaderVariablesPhysicallyBasedSkyID); } void PrecomputeTables(CommandBuffer cmd) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs.hlsl index bc68e702d48..a445826aac8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs.hlsl @@ -13,5 +13,36 @@ #define PBRSKYCONFIG_IN_SCATTERED_RADIANCE_TABLE_SIZE_Z (16) #define PBRSKYCONFIG_IN_SCATTERED_RADIANCE_TABLE_SIZE_W (64) +// Generated from UnityEngine.Rendering.HighDefinition.PhysicallyBasedSkyRenderer+ShaderVariablesPhysicallyBasedSky +// PackingRules = Exact +CBUFFER_START(ShaderVariablesPhysicallyBasedSky) + float _PlanetaryRadius; + float _RcpPlanetaryRadius; + float _AtmosphericDepth; + float _RcpAtmosphericDepth; + float _AtmosphericRadius; + float _AerosolAnisotropy; + float _AerosolPhasePartConstant; + float _Unused; + float _AirDensityFalloff; + float _AirScaleHeight; + float _AerosolDensityFalloff; + float _AerosolScaleHeight; + float3 _AirSeaLevelExtinction; + float _AerosolSeaLevelExtinction; + float3 _AirSeaLevelScattering; + float _IntensityMultiplier; + float3 _AerosolSeaLevelScattering; + float _ColorSaturation; + float3 _GroundAlbedo; + float _AlphaSaturation; + float3 _PlanetCenterPosition; + float _AlphaMultiplier; + float3 _HorizonTint; + float _HorizonZenithShiftPower; + float3 _ZenithTint; + float _HorizonZenithShiftScale; +CBUFFER_END + #endif From 264e67f01f17bf9290c526e0df22262799dd9d0b Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Mon, 23 Mar 2020 17:02:58 +0100 Subject: [PATCH 57/92] Warning fix --- .../Runtime/Lighting/LightCookieManager.cs | 2 +- .../Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs index 489c9d44c28..c113acf19eb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs @@ -26,7 +26,7 @@ class LightCookieManager internal const int k_MinCookieSize = 2; readonly Material m_MaterialFilterAreaLights; - MaterialPropertyBlock m_MPBFilterAreaLights; + MaterialPropertyBlock m_MPBFilterAreaLights = new MaterialPropertyBlock(); readonly Material m_CubeToPanoMaterial; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs index 9efd77086cf..c16b3dce0e5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs @@ -212,6 +212,7 @@ void UpdateGlobalConstantBuffer(CommandBuffer cmd, BuiltinSkyParameters builtinP m_ConstantBuffer._AtmosphericRadius = R + D; m_ConstantBuffer._AerosolAnisotropy = pbrSky.aerosolAnisotropy.value; m_ConstantBuffer._AerosolPhasePartConstant = CornetteShanksPhasePartConstant(pbrSky.aerosolAnisotropy.value); + m_ConstantBuffer._Unused = 0.0f; // Warning fix m_ConstantBuffer._AirDensityFalloff = 1.0f / airH; m_ConstantBuffer._AirScaleHeight = airH; From 8cf78631f9e05affeb5a10c18994d44e27001aa7 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 24 Mar 2020 10:52:39 +0100 Subject: [PATCH 58/92] Small fix --- .../Editor/ShaderGenerator/ShaderTypeGeneration.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs index 38aab2df435..fdc8d21651c 100644 --- a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs +++ b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs @@ -1042,7 +1042,7 @@ public bool Generate() arrayInfos[0].elementType != typeof(ShaderGenUInt4) && arrayInfos[0].elementType != typeof(Matrix4x4)) { - Error("Invalid HLSLArray target: '" + field.FieldType + "'" + ", only Vector4 and ShaderGenUInt4 are supported for integer arrays in constant buffers."); + Error("Invalid HLSLArray target: '" + field.FieldType + "'" + ", only Vector4, Matrix4x4 and ShaderGenUInt4 are supported for arrays in constant buffers."); return false; } From 4c761a4590112dfe60123dac8c3a5870970742b4 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 24 Mar 2020 16:16:38 +0100 Subject: [PATCH 59/92] Cleanup of global setup happening before rendering (render graph path or not). --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 70 +++++-------------- .../VolumetricLighting/VolumetricLighting.cs | 17 ++--- .../Runtime/RenderPipeline/HDProfileId.cs | 1 - .../HDRenderPipeline.LightLoop.cs | 3 - .../RenderPipeline/HDRenderPipeline.cs | 47 ++++--------- .../Runtime/Sky/SkyManager.cs | 4 +- 6 files changed, 40 insertions(+), 102 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 3a2c3a864af..c22ab163eac 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -1937,7 +1937,7 @@ void AddBoxVolumeDataAndBound(OrientedBBox obb, LightCategory category, LightFea m_lightList.lightsPerView[viewIndex].bounds.Add(bound); m_lightList.lightsPerView[viewIndex].lightVolumes.Add(volumeData); - } + } internal int GetCurrentShadowCount() { @@ -2594,7 +2594,7 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu m_lightList.lightsPerView[0].lightVolumes.AddRange(m_lightList.lightsPerView[viewIndex].lightVolumes); } - UpdateDataBuffers(); + PushLightDataGlobalParams(cmd); } m_enableBakeShadowMask = m_enableBakeShadowMask && hdCamera.frameSettings.IsEnabled(FrameSettingsField.Shadowmask); @@ -3115,24 +3115,6 @@ void BuildGPULightLists(HDCamera hdCamera, CommandBuffer cmd) PushLightLoopGlobalParams(globalParams, cmd); } - void BindLightDataParameters(HDCamera hdCamera, CommandBuffer cmd) - { - var globalParams = PrepareLightDataGlobalParameters(hdCamera); - PushLightDataGlobalParams(globalParams, cmd); - } - - void UpdateDataBuffers() - { - m_LightLoopLightData.directionalLightData.SetData(m_lightList.directionalLights); - m_LightLoopLightData.lightData.SetData(m_lightList.lights); - m_LightLoopLightData.envLightData.SetData(m_lightList.envLights); - m_LightLoopLightData.decalData.SetData(DecalSystem.m_DecalDatas, 0, 0, Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen)); // don't add more than the size of the buffer - - // These two buffers have been set in Rebuild(). At this point, view 0 contains combined data from all views - m_TileAndClusterData.convexBoundsBuffer.SetData(m_lightList.lightsPerView[0].bounds); - m_TileAndClusterData.lightVolumeDataBuffer.SetData(m_lightList.lightsPerView[0].lightVolumes); - } - HDAdditionalLightData GetHDAdditionalLightData(Light light) { HDAdditionalLightData add = null; @@ -3148,24 +3130,6 @@ HDAdditionalLightData GetHDAdditionalLightData(Light light) return add; } - struct LightDataGlobalParameters - { - public HDCamera hdCamera; - public LightList lightList; - public LightLoopTextureCaches textureCaches; - public LightLoopLightData lightData; - } - - LightDataGlobalParameters PrepareLightDataGlobalParameters(HDCamera hdCamera) - { - LightDataGlobalParameters parameters = new LightDataGlobalParameters(); - parameters.hdCamera = hdCamera; - parameters.lightList = m_lightList; - parameters.textureCaches = m_TextureCaches; - parameters.lightData = m_LightLoopLightData; - return parameters; - } - struct ShadowGlobalParameters { public HDCamera hdCamera; @@ -3246,22 +3210,26 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, H cb._EnableSSRefraction = hdCamera.frameSettings.IsEnabled(FrameSettingsField.Refraction) ? 1u : 0u; } - static void PushLightDataGlobalParams(in LightDataGlobalParameters param, CommandBuffer cmd) + void PushLightDataGlobalParams(CommandBuffer cmd) { - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PushLightDataGlobalParameters))) - { - cmd.SetGlobalTexture(HDShaderIDs._CookieAtlas, param.textureCaches.lightCookieManager.atlasTexture); - cmd.SetGlobalTexture(HDShaderIDs._CookieCubeTextures, param.textureCaches.lightCookieManager.cubeCache); - cmd.SetGlobalTexture(HDShaderIDs._EnvCubemapTextures, param.textureCaches.reflectionProbeCache.GetTexCache()); - cmd.SetGlobalTexture(HDShaderIDs._Env2DTextures, param.textureCaches.reflectionPlanarProbeCache.GetTexCache()); + m_LightLoopLightData.directionalLightData.SetData(m_lightList.directionalLights); + m_LightLoopLightData.lightData.SetData(m_lightList.lights); + m_LightLoopLightData.envLightData.SetData(m_lightList.envLights); + m_LightLoopLightData.decalData.SetData(DecalSystem.m_DecalDatas, 0, 0, Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen)); // don't add more than the size of the buffer - cmd.SetGlobalBuffer(HDShaderIDs._LightDatas, param.lightData.lightData); - cmd.SetGlobalBuffer(HDShaderIDs._EnvLightDatas, param.lightData.envLightData); - cmd.SetGlobalBuffer(HDShaderIDs._DecalDatas, param.lightData.decalData); + // These two buffers have been set in Rebuild(). At this point, view 0 contains combined data from all views + m_TileAndClusterData.convexBoundsBuffer.SetData(m_lightList.lightsPerView[0].bounds); + m_TileAndClusterData.lightVolumeDataBuffer.SetData(m_lightList.lightsPerView[0].lightVolumes); - // Directional lights are made available immediately after PrepareLightsForGPU for the PBR sky. - cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, param.lightData.directionalLightData); - } + cmd.SetGlobalTexture(HDShaderIDs._CookieAtlas, m_TextureCaches.lightCookieManager.atlasTexture); + cmd.SetGlobalTexture(HDShaderIDs._CookieCubeTextures, m_TextureCaches.lightCookieManager.cubeCache); + cmd.SetGlobalTexture(HDShaderIDs._EnvCubemapTextures, m_TextureCaches.reflectionProbeCache.GetTexCache()); + cmd.SetGlobalTexture(HDShaderIDs._Env2DTextures, m_TextureCaches.reflectionPlanarProbeCache.GetTexCache()); + + cmd.SetGlobalBuffer(HDShaderIDs._LightDatas, m_LightLoopLightData.lightData); + cmd.SetGlobalBuffer(HDShaderIDs._EnvLightDatas, m_LightLoopLightData.envLightData); + cmd.SetGlobalBuffer(HDShaderIDs._DecalDatas, m_LightLoopLightData.decalData); + cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, m_LightLoopLightData.directionalLightData); } static void PushShadowGlobalParams(in ShadowGlobalParameters param, CommandBuffer cmd) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 9a168b47e77..61b102b7937 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -481,18 +481,6 @@ void UpdateShaderVariablesGlobalVolumetrics(ref ShaderVariablesGlobal cb, in RTH cb._VBufferRcpInstancedViewCount = 1.0f / hdCamera.viewCount; } - void PushVolumetricLightingGlobalParams(HDCamera hdCamera, CommandBuffer cmd, int frameIndex) - { - if (!Fog.IsVolumetricFogEnabled(hdCamera)) - { - cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, HDUtils.clearTexture3D); - } - else - { - cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, m_LightingBufferHandle); - } - } - DensityVolumeList PrepareVisibleDensityVolumeList(HDCamera hdCamera, CommandBuffer cmd, float time) { DensityVolumeList densityVolumes = new DensityVolumeList(); @@ -823,7 +811,10 @@ static void FilterVolumetricLighting(in VolumetricLightingParameters parameters, void VolumetricLightingPass(HDCamera hdCamera, CommandBuffer cmd, int frameIndex) { if (!Fog.IsVolumetricFogEnabled(hdCamera)) + { + cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, HDUtils.clearTexture3D); return; + } var parameters = PrepareVolumetricLightingParameters(hdCamera, frameIndex); @@ -843,6 +834,8 @@ void VolumetricLightingPass(HDCamera hdCamera, CommandBuffer cmd, int frameIndex // Let's filter out volumetric buffer if (parameters.filterVolume) FilterVolumetricLighting(parameters, m_DensityBufferHandle, m_LightingBufferHandle, cmd); + + cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, m_LightingBufferHandle); } } // class VolumetricLightingModule } // namespace UnityEngine.Rendering.HighDefinition diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs index 098450ea611..07684c83103 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs @@ -115,7 +115,6 @@ internal enum HDProfileId // Profile sampler for prepare light for GPU PrepareLightsForGPU, - PushLightDataGlobalParameters, // Profile sampler for shadow PushShadowGlobalParameters, diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 0481313705a..f7c80313897 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -27,7 +27,6 @@ static void ReadLightingBuffers(LightingBuffers buffers, RenderGraphBuilder buil class BuildGPULightListPassData { - public LightDataGlobalParameters lightDataGlobalParameters; public ShadowGlobalParameters shadowGlobalParameters; public LightLoopGlobalParameters lightLoopGlobalParameters; @@ -45,7 +44,6 @@ void BuildGPULightList(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle { builder.EnableAsyncCompute(hdCamera.frameSettings.BuildLightListRunsAsync()); - passData.lightDataGlobalParameters = PrepareLightDataGlobalParameters(hdCamera); passData.shadowGlobalParameters = PrepareShadowGlobalParameters(hdCamera); passData.lightLoopGlobalParameters = PrepareLightLoopGlobalParameters(hdCamera); passData.buildGPULightListParameters = PrepareBuildGPULightListParameters(hdCamera); @@ -83,7 +81,6 @@ void BuildGPULightList(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle BuildDispatchIndirectArguments(data.buildGPULightListParameters, data.buildGPULightListResources, tileFlagsWritten, context.cmd); // TODO RENDERGRAPH WARNING: Note that the three sets of variables are bound here, but it should be handled differently. - PushLightDataGlobalParams(data.lightDataGlobalParameters, context.cmd); PushShadowGlobalParams(data.shadowGlobalParameters, context.cmd); PushLightLoopGlobalParams(data.lightLoopGlobalParameters, context.cmd); }); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 116757e34bd..fd5b1c669f3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -1016,36 +1016,9 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) hdCamera.UpdateShaderVariablesXRCB(ref m_ShaderVariablesXRCB); ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesXRCB, HDShaderIDs._ShaderVariablesXR); - } - - void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd) - { - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PushGlobalParameters))) - { - PushVolumetricLightingGlobalParams(hdCamera, cmd, m_FrameCount); - - // It will be overridden for transparent pass. - cmd.SetGlobalInt(HDShaderIDs._ColorMaskTransparentVel, (int)UnityEngine.Rendering.ColorWriteMask.All); - - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.MotionVectors)) - { - cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, m_SharedRTManager.GetMotionVectorsBuffer()); - } - else - { - cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, TextureXR.GetBlackTexture()); - } - // Light loop stuff... - if (hdCamera.IsSSREnabled()) - cmd.SetGlobalTexture(HDShaderIDs._SsrLightingTexture, m_SsrLightingTexture); - else - cmd.SetGlobalTexture(HDShaderIDs._SsrLightingTexture, TextureXR.GetClearTexture()); - - - m_SkyManager.SetGlobalSkyData(cmd, hdCamera); - - } + // This one is not in a constant buffer because it's only used as a parameter for some shader's render states. It's not actually used inside shader code. + cmd.SetGlobalInt(HDShaderIDs._ColorMaskTransparentVel, (int)ColorWriteMask.All); } void CopyDepthBufferIfNeeded(HDCamera hdCamera, CommandBuffer cmd) @@ -1951,8 +1924,6 @@ AOVRequestData aovRequest bool enableBakeShadowMask = PrepareLightsForGPU(cmd, hdCamera, cullingResults, hdProbeCullingResults, densityVolumes, m_CurrentDebugDisplaySettings, aovRequest); UpdateShaderVariablesGlobalCB(hdCamera, cmd); - // Let's bind as soon as possible the light data - BindLightDataParameters(hdCamera, cmd); // Configure all the keywords ConfigureKeywords(enableBakeShadowMask, hdCamera, cmd); @@ -1964,7 +1935,6 @@ AOVRequestData aovRequest else cmd.SetGlobalTexture(HDShaderIDs._SkyTexture, CoreUtils.magentaCubeTextureArray); - PushGlobalParams(hdCamera, cmd); VFXManager.ProcessCameraCommand(camera, cmd); if (GL.wireframe) @@ -2053,9 +2023,14 @@ AOVRequestData aovRequest RenderCameraMotionVectors(cullingResults, hdCamera, renderContext, cmd); } + + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.MotionVectors)) + cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, m_SharedRTManager.GetMotionVectorsBuffer()); + else + cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, TextureXR.GetBlackTexture()); + #if UNITY_EDITOR - var showGizmos = camera.cameraType == CameraType.SceneView || - (camera.targetTexture == null && camera.cameraType == CameraType.Game); + var showGizmos = camera.cameraType == CameraType.SceneView || (camera.targetTexture == null && camera.cameraType == CameraType.Game); #endif RenderTransparencyOverdraw(cullingResults, hdCamera, renderContext, cmd); @@ -3838,7 +3813,10 @@ static void RenderSSR( in RenderSSRParameters parameters, void RenderSSR(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext) { if (!hdCamera.IsSSREnabled()) + { + cmd.SetGlobalTexture(HDShaderIDs._SsrLightingTexture, TextureXR.GetClearTexture()); return; + } var settings = hdCamera.volumeStack.GetComponent(); bool usesRaytracedReflections = hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value; @@ -3865,6 +3843,7 @@ void RenderSSR(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext ren } } + cmd.SetGlobalTexture(HDShaderIDs._SsrLightingTexture, m_SsrLightingTexture); PushFullScreenDebugTexture(hdCamera, cmd, m_SsrLightingTexture, FullScreenDebugMode.ScreenSpaceReflections); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs index 8c364fa3124..eb016c8def4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs @@ -230,7 +230,7 @@ public void UpdateCurrentSkySettings(HDCamera hdCamera) hdCamera.UpdateCurrentSky(this); } - public void SetGlobalSkyData(CommandBuffer cmd, HDCamera hdCamera) + void SetGlobalSkyData(CommandBuffer cmd, HDCamera hdCamera) { if (IsCachedContextValid(hdCamera.lightingSky)) { @@ -793,6 +793,8 @@ public void UpdateEnvironment(HDCamera hdCamera, ScriptableRenderContext renderC m_UpdateRequired = false; + SetGlobalSkyData(cmd, hdCamera); + var reflectionTexture = GetReflectionTexture(hdCamera.lightingSky); cmd.SetGlobalTexture(HDShaderIDs._SkyTexture, reflectionTexture); } From 6b6e5882662c44dfbcce1c969e476905b1c4a043 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 24 Mar 2020 18:20:03 +0100 Subject: [PATCH 60/92] Post merge fix --- .../Lighting/Shadow/ScreenSpaceShadowManager.cs | 10 +--------- .../SubsurfaceScatteringManager.cs | 2 -- .../Raytracing/HDRaytracingAmbientOcclusion.cs | 2 -- .../Raytracing/HDRaytracingIndirectDiffuse.cs | 6 ------ .../Raytracing/HDRaytracingReflection.cs | 6 ------ .../Runtime/ShaderLibrary/ShaderVariablesGlobal.cs | 5 ++--- 6 files changed, 3 insertions(+), 28 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs index 000aa82df88..8aa98999558 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs @@ -326,10 +326,6 @@ void RenderDirectionalLightScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamer // Inject the ray-tracing sampling data m_BlueNoise.BindDitheredRNGData8SPP(cmd); - // Compute the current frame index - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); - // Inject the ray generation data RayTracingSettings rayTracingSettings = hdCamera.volumeStack.GetComponent(); cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rayTracingSettings.rayBias.value); @@ -540,8 +536,6 @@ void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera cmd.SetComputeMatrixParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingAreaWorldToLocal, m_WorldToLocalArea); cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingTargetAreaLight, lightIndex); cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, additionalLightData.numRayTracingSamples); - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); // Bind the input buffers cmd.SetComputeTextureParam(m_ScreenSpaceShadowsCS, m_AreaRaytracingAreaShadowPrepassKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); @@ -791,8 +785,6 @@ void RenderPunctualScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera cmd.SetGlobalInt(HDShaderIDs._RaytracingSampleIndex, sampleIdx); cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, additionalLightData.numRayTracingSamples); cmd.SetComputeFloatParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingLightRadius, additionalLightData.shapeRadius); - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); // If this is a spot light, inject the spot angle in radians if (lightData.lightType == GPULightType.Spot) @@ -844,7 +836,7 @@ void RenderPunctualScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera RTHandle shadowHistoryDistanceArray = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RaytracedShadowDistanceValidity) ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RaytracedShadowDistanceValidity, ShadowHistoryDistanceBufferAllocatorFunction, 1); - // We need to set the history as invalid if the light has moved (rotated or translated), + // We need to set the history as invalid if the light has moved (rotated or translated), float historyValidity = 1.0f; if (additionalLightData.previousTransform != additionalLightData.transform.localToWorldMatrix || !hdCamera.ValidShadowHistory(additionalLightData, lightData.screenSpaceShadowIndex, lightData.lightType)) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index b68f3babc30..8c0d1f86770 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -345,8 +345,6 @@ void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle c cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rayTracingSettings.rayBias.value); cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, settings.sampleCount.value); cmd.SetGlobalInt(HDShaderIDs._RaytracingSampleIndex, sampleIndex); - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); // Bind the textures for ray generation cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._DepthTexture, sharedRTManager.GetDepthStencilBuffer()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs index 4e06ff1df40..c295d1ae076 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs @@ -91,8 +91,6 @@ public void RenderAO(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputTextur cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, aoSettings.rayLength.value); cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, aoSettings.sampleCount.value); int frameIndex = m_RenderPipeline.RayTracingFrameIndex(hdCamera); - cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); - cmd.SetGlobalInt(HDShaderIDs._RayCountEnabled, rayCountManager.RayCountIsEnabled()); // Set the data for the ray generation cmd.SetRayTracingTextureParam(aoShader, HDShaderIDs._DepthTexture, m_RenderPipeline.sharedRTManager.GetDepthStencilBuffer()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs index 575ed25308e..442034e5409 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs @@ -183,10 +183,6 @@ void RenderIndirectDiffusePerformance(HDCamera hdCamera, CommandBuffer cmd, Scri // Bind all the required scalars cmd.SetGlobalFloat(HDShaderIDs._RaytracingIntensityClamp, settings.clampValue.value); - // Bind the sampling data - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); - // Bind the output buffers cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._RaytracingDirectionBuffer, directionBuffer); @@ -271,8 +267,6 @@ void BindRayTracedIndirectDiffuseData(CommandBuffer cmd, HDCamera hdCamera cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rtSettings.rayBias.value); cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, settings.rayLength.value); cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, settings.sampleCount.value); - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); // Set the data for the ray generation cmd.SetRayTracingTextureParam(indirectDiffuseShader, HDShaderIDs._IndirectDiffuseTextureRW, outputLightingBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs index bb759c7de6f..8fd85ad43a2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs @@ -67,8 +67,6 @@ void BindRayTracedReflectionData(CommandBuffer cmd, HDCamera hdCamera, RayTracin cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rtSettings.rayBias.value); cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, settings.rayLength.value); cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, settings.sampleCount.value); - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); // Inject the ray-tracing sampling data blueNoise.BindDitheredRNGData8SPP(cmd); @@ -203,10 +201,6 @@ void RenderReflectionsPerformance(HDCamera hdCamera, CommandBuffer cmd, RTHandle cmd.SetGlobalFloat(HDShaderIDs._RaytracingReflectionMinSmoothness, settings.minSmoothness.value); cmd.SetGlobalInt(HDShaderIDs._RaytracingIncludeSky, settings.reflectSky.value ? 1 : 0); - // Bind the sampling data - int frameIndex = RayTracingFrameIndex(hdCamera); - cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex); - // Bind the output buffers cmd.SetComputeTextureParam(reflectionShaderCS, currentKernel, HDShaderIDs._RaytracingDirectionBuffer, intermediateBuffer1); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index 5508038960c..c08749a6590 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -222,10 +222,9 @@ unsafe struct ShaderVariablesGlobal public Vector4 _CoarseStencilBufferSize; - // Uniform variables that defines if we should be using the raytraced indirect diffuse - public int _RaytracedIndirectDiffuse; + public int _RaytracedIndirectDiffuse; // Uniform variables that defines if we should be using the raytraced indirect diffuse public int _UseRayTracedReflections; - public int _RaytracingFrameIndex; + public int _RaytracingFrameIndex; // Index of the current frame [0, 7] public float _Pad7; } } From 33f3c7297d3fe7f511fcbe6aed1eaf0b7477615e Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 25 Mar 2020 10:21:48 +0100 Subject: [PATCH 61/92] Added global constant buffer hlsl generation. --- .../Editor/ShaderGenerator/ShaderTypeGeneration.cs | 5 ++++- .../Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs | 8 +++++++- .../Runtime/ShaderLibrary/ShaderVariablesGlobal.cs | 8 +++++++- .../Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl | 2 +- .../Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl | 3 +-- 5 files changed, 20 insertions(+), 6 deletions(-) diff --git a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs index fdc8d21651c..4c62f7bab77 100644 --- a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs +++ b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs @@ -410,7 +410,10 @@ public string EmitTypeDecl() if (attr.generateCBuffer) { - shaderText += "CBUFFER_START(" + type.Name + ")\n"; + if (attr.constantRegister != -1) + shaderText += "GLOBAL_CBUFFER_START(" + type.Name + ", b" + attr.constantRegister + ")\n"; + else + shaderText += "CBUFFER_START(" + type.Name + ")\n"; } else if (!attr.omitStructDeclaration) { diff --git a/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs b/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs index d27b6f8c625..27c2445529a 100644 --- a/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs +++ b/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs @@ -98,6 +98,10 @@ public class GenerateHLSL : System.Attribute /// Generate constant buffer declaration or not. /// public bool generateCBuffer; + /// + /// If specified, when generating a constant buffer, use this explicit register. + /// + public int constantRegister; /// /// GenerateHLSL attribute constructor. @@ -109,7 +113,8 @@ public class GenerateHLSL : System.Attribute /// Start value of debug defines. /// Omit structure declaration. /// Contains packed fields. - public GenerateHLSL(PackingRules rules = PackingRules.Exact, bool needAccessors = true, bool needSetters = false, bool needParamDebug = false, int paramDefinesStart = 1, bool omitStructDeclaration = false, bool containsPackedFields = false, bool generateCBuffer = false) + public GenerateHLSL(PackingRules rules = PackingRules.Exact, bool needAccessors = true, bool needSetters = false, bool needParamDebug = false, int paramDefinesStart = 1, + bool omitStructDeclaration = false, bool containsPackedFields = false, bool generateCBuffer = false, int constantRegister = -1) { packingRules = rules; this.needAccessors = needAccessors; @@ -119,6 +124,7 @@ public GenerateHLSL(PackingRules rules = PackingRules.Exact, bool needAccessors this.omitStructDeclaration = omitStructDeclaration; this.containsPackedFields = containsPackedFields; this.generateCBuffer = generateCBuffer; + this.constantRegister = constantRegister; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index c08749a6590..c212e914b02 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -1,5 +1,11 @@ namespace UnityEngine.Rendering.HighDefinition { + // Global Constant Buffers - b registers. Unity supports a maximum of 16 global constant buffers. + enum ConstantRegister + { + Global = 0, + } + // We need to keep the number of different constant buffers low. // Indeed, those are bound for every single drawcall so if we split things in various CB (lightloop, SSS, Fog, etc) // We multiply the number of CB we have to bind per drawcall. @@ -15,7 +21,7 @@ namespace UnityEngine.Rendering.HighDefinition // - Base element size for array should be 4 components of 4 bytes (Vector4 or Vector4Int basically) otherwise the array will be interlaced with padding on shader side. // Try to keep data grouped by access and rendering system as much as possible (fog params or light params together for example). // => Don't move a float parameter away from where it belongs for filling a hole. Add padding in this case. - [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + [GenerateHLSL(needAccessors = false, generateCBuffer = true, constantRegister = (int)ConstantRegister.Global)] unsafe struct ShaderVariablesGlobal { public const int defaultLightLayers = 0xFF; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 1e8ad26f53e..4b69b687da5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -12,7 +12,7 @@ // Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesGlobal // PackingRules = Exact -CBUFFER_START(ShaderVariablesGlobal) +GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) float4x4 _ViewMatrix; float4x4 _InvViewMatrix; float4x4 _ProjMatrix; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl index aa0d0c57aab..22b13302de2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl @@ -3,7 +3,6 @@ // Global Constant Buffers - b registers. Unity supports a maximum of 16 global constant buffers. // Common constant buffers -#define UNITY_GLOBAL_CBUFFER_REGISTER b0 #define UNITY_XR_VIEW_CONSTANTS_CBUFFER_REGISTER b1 #define UNITY_PHYSICALLY_BASED_SKY_CBUFFER_REGISTER b2 // Ray tracing specific constant buffers @@ -16,4 +15,4 @@ #define RAY_TRACING_LIGHT_DATA_REGISTER t3 #define RAY_TRACING_ENV_LIGHT_DATA_REGISTER t4 -#endif // UNITY_SHADER_VARIABLES_GLOBAL_INCLUDED \ No newline at end of file +#endif // UNITY_SHADER_VARIABLES_GLOBAL_INCLUDED From 5499ad1bccc55f9dde0b1a2a358d8e7ba6a43fb7 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 25 Mar 2020 12:05:49 +0100 Subject: [PATCH 62/92] Post merge fix --- .../ScreenSpaceLighting/AmbientOcclusion.cs | 18 +++++++----------- .../ShaderLibrary/ShaderVariablesGlobal.cs | 2 ++ .../ShaderLibrary/ShaderVariablesGlobal.hlsl | 3 --- .../Runtime/ShaderLibrary/ShaderVariablesXR.cs | 2 +- .../ShaderLibrary/ShaderVariablesXR.cs.hlsl | 2 +- .../PhysicallyBasedSkyRenderer.cs | 2 +- .../PhysicallyBasedSkyRenderer.cs.hlsl | 2 +- 7 files changed, 13 insertions(+), 18 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs index c7c56b35f1b..1b9d37179d1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs @@ -467,20 +467,21 @@ static void DenoiseAO( in RenderAOParameters parameters, if (parameters.temporalAccumulation || parameters.fullResolution) { - ConstantBuffer.Set(cmd, parameters.denoiseAOCS, HDShaderIDs._ShaderVariablesAmbientOcclusion); + var blurCS = parameters.spatialDenoiseAOCS; + ConstantBuffer.Set(cmd, blurCS, HDShaderIDs._ShaderVariablesAmbientOcclusion); // Spatial - cmd.SetComputeTextureParam(parameters.denoiseAOCS, parameters.denoiseKernelSpatial, HDShaderIDs._AOPackedData, packedDataTex); + cmd.SetComputeTextureParam(blurCS, parameters.denoiseKernelSpatial, HDShaderIDs._AOPackedData, packedDataTex); if (parameters.temporalAccumulation) { - cmd.SetComputeTextureParam(parameters.denoiseAOCS, parameters.denoiseKernelSpatial, HDShaderIDs._AOPackedBlurred, packedDataBlurredTex); + cmd.SetComputeTextureParam(blurCS, parameters.denoiseKernelSpatial, HDShaderIDs._AOPackedBlurred, packedDataBlurredTex); } else { - cmd.SetComputeTextureParam(parameters.denoiseAOCS, parameters.denoiseKernelSpatial, HDShaderIDs._OcclusionTexture, aoOutputTex); + cmd.SetComputeTextureParam(blurCS, parameters.denoiseKernelSpatial, HDShaderIDs._OcclusionTexture, aoOutputTex); } - cmd.DispatchCompute(parameters.denoiseAOCS, parameters.denoiseKernelSpatial, threadGroupX, threadGroupY, parameters.viewCount); + cmd.DispatchCompute(blurCS, parameters.denoiseKernelSpatial, threadGroupX, threadGroupY, parameters.viewCount); } if (parameters.temporalAccumulation) @@ -493,12 +494,7 @@ static void DenoiseAO( in RenderAOParameters parameters, } var blurCS = parameters.temporalDenoiseAOCS; - cmd.SetComputeVectorParam(blurCS, HDShaderIDs._AOParams1, parameters.aoParams1); - cmd.SetComputeVectorParam(blurCS, HDShaderIDs._AOParams2, parameters.aoParams2); - cmd.SetComputeVectorParam(blurCS, HDShaderIDs._AOParams3, parameters.aoParams3); - cmd.SetComputeVectorParam(blurCS, HDShaderIDs._AOParams4, parameters.aoParams4); - cmd.SetComputeVectorParam(blurCS, HDShaderIDs._AOBufferSize, parameters.aoBufferInfo); - + ConstantBuffer.Set(cmd, blurCS, HDShaderIDs._ShaderVariablesAmbientOcclusion); // Temporal cmd.SetComputeTextureParam(blurCS, parameters.denoiseKernelTemporal, HDShaderIDs._AOPackedData, packedDataTex); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index c212e914b02..3623b58075b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -4,6 +4,8 @@ namespace UnityEngine.Rendering.HighDefinition enum ConstantRegister { Global = 0, + XR = 1, + PBRSky = 2, } // We need to keep the number of different constant buffers low. diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl index 22b13302de2..9cf4cb6174b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl @@ -2,9 +2,6 @@ #define UNITY_SHADER_VARIABLES_GLOBAL_INCLUDED // Global Constant Buffers - b registers. Unity supports a maximum of 16 global constant buffers. - // Common constant buffers -#define UNITY_XR_VIEW_CONSTANTS_CBUFFER_REGISTER b1 -#define UNITY_PHYSICALLY_BASED_SKY_CBUFFER_REGISTER b2 // Ray tracing specific constant buffers #define UNITY_RAY_TRACING_GLOBAL_CBUFFER_REGISTER b3 #define UNITY_RAY_TRACING_LIGHT_LOOP_CBUFFER_REGISTER b4 diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs index c3cbe289eb2..6898a2fbcc3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs @@ -1,7 +1,7 @@ namespace UnityEngine.Rendering.HighDefinition { // Custom generated by HDRP, not from Unity Engine (passed in via HDCamera) - [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + [GenerateHLSL(needAccessors = false, generateCBuffer = true, constantRegister = (int)ConstantRegister.XR)] unsafe struct ShaderVariablesXR { [HLSLArray((int)ShaderOptions.XrMaxViews, typeof(Matrix4x4))] diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl index 90370efba08..7f27e8fe898 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesXR.cs.hlsl @@ -6,7 +6,7 @@ #define SHADERVARIABLESXR_CS_HLSL // Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesXR // PackingRules = Exact -CBUFFER_START(ShaderVariablesXR) +GLOBAL_CBUFFER_START(ShaderVariablesXR, b1) float4x4 _XRViewMatrix[2]; float4x4 _XRInvViewMatrix[2]; float4x4 _XRProjMatrix[2]; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs index c16b3dce0e5..43e7593b6e5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs @@ -18,7 +18,7 @@ public enum PbrSkyConfig InScatteredRadianceTableSizeW = 64, // , } - [GenerateHLSL(needAccessors = false, generateCBuffer = true)] + [GenerateHLSL(needAccessors = false, generateCBuffer = true, constantRegister = (int)ConstantRegister.PBRSky)] unsafe struct ShaderVariablesPhysicallyBasedSky { // All the distance-related entries use SI units (meter, 1/meter, etc). diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs.hlsl index a445826aac8..69644bc7a6a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs.hlsl @@ -15,7 +15,7 @@ // Generated from UnityEngine.Rendering.HighDefinition.PhysicallyBasedSkyRenderer+ShaderVariablesPhysicallyBasedSky // PackingRules = Exact -CBUFFER_START(ShaderVariablesPhysicallyBasedSky) +GLOBAL_CBUFFER_START(ShaderVariablesPhysicallyBasedSky, b2) float _PlanetaryRadius; float _RcpPlanetaryRadius; float _AtmosphericDepth; From 444f813d187e819be306fca50661f4ed6daf8957 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 25 Mar 2020 17:18:38 +0100 Subject: [PATCH 63/92] Converted raytracing lightloop variables to constant buffer. --- .../RenderPipeline/HDRenderPipeline.cs | 17 +++++++++---- .../RenderPipeline/HDStringConstants.cs | 8 ++----- .../RenderPipeline/PathTracing/PathTracing.cs | 5 ---- .../Raytracing/HDRaytracingLightCluster.cs | 24 ++++++------------- .../Raytracing/HDRaytracingManager.cs | 16 +++++++++++++ .../HDRaytracingRecursiveRenderer.cs | 5 ---- .../Shaders/RaytracingLightCluster.compute | 20 +++++++--------- .../ShaderVariablesRaytracingLightLoop.cs | 13 ++++++++++ ...ShaderVariablesRaytracingLightLoop.cs.hlsl | 19 +++++++++++++++ ...rVariablesRaytracingLightLoop.cs.hlsl.meta | 9 +++++++ ...ShaderVariablesRaytracingLightLoop.cs.meta | 11 +++++++++ .../ShaderVariablesRaytracingLightLoop.hlsl | 15 +++--------- .../ShaderLibrary/ShaderVariablesGlobal.cs | 1 + .../ShaderLibrary/ShaderVariablesGlobal.hlsl | 1 - 14 files changed, 103 insertions(+), 61 deletions(-) create mode 100644 com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs create mode 100644 com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.hlsl create mode 100644 com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.hlsl.meta create mode 100644 com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.meta diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 2a0f9e8bec3..7699186a440 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -966,6 +966,15 @@ void Resize(HDCamera hdCamera) } } + void UpdateGlobalConstantBuffers(HDCamera hdCamera, CommandBuffer cmd) + { + UpdateShaderVariablesGlobalCB(hdCamera, cmd); + UpdateShaderVariablesXRCB(hdCamera, cmd); + + // This one is not in a constant buffer because it's only used as a parameter for some shader's render states. It's not actually used inside shader code. + cmd.SetGlobalInt(HDShaderIDs._ColorMaskTransparentVel, (int)ColorWriteMask.All); + } + void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) { hdCamera.UpdateShaderVariablesGlobalCB(ref m_ShaderVariablesGlobalCB, m_FrameCount); @@ -1013,12 +1022,12 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) } ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); + } + void UpdateShaderVariablesXRCB(HDCamera hdCamera, CommandBuffer cmd) + { hdCamera.UpdateShaderVariablesXRCB(ref m_ShaderVariablesXRCB); ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesXRCB, HDShaderIDs._ShaderVariablesXR); - - // This one is not in a constant buffer because it's only used as a parameter for some shader's render states. It's not actually used inside shader code. - cmd.SetGlobalInt(HDShaderIDs._ColorMaskTransparentVel, (int)ColorWriteMask.All); } void CopyDepthBufferIfNeeded(HDCamera hdCamera, CommandBuffer cmd) @@ -1923,7 +1932,7 @@ AOVRequestData aovRequest // So the first thing to do is to go through all the light: PrepareLightsForGPU bool enableBakeShadowMask = PrepareLightsForGPU(cmd, hdCamera, cullingResults, hdProbeCullingResults, densityVolumes, m_CurrentDebugDisplaySettings, aovRequest); - UpdateShaderVariablesGlobalCB(hdCamera, cmd); + UpdateGlobalConstantBuffers(hdCamera, cmd); // Configure all the keywords ConfigureKeywords(enableBakeShadowMask, hdCamera, cmd); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 8e42eb4aa92..3b2ed2e22ac 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -253,6 +253,7 @@ static class HDShaderIDs public static readonly int _ShaderVariablesXR = Shader.PropertyToID("ShaderVariablesXR"); public static readonly int _ShaderVariablesVolumetric = Shader.PropertyToID("ShaderVariablesVolumetric"); public static readonly int _ShaderVariablesLightList = Shader.PropertyToID("ShaderVariablesLightList"); + public static readonly int _ShaderVariablesRaytracingLightLoop = Shader.PropertyToID("ShaderVariablesRaytracingLightLoop"); public static readonly int _ShaderVariablesDebugDisplay = Shader.PropertyToID("ShaderVariablesDebugDisplay"); public static readonly int _SSSBufferTexture = Shader.PropertyToID("_SSSBufferTexture"); @@ -422,15 +423,10 @@ static class HDShaderIDs public static readonly string _RaytracingAccelerationStructureName = "_RaytracingAccelerationStructure"; // Light Cluster - public static readonly int _MinClusterPos = Shader.PropertyToID("_MinClusterPos"); - public static readonly int _MaxClusterPos = Shader.PropertyToID("_MaxClusterPos"); - public static readonly int _LightPerCellCount = Shader.PropertyToID("_LightPerCellCount"); public static readonly int _LightDatasRT = Shader.PropertyToID("_LightDatasRT"); public static readonly int _EnvLightDatasRT = Shader.PropertyToID("_EnvLightDatasRT"); - public static readonly int _PunctualLightCountRT = Shader.PropertyToID("_PunctualLightCountRT"); - public static readonly int _AreaLightCountRT = Shader.PropertyToID("_AreaLightCountRT"); - public static readonly int _EnvLightCountRT = Shader.PropertyToID("_EnvLightCountRT"); public static readonly int _RaytracingLightCluster = Shader.PropertyToID("_RaytracingLightCluster"); + public static readonly int _RaytracingLightClusterRW = Shader.PropertyToID("_RaytracingLightClusterRW"); // Denoising public static readonly int _HistoryBuffer = Shader.PropertyToID("_HistoryBuffer"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs index d30b4c852a7..5cfdadfcc3f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs @@ -261,11 +261,6 @@ void RenderPathTracing(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputText // LightLoop data cmd.SetGlobalBuffer(HDShaderIDs._RaytracingLightCluster, lightCluster.GetCluster()); cmd.SetGlobalBuffer(HDShaderIDs._LightDatasRT, lightCluster.GetLightDatas()); - cmd.SetGlobalVector(HDShaderIDs._MinClusterPos, lightCluster.GetMinClusterPos()); - cmd.SetGlobalVector(HDShaderIDs._MaxClusterPos, lightCluster.GetMaxClusterPos()); - cmd.SetGlobalInt(HDShaderIDs._LightPerCellCount, lightClusterSettings.maxNumLightsPercell.value); - cmd.SetGlobalInt(HDShaderIDs._PunctualLightCountRT, lightCluster.GetPunctualLightCount()); - cmd.SetGlobalInt(HDShaderIDs._AreaLightCountRT, lightCluster.GetAreaLightCount()); // Set the data for the ray miss cmd.SetRayTracingIntParam(pathTracingShader, HDShaderIDs._RaytracingCameraSkyEnabled, m_CameraSkyEnabled ? 1 : 0); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs index 282a3eb98ac..469f6445847 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs @@ -200,7 +200,7 @@ void ResizeVolumeBuffer(int numLights) void ResizeLightDataBuffer(int numLights) { - // Release the previous buffer + // Release the previous buffer if (m_LightDataGPUArray != null) { // If it is not null and it has already the right size, we are pretty much done @@ -411,11 +411,8 @@ void BuildLightCluster(HDCamera hdCamera, CommandBuffer cmd) int lightClusterKernel = lightClusterCS.FindKernel(m_LightClusterKernelName); // Inject all the parameters - cmd.SetComputeBufferParam(lightClusterCS, lightClusterKernel, HDShaderIDs._RaytracingLightCluster, m_LightCluster); - cmd.SetComputeVectorParam(lightClusterCS, HDShaderIDs._MinClusterPos, minClusterPos); - cmd.SetComputeVectorParam(lightClusterCS, HDShaderIDs._MaxClusterPos, maxClusterPos); + cmd.SetComputeBufferParam(lightClusterCS, lightClusterKernel, HDShaderIDs._RaytracingLightClusterRW, m_LightCluster); cmd.SetComputeVectorParam(lightClusterCS, _ClusterCellSize, clusterCellSize); - cmd.SetComputeFloatParam(lightClusterCS, HDShaderIDs._LightPerCellCount, HDShadowUtils.Asfloat(numLightsPerCell)); cmd.SetComputeBufferParam(lightClusterCS, lightClusterKernel, _LightVolumes, m_LightVolumeGPUArray); cmd.SetComputeFloatParam(lightClusterCS, _LightVolumeCount, HDShadowUtils.Asfloat(totalLightCount)); @@ -724,10 +721,7 @@ public void EvaluateClusterDebugView(CommandBuffer cmd, HDCamera hdCamera) // Inject all the parameters to the debug compute cmd.SetComputeBufferParam(lightClusterDebugCS, m_LightClusterDebugKernel, HDShaderIDs._RaytracingLightCluster, m_LightCluster); - cmd.SetComputeVectorParam(lightClusterDebugCS, HDShaderIDs._MinClusterPos, minClusterPos); - cmd.SetComputeVectorParam(lightClusterDebugCS, HDShaderIDs._MaxClusterPos, maxClusterPos); cmd.SetComputeVectorParam(lightClusterDebugCS, _ClusterCellSize, clusterCellSize); - cmd.SetComputeIntParam(lightClusterDebugCS, HDShaderIDs._LightPerCellCount, numLightsPerCell); cmd.SetComputeTextureParam(lightClusterDebugCS, m_LightClusterDebugKernel, HDShaderIDs._CameraDepthTexture, m_RenderPipeline.sharedRTManager.GetDepthStencilBuffer()); // Target output texture @@ -746,10 +740,7 @@ public void EvaluateClusterDebugView(CommandBuffer cmd, HDCamera hdCamera) // Bind the parameters m_DebugMaterialProperties.SetBuffer(HDShaderIDs._RaytracingLightCluster, m_LightCluster); - m_DebugMaterialProperties.SetVector(HDShaderIDs._MinClusterPos, minClusterPos); - m_DebugMaterialProperties.SetVector(HDShaderIDs._MaxClusterPos, maxClusterPos); m_DebugMaterialProperties.SetVector(_ClusterCellSize, clusterCellSize); - m_DebugMaterialProperties.SetInt(HDShaderIDs._LightPerCellCount, numLightsPerCell); m_DebugMaterialProperties.SetTexture(HDShaderIDs._CameraDepthTexture, m_RenderPipeline.sharedRTManager.GetDepthTexture()); // Draw the faces @@ -804,6 +795,11 @@ public int GetEnvLightCount() return envLightCount; } + public int GetLightPerCellCount() + { + return numLightsPerCell; + } + void InvalidateCluster() { // Invalidate the cluster's bounds so that we never access the buffer @@ -860,12 +856,6 @@ public void BindLightClusterData(CommandBuffer cmd) cmd.SetGlobalBuffer(HDShaderIDs._RaytracingLightCluster, GetCluster()); cmd.SetGlobalBuffer(HDShaderIDs._LightDatasRT, GetLightDatas()); cmd.SetGlobalBuffer(HDShaderIDs._EnvLightDatasRT, GetEnvLightDatas()); - cmd.SetGlobalVector(HDShaderIDs._MinClusterPos, GetMinClusterPos()); - cmd.SetGlobalVector(HDShaderIDs._MaxClusterPos, GetMaxClusterPos()); - cmd.SetGlobalInt(HDShaderIDs._LightPerCellCount, numLightsPerCell); - cmd.SetGlobalInt(HDShaderIDs._PunctualLightCountRT, GetPunctualLightCount()); - cmd.SetGlobalInt(HDShaderIDs._AreaLightCountRT, GetAreaLightCount()); - cmd.SetGlobalInt(HDShaderIDs._EnvLightCountRT, GetEnvLightCount()); } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs index 6d9593121c2..fd9a6766829 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs @@ -105,6 +105,8 @@ public partial class HDRenderPipeline RTHandle m_RayTracingIntermediateBufferRGBA2; RTHandle m_RayTracingIntermediateBufferRGBA3; + ShaderVariablesRaytracingLightLoop m_ShaderVariablesRaytracingLightLoopCB = new ShaderVariablesRaytracingLightLoop(); + internal RTHandle GetRayTracingBuffer(InternalRayTracingBuffers bufferID) { switch (bufferID) @@ -574,9 +576,23 @@ internal void BuildRayTracingLightCluster(CommandBuffer cmd, HDCamera hdCamera) { m_RayTracingLightCluster.EvaluateLightClusters(cmd, hdCamera, m_RayTracingLights); m_ValidRayTracingCluster = true; + + UpdateShaderVariablesRaytracingLightLoopCB(hdCamera, cmd); } } + void UpdateShaderVariablesRaytracingLightLoopCB(HDCamera hdCamera, CommandBuffer cmd) + { + m_ShaderVariablesRaytracingLightLoopCB._MinClusterPos = m_RayTracingLightCluster.GetMinClusterPos(); + m_ShaderVariablesRaytracingLightLoopCB._LightPerCellCount = (uint)m_RayTracingLightCluster.GetLightPerCellCount(); + m_ShaderVariablesRaytracingLightLoopCB._MaxClusterPos = m_RayTracingLightCluster.GetMaxClusterPos(); + m_ShaderVariablesRaytracingLightLoopCB._PunctualLightCountRT = (uint)m_RayTracingLightCluster.GetPunctualLightCount(); + m_ShaderVariablesRaytracingLightLoopCB._AreaLightCountRT = (uint)m_RayTracingLightCluster.GetAreaLightCount(); + m_ShaderVariablesRaytracingLightLoopCB._EnvLightCountRT = (uint)m_RayTracingLightCluster.GetEnvLightCount(); + + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRaytracingLightLoopCB, HDShaderIDs._ShaderVariablesRaytracingLightLoop); + } + internal RayTracingAccelerationStructure RequestAccelerationStructure() { if (m_ValidRayTracingState) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs index ad26db051a4..d891bdf6c08 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs @@ -141,11 +141,6 @@ void RaytracingRecursiveRender(HDCamera hdCamera, CommandBuffer cmd, ScriptableR // LightLoop data cmd.SetGlobalBuffer(HDShaderIDs._RaytracingLightCluster, lightCluster.GetCluster()); cmd.SetGlobalBuffer(HDShaderIDs._LightDatasRT, lightCluster.GetLightDatas()); - cmd.SetGlobalVector(HDShaderIDs._MinClusterPos, lightCluster.GetMinClusterPos()); - cmd.SetGlobalVector(HDShaderIDs._MaxClusterPos, lightCluster.GetMaxClusterPos()); - cmd.SetGlobalInt(HDShaderIDs._LightPerCellCount, lightClusterSettings.maxNumLightsPercell.value); - cmd.SetGlobalInt(HDShaderIDs._PunctualLightCountRT, lightCluster.GetPunctualLightCount()); - cmd.SetGlobalInt(HDShaderIDs._AreaLightCountRT, lightCluster.GetAreaLightCount()); // Note: Just in case, we rebind the directional light data (in case they were not) cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, m_LightLoopLightData.directionalLightData); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightCluster.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightCluster.compute index e1529dabe20..a1a1bf1e5c2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightCluster.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightCluster.compute @@ -5,8 +5,9 @@ // SRP & HDRP includes #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition\Runtime\ShaderLibrary\ShaderVariables.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition\Runtime\RenderPipeline\Raytracing/HDRaytracingLightCluster.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.hlsl" #define CLUSTER_GROUP_SIZE 8 @@ -15,11 +16,8 @@ StructuredBuffer _LightVolumes; uint _LightVolumeCount; // The target data that this computer shader must fill -RWStructuredBuffer _RaytracingLightCluster; -float3 _MinClusterPos; -float3 _MaxClusterPos; +RWStructuredBuffer _RaytracingLightClusterRW; float3 _ClusterCellSize; -uint _LightPerCellCount; static const float3 CornerSubDirections[8] = { float3(-0.5f, -0.5f, -0.5f), @@ -123,7 +121,7 @@ void RaytracingLightCluster(uint3 threadID : SV_GroupThreadID, uint3 groupId : S if(intersects) { // Flag this light in this cell and increase the light count - _RaytracingLightCluster[cellIndex * cellDataSize + 4 + currentLightCount] = currentLight.lightIndex; + _RaytracingLightClusterRW[cellIndex * cellDataSize + 4 + currentLightCount] = currentLight.lightIndex; currentLightCount++; // Also increase the matching light count @@ -143,10 +141,10 @@ void RaytracingLightCluster(uint3 threadID : SV_GroupThreadID, uint3 groupId : S } // Set the light count for the cell - _RaytracingLightCluster[cellIndex * cellDataSize] = currentLightCount; - _RaytracingLightCluster[cellIndex * cellDataSize + 1] = punctualLightCount; - _RaytracingLightCluster[cellIndex * cellDataSize + 2] = punctualLightCount + areaLightCount; - _RaytracingLightCluster[cellIndex * cellDataSize + 3] = areaLightCount + punctualLightCount + envLightCount; + _RaytracingLightClusterRW[cellIndex * cellDataSize] = currentLightCount; + _RaytracingLightClusterRW[cellIndex * cellDataSize + 1] = punctualLightCount; + _RaytracingLightClusterRW[cellIndex * cellDataSize + 2] = punctualLightCount + areaLightCount; + _RaytracingLightClusterRW[cellIndex * cellDataSize + 3] = areaLightCount + punctualLightCount + envLightCount; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs new file mode 100644 index 00000000000..0da49a3a9a0 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs @@ -0,0 +1,13 @@ +namespace UnityEngine.Rendering.HighDefinition +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true, constantRegister = (int)ConstantRegister.RayTracingLightLoop)] + unsafe struct ShaderVariablesRaytracingLightLoop + { + public Vector3 _MinClusterPos; + public uint _LightPerCellCount; + public Vector3 _MaxClusterPos; + public uint _PunctualLightCountRT; + public uint _AreaLightCountRT; + public uint _EnvLightCountRT; + } +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.hlsl new file mode 100644 index 00000000000..fb1a76af2f1 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.hlsl @@ -0,0 +1,19 @@ +// +// This file was automatically generated. Please don't edit by hand. +// + +#ifndef SHADERVARIABLESRAYTRACINGLIGHTLOOP_CS_HLSL +#define SHADERVARIABLESRAYTRACINGLIGHTLOOP_CS_HLSL +// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesRaytracingLightLoop +// PackingRules = Exact +GLOBAL_CBUFFER_START(ShaderVariablesRaytracingLightLoop, b4) + float3 _MinClusterPos; + uint _LightPerCellCount; + float3 _MaxClusterPos; + uint _PunctualLightCountRT; + uint _AreaLightCountRT; + uint _EnvLightCountRT; +CBUFFER_END + + +#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.hlsl.meta new file mode 100644 index 00000000000..6e113a6d916 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.hlsl.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 6406914af4a2b9a42ae731cf46f90a89 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.meta b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.meta new file mode 100644 index 00000000000..bef77758c46 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9ecef279876c4f94caa6c8bde9d8e297 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.hlsl index d7ba4435888..07c117c3dc0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.hlsl @@ -1,19 +1,10 @@ #ifndef UNITY_SHADER_VARIABLES_RAY_TRACING_LIGHT_LOOP_INCLUDED #define UNITY_SHADER_VARIABLES_RAY_TRACING_LIGHT_LOOP_INCLUDED -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.cs.hlsl" -GLOBAL_RESOURCE(StructuredBuffer, _RaytracingLightCluster, RAY_TRACING_LIGHT_CLUSTER_REGISTER); +GLOBAL_RESOURCE(StructuredBuffer, _RaytracingLightCluster, RAY_TRACING_LIGHT_CLUSTER_REGISTER); GLOBAL_RESOURCE(StructuredBuffer, _LightDatasRT, RAY_TRACING_LIGHT_DATA_REGISTER); GLOBAL_RESOURCE(StructuredBuffer, _EnvLightDatasRT, RAY_TRACING_ENV_LIGHT_DATA_REGISTER); -GLOBAL_CBUFFER_START(UnityRayTracingLightLoop, UNITY_RAY_TRACING_LIGHT_LOOP_CBUFFER_REGISTER) - uint _LightPerCellCount; - float3 _MinClusterPos; - float3 _MaxClusterPos; - uint _PunctualLightCountRT; - uint _AreaLightCountRT; - uint _EnvLightCountRT; -CBUFFER_END - -#endif // UNITY_SHADER_VARIABLES_RAY_TRACING_LIGHT_LOOP_INCLUDED \ No newline at end of file +#endif // UNITY_SHADER_VARIABLES_RAY_TRACING_LIGHT_LOOP_INCLUDED diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index 3623b58075b..2c987bfc6b2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -6,6 +6,7 @@ enum ConstantRegister Global = 0, XR = 1, PBRSky = 2, + RayTracingLightLoop = 4, } // We need to keep the number of different constant buffers low. diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl index 9cf4cb6174b..f1539b3c9f2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl @@ -4,7 +4,6 @@ // Global Constant Buffers - b registers. Unity supports a maximum of 16 global constant buffers. // Ray tracing specific constant buffers #define UNITY_RAY_TRACING_GLOBAL_CBUFFER_REGISTER b3 -#define UNITY_RAY_TRACING_LIGHT_LOOP_CBUFFER_REGISTER b4 // Global Input Resources - t registers. Unity supports a maximum of 64 global input resources (compute buffers, textures, acceleration structure). #define RAY_TRACING_ACCELERATION_STRUCTURE_REGISTER t0 From a360399679d3214a320ed1c5f09164f6378e3190 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 26 Mar 2020 11:04:27 +0100 Subject: [PATCH 64/92] Converted RayTracing global variables to constant buffer. --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 6 +-- .../ScreenSpaceLighting/AmbientOcclusion.cs | 4 +- .../Shadow/ScreenSpaceShadowManager.cs | 40 +++++++-------- .../SubsurfaceScatteringManager.cs | 7 ++- .../RenderPipeline/HDRenderPipeline.cs | 21 +++++++- .../RenderPipeline/HDStringConstants.cs | 17 +------ .../RenderPipeline/PathTracing/PathTracing.cs | 22 +++----- .../HDRaytracingAmbientOcclusion.cs | 10 ++-- .../HDRaytracingDeferredLightLoop.cs | 24 ++------- .../Raytracing/HDRaytracingIndirectDiffuse.cs | 42 ++++++--------- .../HDRaytracingRecursiveRenderer.cs | 14 ++--- .../Raytracing/HDRaytracingReflection.cs | 51 ++++++++----------- .../Raytracing/HDReflectionDenoiser.cs | 2 - .../Shaders/ShaderVariablesRaytracing.cs | 34 +++++++++++++ .../Shaders/ShaderVariablesRaytracing.cs.hlsl | 28 ++++++++++ .../ShaderVariablesRaytracing.cs.hlsl.meta | 9 ++++ .../Shaders/ShaderVariablesRaytracing.cs.meta | 11 ++++ .../Shaders/ShaderVariablesRaytracing.hlsl | 32 +----------- .../ShaderLibrary/ShaderVariablesGlobal.cs | 1 + 19 files changed, 184 insertions(+), 191 deletions(-) create mode 100644 com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs create mode 100644 com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.hlsl create mode 100644 com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.hlsl.meta create mode 100644 com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.meta diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 78e5e8560ad..7d4a2f975d7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3029,7 +3029,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera h parameters.screenSpaceAABBShader = buildScreenAABBShader; parameters.screenSpaceAABBShader.shaderKeywords = null; if (isProjectionOblique) - { + { parameters.screenSpaceAABBShader.EnableKeyword("USE_OBLIQUE_MODE"); } parameters.screenSpaceAABBKernel = s_GenAABBKernel; @@ -3331,7 +3331,6 @@ struct ContactShadowsParameters public bool rayTracingEnabled; public RayTracingShader contactShadowsRTS; public RayTracingAccelerationStructure accelerationStructure; - public float rayTracingBias; public int actualWidth; public int actualHeight; public int depthTextureParameterName; @@ -3351,9 +3350,7 @@ ContactShadowsParameters PrepareContactShadowsParameters(HDCamera hdCamera, floa parameters.rayTracingEnabled = hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing); if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) { - RayTracingSettings raySettings = hdCamera.volumeStack.GetComponent(); parameters.contactShadowsRTS = m_Asset.renderPipelineRayTracingResources.contactShadowRayTracingRT; - parameters.rayTracingBias = raySettings.rayBias.value; parameters.accelerationStructure = RequestAccelerationStructure(); parameters.actualWidth = hdCamera.actualWidth; @@ -3405,7 +3402,6 @@ static void RenderContactShadows( in ContactShadowsParameters parameters, if (parameters.rayTracingEnabled) { cmd.SetRayTracingShaderPass(parameters.contactShadowsRTS, "VisibilityDXR"); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, parameters.rayTracingBias); cmd.SetRayTracingAccelerationStructure(parameters.contactShadowsRTS, HDShaderIDs._RaytracingAccelerationStructureName, parameters.accelerationStructure); cmd.SetRayTracingVectorParam(parameters.contactShadowsRTS, HDShaderIDs._ContactShadowParamsParameters, parameters.params1); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs index 1b9d37179d1..ac4939d0314 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs @@ -241,7 +241,7 @@ internal void InitRaytracing(HDRenderPipeline renderPipeline) internal bool IsActive(HDCamera camera, AmbientOcclusion settings) => camera.frameSettings.IsEnabled(FrameSettingsField.SSAO) && settings.intensity.value > 0f; - internal void Render(CommandBuffer cmd, HDCamera camera, ScriptableRenderContext renderContext, int frameCount) + internal void Render(CommandBuffer cmd, HDCamera camera, ScriptableRenderContext renderContext, in ShaderVariablesRaytracing globalRTCB, int frameCount) { var settings = camera.volumeStack.GetComponent(); @@ -253,7 +253,7 @@ internal void Render(CommandBuffer cmd, HDCamera camera, ScriptableRenderContext else { if (camera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value) - m_RaytracingAmbientOcclusion.RenderAO(camera, cmd, m_AmbientOcclusionTex, renderContext, frameCount); + m_RaytracingAmbientOcclusion.RenderAO(camera, cmd, m_AmbientOcclusionTex, globalRTCB, renderContext, frameCount); else { Dispatch(cmd, camera, frameCount); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs index 8aa98999558..0b720a634a6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs @@ -326,10 +326,6 @@ void RenderDirectionalLightScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamer // Inject the ray-tracing sampling data m_BlueNoise.BindDitheredRNGData8SPP(cmd); - // Inject the ray generation data - RayTracingSettings rayTracingSettings = hdCamera.volumeStack.GetComponent(); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rayTracingSettings.rayBias.value); - // Make sure the right closest hit/any hit will be triggered by using the right multi compile CoreUtils.SetKeyword(cmd, "TRANSPARENT_COLOR_SHADOW", m_CurrentSunLightAdditionalLightData.colorShadow); @@ -339,10 +335,13 @@ void RenderDirectionalLightScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamer // Loop through the samples of this frame for (int sampleIdx = 0; sampleIdx < m_CurrentSunLightAdditionalLightData.numRayTracingSamples; ++sampleIdx) { + // Update global Constant Buffer + m_ShaderVariablesRayTracingCB._RaytracingSampleIndex = sampleIdx; + m_ShaderVariablesRayTracingCB._RaytracingNumSamples = m_CurrentSunLightAdditionalLightData.numRayTracingSamples; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + // Bind the light & sampling data cmd.SetComputeBufferParam(m_ScreenSpaceShadowsCS, m_RaytracingDirectionalShadowSample, HDShaderIDs._DirectionalLightDatas, m_LightLoopLightData.directionalLightData); - cmd.SetGlobalInt(HDShaderIDs._RaytracingSampleIndex, sampleIdx); - cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, m_CurrentSunLightAdditionalLightData.numRayTracingSamples); // Input Buffer cmd.SetComputeTextureParam(m_ScreenSpaceShadowsCS, m_RaytracingDirectionalShadowSample, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); @@ -359,14 +358,12 @@ void RenderDirectionalLightScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamer // Set ray count texture RayCountManager rayCountManager = GetRayCountManager(); - cmd.SetGlobalInt(HDShaderIDs._RayCountEnabled, rayCountManager.RayCountIsEnabled()); cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._RayCountTexture, rayCountManager.GetRayCountTexture()); // Input buffers cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._RaytracingDirectionBuffer, directionBuffer); - cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, m_CurrentSunLightAdditionalLightData.numRayTracingSamples); // Output buffer cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, m_CurrentSunLightAdditionalLightData.colorShadow ? HDShaderIDs._RaytracedColorShadowIntegration : HDShaderIDs._RaytracedShadowIntegration, intermediateBuffer0); @@ -535,7 +532,9 @@ void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera cmd.SetComputeBufferParam(m_ScreenSpaceShadowsCS, m_AreaRaytracingAreaShadowPrepassKernel, HDShaderIDs._LightDatas, m_LightLoopLightData.lightData); cmd.SetComputeMatrixParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingAreaWorldToLocal, m_WorldToLocalArea); cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingTargetAreaLight, lightIndex); - cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, additionalLightData.numRayTracingSamples); + + m_ShaderVariablesRayTracingCB._RaytracingNumSamples = additionalLightData.numRayTracingSamples; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind the input buffers cmd.SetComputeTextureParam(m_ScreenSpaceShadowsCS, m_AreaRaytracingAreaShadowPrepassKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); @@ -568,7 +567,6 @@ void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera // Set ray count texture RayCountManager rayCountManager = GetRayCountManager(); - cmd.SetGlobalInt(HDShaderIDs._RayCountEnabled, rayCountManager.RayCountIsEnabled()); cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._RayCountTexture, rayCountManager.GetRayCountTexture()); // Input data @@ -580,8 +578,6 @@ void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._RaytracingDirectionBuffer, directionBuffer); cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._RaytracingDistanceBuffer, distanceBuffer); cmd.SetRayTracingIntParam(m_ScreenSpaceShadowsRT, HDShaderIDs._RaytracingTargetAreaLight, lightIndex); - RayTracingSettings rayTracingSettings = hdCamera.volumeStack.GetComponent(); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rayTracingSettings.rayBias.value); // Output data cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._RaytracedAreaShadowIntegration, intermediateBufferRGBA0); @@ -592,12 +588,15 @@ void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera // Let's do the following samples (if any) for (int sampleIndex = 1; sampleIndex < additionalLightData.numRayTracingSamples; ++sampleIndex) { + // Update global Constant Buffer + m_ShaderVariablesRayTracingCB._RaytracingNumSamples = additionalLightData.numRayTracingSamples; + m_ShaderVariablesRayTracingCB._RaytracingSampleIndex = sampleIndex; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + // Bind the light data cmd.SetComputeBufferParam(m_ScreenSpaceShadowsCS, m_AreaRaytracingAreaShadowNewSampleKernel, HDShaderIDs._LightDatas, m_LightLoopLightData.lightData); cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingTargetAreaLight, lightIndex); - cmd.SetGlobalInt(HDShaderIDs._RaytracingSampleIndex, sampleIndex); cmd.SetComputeMatrixParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingAreaWorldToLocal, m_WorldToLocalArea); - cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, additionalLightData.numRayTracingSamples); // Input Buffers cmd.SetComputeTextureParam(m_ScreenSpaceShadowsCS, m_AreaRaytracingAreaShadowNewSampleKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); @@ -769,21 +768,20 @@ void RenderPunctualScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera cmd.DispatchCompute(m_ScreenSpaceShadowsCS, m_ClearShadowTexture, numTilesX, numTilesY, hdCamera.viewCount); } - // Bind the ray generation scalars - RayTracingSettings rayTracingSettings = hdCamera.volumeStack.GetComponent(); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rayTracingSettings.rayBias.value); - // Loop through the samples of this frame for (int sampleIdx = 0; sampleIdx < additionalLightData.numRayTracingSamples; ++sampleIdx) { + // Update global constant buffer + m_ShaderVariablesRayTracingCB._RaytracingSampleIndex = sampleIdx; + m_ShaderVariablesRayTracingCB._RaytracingNumSamples = additionalLightData.numRayTracingSamples; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + // Bind the right kernel int shadowKernel = lightData.lightType == GPULightType.Point ? m_RaytracingPointShadowSample : m_RaytracingSpotShadowSample; // Bind the light & sampling data cmd.SetComputeBufferParam(m_ScreenSpaceShadowsCS, shadowKernel, HDShaderIDs._LightDatas, m_LightLoopLightData.lightData); cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingTargetAreaLight, lightIndex); - cmd.SetGlobalInt(HDShaderIDs._RaytracingSampleIndex, sampleIdx); - cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, additionalLightData.numRayTracingSamples); cmd.SetComputeFloatParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingLightRadius, additionalLightData.shapeRadius); // If this is a spot light, inject the spot angle in radians @@ -809,7 +807,6 @@ void RenderPunctualScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera // Set ray count texture RayCountManager rayCountManager = GetRayCountManager(); - cmd.SetGlobalInt(HDShaderIDs._RayCountEnabled, rayCountManager.RayCountIsEnabled()); cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._RayCountTexture, rayCountManager.GetRayCountTexture()); // Input buffers @@ -817,7 +814,6 @@ void RenderPunctualScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._RaytracingDirectionBuffer, directionBuffer); cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._RaytracingDistanceBuffer, distanceBuffer); - cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, additionalLightData.numRayTracingSamples); // Output buffer cmd.SetRayTracingTextureParam(m_ScreenSpaceShadowsRT, HDShaderIDs._RaytracedShadowIntegration, intermediateBuffer0); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index 8c0d1f86770..e1c8ae04cc7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -315,7 +315,6 @@ void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle c // Fetch the volume overrides that we shall be using RayTracingShader subSurfaceShader = m_Asset.renderPipelineRayTracingResources.subSurfaceRayTracing; - RayTracingSettings rayTracingSettings = hdCamera.volumeStack.GetComponent(); ComputeShader deferredRayTracing = m_Asset.renderPipelineRayTracingResources.deferredRaytracingCS; // Fetch all the intermediate buffers that we need @@ -342,9 +341,9 @@ void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle c for (int sampleIndex = 0; sampleIndex < settings.sampleCount.value; ++sampleIndex) { // Inject the ray generation data - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rayTracingSettings.rayBias.value); - cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, settings.sampleCount.value); - cmd.SetGlobalInt(HDShaderIDs._RaytracingSampleIndex, sampleIndex); + m_ShaderVariablesRayTracingCB._RaytracingNumSamples = settings.sampleCount.value; + m_ShaderVariablesRayTracingCB._RaytracingSampleIndex = sampleIndex; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind the textures for ray generation cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._DepthTexture, sharedRTManager.GetDepthStencilBuffer()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 7699186a440..19d1942074f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -970,6 +970,7 @@ void UpdateGlobalConstantBuffers(HDCamera hdCamera, CommandBuffer cmd) { UpdateShaderVariablesGlobalCB(hdCamera, cmd); UpdateShaderVariablesXRCB(hdCamera, cmd); + UpdateShaderVariablesRaytracingCB(hdCamera, cmd); // This one is not in a constant buffer because it's only used as a parameter for some shader's render states. It's not actually used inside shader code. cmd.SetGlobalInt(HDShaderIDs._ColorMaskTransparentVel, (int)ColorWriteMask.All); @@ -1030,6 +1031,24 @@ void UpdateShaderVariablesXRCB(HDCamera hdCamera, CommandBuffer cmd) ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesXRCB, HDShaderIDs._ShaderVariablesXR); } + ShaderVariablesRaytracing m_ShaderVariablesRayTracingCB = new ShaderVariablesRaytracing(); + + void UpdateShaderVariablesRaytracingCB(HDCamera hdCamera, CommandBuffer cmd) + { + RayTracingSettings rayTracingSettings = hdCamera.volumeStack.GetComponent(); + ScreenSpaceReflection screenSpaceReflection = hdCamera.volumeStack.GetComponent(); + + // Those are globally set parameters. The others are set per effect and will update the constant buffer as we render. + m_ShaderVariablesRayTracingCB._RaytracingRayBias = rayTracingSettings.rayBias.value; + m_ShaderVariablesRayTracingCB._RayCountEnabled = m_RayCountManager.RayCountIsEnabled(); + m_ShaderVariablesRayTracingCB._RaytracingCameraNearPlane = hdCamera.camera.nearClipPlane; + m_ShaderVariablesRayTracingCB._RaytracingPixelSpreadAngle = GetPixelSpreadAngle(hdCamera.camera.fieldOfView, hdCamera.actualWidth, hdCamera.actualHeight); + m_ShaderVariablesRayTracingCB._RaytracingReflectionMinSmoothness = screenSpaceReflection.minSmoothness.value; + m_ShaderVariablesRayTracingCB._RaytracingReflectionSmoothnessFadeStart = screenSpaceReflection.smoothnessFadeStart.value; + + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + } + void CopyDepthBufferIfNeeded(HDCamera hdCamera, CommandBuffer cmd) { if (!m_IsDepthBufferCopyValid) @@ -2185,7 +2204,7 @@ void Callback(CommandBuffer c, HDCamera cam) } if (!hdCamera.frameSettings.SSAORunsAsync()) - m_AmbientOcclusionSystem.Render(cmd, hdCamera, renderContext, m_FrameCount); + m_AmbientOcclusionSystem.Render(cmd, hdCamera, renderContext, m_ShaderVariablesRayTracingCB, m_FrameCount); // Run the contact shadows here as they need the light list HDUtils.CheckRTCreated(m_ContactShadowBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 3b2ed2e22ac..5e370503501 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -253,6 +253,7 @@ static class HDShaderIDs public static readonly int _ShaderVariablesXR = Shader.PropertyToID("ShaderVariablesXR"); public static readonly int _ShaderVariablesVolumetric = Shader.PropertyToID("ShaderVariablesVolumetric"); public static readonly int _ShaderVariablesLightList = Shader.PropertyToID("ShaderVariablesLightList"); + public static readonly int _ShaderVariablesRaytracing = Shader.PropertyToID("ShaderVariablesRaytracing"); public static readonly int _ShaderVariablesRaytracingLightLoop = Shader.PropertyToID("ShaderVariablesRaytracingLightLoop"); public static readonly int _ShaderVariablesDebugDisplay = Shader.PropertyToID("ShaderVariablesDebugDisplay"); @@ -413,13 +414,8 @@ static class HDShaderIDs public static readonly int _HorizonZenithShiftScale = Shader.PropertyToID("_HorizonZenithShiftScale"); // Raytracing variables - public static readonly int _RaytracingRayBias = Shader.PropertyToID("_RaytracingRayBias"); public static readonly int _RayTracingLayerMask = Shader.PropertyToID("_RayTracingLayerMask"); - public static readonly int _RaytracingNumSamples = Shader.PropertyToID("_RaytracingNumSamples"); - public static readonly int _RaytracingSampleIndex = Shader.PropertyToID("_RaytracingSampleIndex"); - public static readonly int _RaytracingRayMaxLength = Shader.PropertyToID("_RaytracingRayMaxLength"); public static readonly int _PixelSpreadAngleTangent = Shader.PropertyToID("_PixelSpreadAngleTangent"); - public static readonly int _RaytracingPixelSpreadAngle = Shader.PropertyToID("_RaytracingPixelSpreadAngle"); public static readonly string _RaytracingAccelerationStructureName = "_RaytracingAccelerationStructure"; // Light Cluster @@ -459,14 +455,8 @@ static class HDShaderIDs public static readonly int _AccumulatedFrameTexture = Shader.PropertyToID("_AccumulatedFrameTexture"); public static readonly int _TemporalAccumuationWeight = Shader.PropertyToID("_TemporalAccumuationWeight"); public static readonly int _SpatialFilterRadius = Shader.PropertyToID("_SpatialFilterRadius"); - public static readonly int _RaytracingReflectionMaxDistance = Shader.PropertyToID("_RaytracingReflectionMaxDistance"); public static readonly int _RaytracingHitDistanceTexture = Shader.PropertyToID("_RaytracingHitDistanceTexture"); - public static readonly int _RaytracingIntensityClamp = Shader.PropertyToID("_RaytracingIntensityClamp"); - public static readonly int _RaytracingPreExposition = Shader.PropertyToID("_RaytracingPreExposition"); - public static readonly int _RaytracingReflectionMinSmoothness = Shader.PropertyToID("_RaytracingReflectionMinSmoothness"); - public static readonly int _RaytracingReflectionSmoothnessFadeStart = Shader.PropertyToID("_RaytracingReflectionSmoothnessFadeStart"); public static readonly int _RaytracingVSNormalTexture = Shader.PropertyToID("_RaytracingVSNormalTexture"); - public static readonly int _RaytracingIncludeSky = Shader.PropertyToID("_RaytracingIncludeSky"); // Shadows public static readonly int _RaytracingTargetAreaLight = Shader.PropertyToID("_RaytracingTargetAreaLight"); @@ -499,7 +489,6 @@ static class HDShaderIDs public static readonly int _RaytracingAOIntensity = Shader.PropertyToID("_RaytracingAOIntensity"); // Ray count - public static readonly int _RayCountEnabled = Shader.PropertyToID("_RayCountEnabled"); public static readonly int _RayCountTexture = Shader.PropertyToID("_RayCountTexture"); public static readonly int _RayCountType = Shader.PropertyToID("_RayCountType"); public static readonly int _InputRayCountTexture = Shader.PropertyToID("_InputRayCountTexture"); @@ -510,10 +499,7 @@ static class HDShaderIDs // Primary Visibility public static readonly int _RaytracingFlagMask = Shader.PropertyToID("_RaytracingFlagMask"); - public static readonly int _RaytracingMinRecursion = Shader.PropertyToID("_RaytracingMinRecursion"); - public static readonly int _RaytracingMaxRecursion = Shader.PropertyToID("_RaytracingMaxRecursion"); public static readonly int _RaytracingPrimaryDebug = Shader.PropertyToID("_RaytracingPrimaryDebug"); - public static readonly int _RaytracingCameraNearPlane = Shader.PropertyToID("_RaytracingCameraNearPlane"); public static readonly int _RaytracingCameraSkyEnabled = Shader.PropertyToID("_RaytracingCameraSkyEnabled"); public static readonly int _RaytracingCameraClearColor = Shader.PropertyToID("_RaytracingCameraClearColor"); @@ -525,7 +511,6 @@ static class HDShaderIDs // Deferred Lighting public static readonly int _RaytracingLitBufferRW = Shader.PropertyToID("_RaytracingLitBufferRW"); - public static readonly int _RaytracingDiffuseRay = Shader.PropertyToID("_RaytracingDiffuseRay"); // Ray binning public static readonly int _RayBinResult = Shader.PropertyToID("_RayBinResult"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs index 5cfdadfcc3f..18f4f0ca94c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs @@ -217,7 +217,6 @@ void RenderPathTracing(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputText RayTracingAccelerationStructure accelerationStructure = RequestAccelerationStructure(); HDRaytracingLightCluster lightCluster = RequestLightCluster(); LightCluster lightClusterSettings = hdCamera.volumeStack.GetComponent(); - RayTracingSettings rayTracingSettings = hdCamera.volumeStack.GetComponent(); if (!m_SubFrameManager.isRecording) { @@ -243,20 +242,13 @@ void RenderPathTracing(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputText cmd.SetGlobalTexture(HDShaderIDs._OwenScrambledTexture, m_Asset.renderPipelineResources.textures.owenScrambled256Tex); cmd.SetGlobalTexture(HDShaderIDs._ScramblingTexture, m_Asset.renderPipelineResources.textures.scramblingTex); - // Inject the ray generation data - - cmd.SetGlobalFloat(HDShaderIDs._RaytracingNumSamples, m_SubFrameManager.subFrameCount); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingMinRecursion, m_PathTracingSettings.minimumDepth.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingMaxRecursion, m_PathTracingSettings.maximumDepth.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingIntensityClamp, m_PathTracingSettings.maximumIntensity.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rayTracingSettings.rayBias.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingCameraNearPlane, hdCamera.camera.nearClipPlane); - - // Set the data for the ray generation - cmd.SetGlobalInt(HDShaderIDs._RaytracingSampleIndex, (int)m_SubFrameManager.iteration); - - // Compute an approximate pixel spread angle value (in radians) - cmd.SetGlobalFloat(HDShaderIDs._RaytracingPixelSpreadAngle, GetPixelSpreadAngle(hdCamera.camera.fieldOfView, hdCamera.actualWidth, hdCamera.actualHeight)); + // Update the global constant buffer + m_ShaderVariablesRayTracingCB._RaytracingNumSamples = (int)m_SubFrameManager.subFrameCount; + m_ShaderVariablesRayTracingCB._RaytracingMinRecursion = m_PathTracingSettings.minimumDepth.value; + m_ShaderVariablesRayTracingCB._RaytracingMaxRecursion = m_PathTracingSettings.maximumDepth.value; + m_ShaderVariablesRayTracingCB._RaytracingIntensityClamp = m_PathTracingSettings.maximumIntensity.value; + m_ShaderVariablesRayTracingCB._RaytracingSampleIndex = (int)m_SubFrameManager.iteration; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // LightLoop data cmd.SetGlobalBuffer(HDShaderIDs._RaytracingLightCluster, lightCluster.GetCluster()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs index c295d1ae076..6f0ceea9e21 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs @@ -61,7 +61,7 @@ public void SetDefaultAmbientOcclusionTexture(CommandBuffer cmd) cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, TextureXR.GetBlackTexture()); } - public void RenderAO(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputTexture, ScriptableRenderContext renderContext, int frameCount) + public void RenderAO(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputTexture, ShaderVariablesRaytracing globalCB, ScriptableRenderContext renderContext, int frameCount) { // If any of the previous requirements is missing, the effect is not requested or no acceleration structure, set the default one and leave right away if (!m_RenderPipeline.GetRayTracingState()) @@ -72,7 +72,6 @@ public void RenderAO(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputTextur RayTracingShader aoShader = m_PipelineRayTracingResources.aoRaytracing; var aoSettings = hdCamera.volumeStack.GetComponent(); - RayTracingSettings rayTracingSettings = hdCamera.volumeStack.GetComponent(); RayCountManager rayCountManager = m_RenderPipeline.GetRayCountManager(); using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingAmbientOcclusion))) @@ -87,10 +86,9 @@ public void RenderAO(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputTextur cmd.SetRayTracingAccelerationStructure(aoShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure); // Inject the ray generation data (be careful of the global constant buffer limitation) - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rayTracingSettings.rayBias.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, aoSettings.rayLength.value); - cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, aoSettings.sampleCount.value); - int frameIndex = m_RenderPipeline.RayTracingFrameIndex(hdCamera); + globalCB._RaytracingRayMaxLength = aoSettings.rayLength.value; + globalCB._RaytracingNumSamples = aoSettings.sampleCount.value; + ConstantBuffer.PushGlobal(cmd, globalCB, HDShaderIDs._ShaderVariablesRaytracing); // Set the data for the ray generation cmd.SetRayTracingTextureParam(aoShader, HDShaderIDs._DepthTexture, m_RenderPipeline.sharedRTManager.GetDepthStencilBuffer()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.cs index 979d0abace4..3a3488d7ca0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.cs @@ -12,21 +12,14 @@ struct DeferredLightingRTParameters // Generic attributes public bool rayBinning; public LayerMask layerMask; - public float rayBias; - public float maxRayLength; - public float clampValue; - public bool includeSky; public bool diffuseLightingOnly; public bool halfResolution; - public int rayCountFlag; public int rayCountType; - public bool preExpose; // Camera data public int width; public int height; public int viewCount; - public float fov; // Compute buffers public ComputeBuffer rayBinResult; @@ -38,6 +31,8 @@ struct DeferredLightingRTParameters public RayTracingShader gBufferRaytracingRT; public ComputeShader deferredRaytracingCS; public ComputeShader rayBinningCS; + + public ShaderVariablesRaytracing globalCB; } struct DeferredLightingRTResources @@ -187,6 +182,9 @@ static void RenderRaytracingDeferredLighting(CommandBuffer cmd, in DeferredLight BinRays(cmd, parameters, buffers.directionBuffer, texWidth, texHeight); } + // Inject the global parameters + ConstantBuffer.PushGlobal(cmd, parameters.globalCB, HDShaderIDs._ShaderVariablesRaytracing); + // Define the shader pass to use for the reflection pass cmd.SetRayTracingShaderPass(parameters.gBufferRaytracingRT, "GBufferDXR"); @@ -202,18 +200,14 @@ static void RenderRaytracingDeferredLighting(CommandBuffer cmd, in DeferredLight cmd.SetRayTracingAccelerationStructure(parameters.gBufferRaytracingRT, HDShaderIDs._RaytracingAccelerationStructureName, parameters.accelerationStructure); // Set ray count texture - cmd.SetGlobalInt(HDShaderIDs._RayCountEnabled, parameters.rayCountFlag); cmd.SetRayTracingIntParam(parameters.gBufferRaytracingRT, HDShaderIDs._RayCountType, parameters.rayCountType); cmd.SetRayTracingTextureParam(parameters.gBufferRaytracingRT, HDShaderIDs._RayCountTexture, buffers.rayCountTexture); // Bind all input parameter - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, parameters.rayBias); cmd.SetRayTracingIntParams(parameters.gBufferRaytracingRT, HDShaderIDs._RayTracingLayerMask, parameters.layerMask); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, parameters.maxRayLength); cmd.SetRayTracingTextureParam(parameters.gBufferRaytracingRT, HDShaderIDs._DepthTexture, buffers.depthStencilBuffer); cmd.SetRayTracingTextureParam(parameters.gBufferRaytracingRT, HDShaderIDs._NormalBufferTexture, buffers.normalBuffer); cmd.SetRayTracingTextureParam(parameters.gBufferRaytracingRT, HDShaderIDs._RaytracingDirectionBuffer, buffers.directionBuffer); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingPixelSpreadAngle, HDRenderPipeline.GetPixelSpreadAngle(parameters.fov, parameters.width, parameters.height)); // Bind the output textures cmd.SetRayTracingTextureParam(parameters.gBufferRaytracingRT, HDShaderIDs._GBufferTextureRW[0], buffers.gbuffer0); @@ -227,16 +221,12 @@ static void RenderRaytracingDeferredLighting(CommandBuffer cmd, in DeferredLight uint heightResolution = (uint)parameters.height; // Include the sky if required - cmd.SetGlobalInt(HDShaderIDs._RaytracingIncludeSky, parameters.includeSky ? 1 : 0); cmd.SetRayTracingTextureParam(parameters.gBufferRaytracingRT, HDShaderIDs._SkyTexture, buffers.skyTexture); // Only compute diffuse lighting if required CoreUtils.SetKeyword(cmd, "DIFFUSE_LIGHTING_ONLY", parameters.diffuseLightingOnly); CoreUtils.SetKeyword(cmd, "MULTI_BOUNCE_INDIRECT", false); - // All rays are diffuse if we are evaluating diffuse lighting only - cmd.SetGlobalInt(HDShaderIDs._RaytracingDiffuseRay, parameters.diffuseLightingOnly ? 1 : 0); - if (parameters.rayBinning) { // Evaluate the dispatch parameters @@ -273,10 +263,6 @@ static void RenderRaytracingDeferredLighting(CommandBuffer cmd, in DeferredLight cmd.SetComputeTextureParam(parameters.deferredRaytracingCS, currentKernel, HDShaderIDs._GBufferTexture[3], buffers.gbuffer3); cmd.SetComputeTextureParam(parameters.deferredRaytracingCS, currentKernel, HDShaderIDs._LightLayersTexture, TextureXR.GetWhiteTexture()); - // Inject the other parameters - cmd.SetGlobalFloat(HDShaderIDs._RaytracingIntensityClamp, parameters.clampValue); - cmd.SetGlobalInt(HDShaderIDs._RaytracingPreExposition, parameters.preExpose ? 1 : 0); - // Bind the output texture cmd.SetComputeTextureParam(parameters.deferredRaytracingCS, currentKernel, HDShaderIDs._RaytracingLitBufferRW, buffers.litBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs index 442034e5409..b01effa2c9f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs @@ -114,22 +114,15 @@ DeferredLightingRTParameters PrepareIndirectDiffuseDeferredLightingRTParameters( // Generic attributes deferredParameters.rayBinning = true; deferredParameters.layerMask.value = (int)RayTracingRendererFlag.GlobalIllumination; - deferredParameters.rayBias = rTSettings.rayBias.value; - deferredParameters.maxRayLength = settings.rayLength.value; - deferredParameters.clampValue = settings.clampValue.value; - deferredParameters.includeSky = true; deferredParameters.diffuseLightingOnly = true; deferredParameters.halfResolution = false; - deferredParameters.rayCountFlag = m_RayCountManager.RayCountIsEnabled(); deferredParameters.rayCountType = (int)RayCountValues.DiffuseGI_Deferred; - deferredParameters.preExpose = true; // Camera data deferredParameters.width = hdCamera.actualWidth; deferredParameters.height = hdCamera.actualHeight; deferredParameters.viewCount = hdCamera.viewCount; - deferredParameters.fov = hdCamera.camera.fieldOfView; // Compute buffers deferredParameters.rayBinResult = m_RayBinResult; @@ -149,6 +142,13 @@ DeferredLightingRTParameters PrepareIndirectDiffuseDeferredLightingRTParameters( Debug.LogWarning("Ray binning is not supported with XR single-pass rendering!"); } + deferredParameters.globalCB = m_ShaderVariablesRayTracingCB; + deferredParameters.globalCB._RaytracingIntensityClamp = settings.clampValue.value; + deferredParameters.globalCB._RaytracingPreExposition = 1; + deferredParameters.globalCB._RaytracingDiffuseRay = 1; + deferredParameters.globalCB._RaytracingIncludeSky = 1; + deferredParameters.globalCB._RaytracingRayMaxLength = settings.rayLength.value; + return deferredParameters; } @@ -180,9 +180,6 @@ void RenderIndirectDiffusePerformance(HDCamera hdCamera, CommandBuffer cmd, Scri cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); - // Bind all the required scalars - cmd.SetGlobalFloat(HDShaderIDs._RaytracingIntensityClamp, settings.clampValue.value); - // Bind the output buffers cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._RaytracingDirectionBuffer, directionBuffer); @@ -246,7 +243,7 @@ void RenderIndirectDiffusePerformance(HDCamera hdCamera, CommandBuffer cmd, Scri void BindRayTracedIndirectDiffuseData(CommandBuffer cmd, HDCamera hdCamera , RayTracingShader indirectDiffuseShader - , GlobalIllumination settings, LightCluster lightClusterSettings, RayTracingSettings rtSettings + , GlobalIllumination settings, LightCluster lightClusterSettings , RTHandle outputLightingBuffer, RTHandle outputHitPointBuffer) { // Grab the acceleration structures and the light cluster to use @@ -263,36 +260,28 @@ void BindRayTracedIndirectDiffuseData(CommandBuffer cmd, HDCamera hdCamera // Inject the ray-tracing sampling data blueNoise.BindDitheredRNGData8SPP(cmd); - // Inject the ray generation data - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rtSettings.rayBias.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, settings.rayLength.value); - cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, settings.sampleCount.value); - // Set the data for the ray generation cmd.SetRayTracingTextureParam(indirectDiffuseShader, HDShaderIDs._IndirectDiffuseTextureRW, outputLightingBuffer); cmd.SetRayTracingTextureParam(indirectDiffuseShader, HDShaderIDs._IndirectDiffuseHitPointTextureRW, outputHitPointBuffer); cmd.SetRayTracingTextureParam(indirectDiffuseShader, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetRayTracingTextureParam(indirectDiffuseShader, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); - // Set the indirect diffuse parameters - cmd.SetGlobalFloat(HDShaderIDs._RaytracingIntensityClamp, settings.clampValue.value); - // Set ray count texture RayCountManager rayCountManager = GetRayCountManager(); - cmd.SetGlobalInt(HDShaderIDs._RayCountEnabled, rayCountManager.RayCountIsEnabled()); cmd.SetRayTracingTextureParam(indirectDiffuseShader, HDShaderIDs._RayCountTexture, rayCountManager.GetRayCountTexture()); - // Compute the pixel spread value - cmd.SetGlobalFloat(HDShaderIDs._RaytracingPixelSpreadAngle, GetPixelSpreadAngle(hdCamera.camera.fieldOfView, hdCamera.actualWidth, hdCamera.actualHeight)); - // LightLoop data lightCluster.BindLightClusterData(cmd); // Set the data for the ray miss cmd.SetRayTracingTextureParam(indirectDiffuseShader, HDShaderIDs._SkyTexture, m_SkyManager.GetSkyReflection(hdCamera)); - // Set the number of bounces to 1 - cmd.SetGlobalInt(HDShaderIDs._RaytracingMaxRecursion, settings.bounceCount.value); + // Update global constant buffer + m_ShaderVariablesRayTracingCB._RaytracingRayMaxLength = settings.rayLength.value; + m_ShaderVariablesRayTracingCB._RaytracingNumSamples = settings.sampleCount.value; + m_ShaderVariablesRayTracingCB._RaytracingIntensityClamp = settings.clampValue.value; + m_ShaderVariablesRayTracingCB._RaytracingMaxRecursion = settings.bounceCount.value; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); } void RenderIndirectDiffuseQuality(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, int frameCount) @@ -300,7 +289,6 @@ void RenderIndirectDiffuseQuality(HDCamera hdCamera, CommandBuffer cmd, Scriptab // First thing to check is: Do we have a valid ray-tracing environment? GlobalIllumination giSettings = hdCamera.volumeStack.GetComponent(); LightCluster lightClusterSettings = hdCamera.volumeStack.GetComponent(); - RayTracingSettings rtSettings = hdCamera.volumeStack.GetComponent(); // Shaders that are used RayTracingShader indirectDiffuseRT = m_Asset.renderPipelineRayTracingResources.indirectDiffuseRaytracingRT; @@ -309,7 +297,7 @@ void RenderIndirectDiffuseQuality(HDCamera hdCamera, CommandBuffer cmd, Scriptab RTHandle intermediateBuffer1 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA1); // Bind all the parameters for ray tracing - BindRayTracedIndirectDiffuseData(cmd, hdCamera, indirectDiffuseRT, giSettings, lightClusterSettings, rtSettings, m_IndirectDiffuseBuffer, intermediateBuffer1); + BindRayTracedIndirectDiffuseData(cmd, hdCamera, indirectDiffuseRT, giSettings, lightClusterSettings, m_IndirectDiffuseBuffer, intermediateBuffer1); // Compute the actual resolution that is needed base on the quality int widthResolution = hdCamera.actualWidth; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs index d891bdf6c08..81592c80e85 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs @@ -94,7 +94,6 @@ void RaytracingRecursiveRender(HDCamera hdCamera, CommandBuffer cmd, ScriptableR RayTracingShader forwardShader = m_Asset.renderPipelineRayTracingResources.forwardRaytracing; Shader raytracingMask = m_Asset.renderPipelineRayTracingResources.raytracingFlagMask; LightCluster lightClusterSettings = hdCamera.volumeStack.GetComponent(); - RayTracingSettings rtSettings = hdCamera.volumeStack.GetComponent(); // Grab the acceleration structure and the list of HD lights for the target camera RayTracingAccelerationStructure accelerationStructure = RequestAccelerationStructure(); @@ -119,11 +118,10 @@ void RaytracingRecursiveRender(HDCamera hdCamera, CommandBuffer cmd, ScriptableR cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._OwenScrambledTexture, m_Asset.renderPipelineResources.textures.owenScrambledRGBATex); cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._ScramblingTexture, m_Asset.renderPipelineResources.textures.scramblingTex); - // Inject the ray generation data - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rtSettings.rayBias.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, recursiveSettings.rayLength.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingMaxRecursion, recursiveSettings.maxDepth.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingCameraNearPlane, hdCamera.camera.nearClipPlane); + // Update the global constant buffer. + m_ShaderVariablesRayTracingCB._RaytracingRayMaxLength = recursiveSettings.rayLength.value; + m_ShaderVariablesRayTracingCB._RaytracingMaxRecursion = recursiveSettings.maxDepth.value; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Set the data for the ray generation cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._RaytracingFlagMask, flagBuffer); @@ -132,12 +130,8 @@ void RaytracingRecursiveRender(HDCamera hdCamera, CommandBuffer cmd, ScriptableR // Set ray count texture RayCountManager rayCountManager = GetRayCountManager(); - cmd.SetGlobalInt(HDShaderIDs._RayCountEnabled, rayCountManager.RayCountIsEnabled()); cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._RayCountTexture, rayCountManager.GetRayCountTexture()); - // Compute an approximate pixel spread angle value (in radians) - cmd.SetGlobalFloat(HDShaderIDs._RaytracingPixelSpreadAngle, GetPixelSpreadAngle(hdCamera.camera.fieldOfView, hdCamera.actualWidth, hdCamera.actualHeight)); - // LightLoop data cmd.SetGlobalBuffer(HDShaderIDs._RaytracingLightCluster, lightCluster.GetCluster()); cmd.SetGlobalBuffer(HDShaderIDs._LightDatasRT, lightCluster.GetLightDatas()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs index 8fd85ad43a2..9719542ff11 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs @@ -43,8 +43,8 @@ void RenderRayTracedReflections(HDCamera hdCamera, CommandBuffer cmd, RTHandle o } } - void BindRayTracedReflectionData(CommandBuffer cmd, HDCamera hdCamera, RayTracingShader reflectionShader, ScreenSpaceReflection settings, LightCluster lightClusterSettings, RayTracingSettings rtSettings - , RTHandle outputLightingBuffer, RTHandle outputHitPointBuffer) + void BindRayTracedReflectionData(CommandBuffer cmd, HDCamera hdCamera, RayTracingShader reflectionShader, ScreenSpaceReflection settings, LightCluster lightClusterSettings, + RTHandle outputLightingBuffer, RTHandle outputHitPointBuffer) { // Grab the acceleration structures and the light cluster to use RayTracingAccelerationStructure accelerationStructure = RequestAccelerationStructure(); @@ -58,15 +58,14 @@ void BindRayTracedReflectionData(CommandBuffer cmd, HDCamera hdCamera, RayTracin cmd.SetRayTracingAccelerationStructure(reflectionShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure); // Global reflection parameters - cmd.SetGlobalFloat(HDShaderIDs._RaytracingIntensityClamp, settings.clampValue.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingReflectionMinSmoothness, settings.minSmoothness.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingReflectionSmoothnessFadeStart, settings.smoothnessFadeStart.value); - cmd.SetGlobalInt(HDShaderIDs._RaytracingIncludeSky, settings.reflectSky.value ? 1 : 0); - + m_ShaderVariablesRayTracingCB._RaytracingIntensityClamp = settings.clampValue.value; + m_ShaderVariablesRayTracingCB._RaytracingIncludeSky = settings.reflectSky.value ? 1 : 0; // Inject the ray generation data - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rtSettings.rayBias.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, settings.rayLength.value); - cmd.SetGlobalInt(HDShaderIDs._RaytracingNumSamples, settings.sampleCount.value); + m_ShaderVariablesRayTracingCB._RaytracingRayMaxLength = settings.rayLength.value; + m_ShaderVariablesRayTracingCB._RaytracingNumSamples = settings.sampleCount.value; + // Set the number of bounces for reflections + m_ShaderVariablesRayTracingCB._RaytracingMaxRecursion = settings.bounceCount.value; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Inject the ray-tracing sampling data blueNoise.BindDitheredRNGData8SPP(cmd); @@ -81,12 +80,8 @@ void BindRayTracedReflectionData(CommandBuffer cmd, HDCamera hdCamera, RayTracin // Set ray count tex RayCountManager rayCountManager = GetRayCountManager(); - cmd.SetGlobalInt(HDShaderIDs._RayCountEnabled, rayCountManager.RayCountIsEnabled()); cmd.SetRayTracingTextureParam(reflectionShader, HDShaderIDs._RayCountTexture, rayCountManager.GetRayCountTexture()); - // Compute the pixel spread value - cmd.SetGlobalFloat(HDShaderIDs._RaytracingPixelSpreadAngle, GetPixelSpreadAngle(hdCamera.camera.fieldOfView, hdCamera.actualWidth, hdCamera.actualHeight)); - // Bind the lightLoop data lightCluster.BindLightClusterData(cmd); @@ -97,9 +92,6 @@ void BindRayTracedReflectionData(CommandBuffer cmd, HDCamera hdCamera, RayTracin RenderTargetIdentifier clearCoatMaskTexture = hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred ? m_GbufferManager.GetBuffersRTI()[2] : TextureXR.GetBlackTexture(); cmd.SetRayTracingTextureParam(reflectionShader, HDShaderIDs._SsrClearCoatMaskTexture, clearCoatMaskTexture); - // Set the number of bounces for reflections - cmd.SetGlobalInt(HDShaderIDs._RaytracingMaxRecursion, settings.bounceCount.value); - // Set the data for the ray miss cmd.SetRayTracingTextureParam(reflectionShader, HDShaderIDs._SkyTexture, m_SkyManager.GetSkyReflection(hdCamera)); } @@ -118,21 +110,14 @@ DeferredLightingRTParameters PrepareReflectionDeferredLightingRTParameters(HDCam // Generic attributes deferredParameters.rayBinning = true; deferredParameters.layerMask.value = (int)RayTracingRendererFlag.Reflection; - deferredParameters.rayBias = rTSettings.rayBias.value; - deferredParameters.maxRayLength = settings.rayLength.value; - deferredParameters.clampValue = settings.clampValue.value; - deferredParameters.includeSky = settings.reflectSky.value; deferredParameters.diffuseLightingOnly = false; deferredParameters.halfResolution = !settings.fullResolution.value; - deferredParameters.rayCountFlag = m_RayCountManager.RayCountIsEnabled(); deferredParameters.rayCountType = (int)RayCountValues.ReflectionDeferred; - deferredParameters.preExpose = false; // Camera data deferredParameters.width = hdCamera.actualWidth; deferredParameters.height = hdCamera.actualHeight; deferredParameters.viewCount = hdCamera.viewCount; - deferredParameters.fov = hdCamera.camera.fieldOfView; // Compute buffers deferredParameters.rayBinResult = m_RayBinResult; @@ -152,6 +137,13 @@ DeferredLightingRTParameters PrepareReflectionDeferredLightingRTParameters(HDCam Debug.LogWarning("Ray binning is not supported with XR single-pass rendering!"); } + deferredParameters.globalCB = m_ShaderVariablesRayTracingCB; + deferredParameters.globalCB._RaytracingRayMaxLength = settings.rayLength.value; + deferredParameters.globalCB._RaytracingIntensityClamp = settings.clampValue.value; + deferredParameters.globalCB._RaytracingIncludeSky = settings.reflectSky.value ? 1 : 0; + deferredParameters.globalCB._RaytracingPreExposition = 0; + deferredParameters.globalCB._RaytracingDiffuseRay = 0; + return deferredParameters; } @@ -197,9 +189,9 @@ void RenderReflectionsPerformance(HDCamera hdCamera, CommandBuffer cmd, RTHandle cmd.SetComputeTextureParam(reflectionShaderCS, currentKernel, HDShaderIDs._StencilTexture, m_SharedRTManager.GetDepthStencilBuffer(), 0, RenderTextureSubElement.Stencil); // Bind all the required scalars - cmd.SetGlobalFloat(HDShaderIDs._RaytracingIntensityClamp, settings.clampValue.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingReflectionMinSmoothness, settings.minSmoothness.value); - cmd.SetGlobalInt(HDShaderIDs._RaytracingIncludeSky, settings.reflectSky.value ? 1 : 0); + m_ShaderVariablesRayTracingCB._RaytracingIntensityClamp = settings.clampValue.value; + m_ShaderVariablesRayTracingCB._RaytracingIncludeSky = settings.reflectSky.value ? 1 : 0; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind the output buffers cmd.SetComputeTextureParam(reflectionShaderCS, currentKernel, HDShaderIDs._RaytracingDirectionBuffer, intermediateBuffer1); @@ -247,8 +239,6 @@ void RenderReflectionsPerformance(HDCamera hdCamera, CommandBuffer cmd, RTHandle cmd.SetComputeTextureParam(reflectionFilter, currentKernel, HDShaderIDs._ScramblingTexture, m_Asset.renderPipelineResources.textures.scramblingTex); cmd.SetComputeIntParam(reflectionFilter, HDShaderIDs._SpatialFilterRadius, settings.upscaleRadius.value); cmd.SetComputeIntParam(reflectionFilter, HDShaderIDs._RaytracingDenoiseRadius, settings.denoise.value ? settings.denoiserRadius.value : 0); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingReflectionMinSmoothness, settings.minSmoothness.value); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingReflectionSmoothnessFadeStart, settings.smoothnessFadeStart.value); numTilesXHR = (texWidth + (areaTileSize - 1)) / areaTileSize; numTilesYHR = (texHeight + (areaTileSize - 1)) / areaTileSize; @@ -297,12 +287,11 @@ void RenderReflectionsQuality(HDCamera hdCamera, CommandBuffer cmd, RTHandle out var settings = hdCamera.volumeStack.GetComponent(); LightCluster lightClusterSettings = hdCamera.volumeStack.GetComponent(); - RayTracingSettings rtSettings = hdCamera.volumeStack.GetComponent(); using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingIntegrateReflection))) { // Bind all the required data for ray tracing - BindRayTracedReflectionData(cmd, hdCamera, reflectionShader, settings, lightClusterSettings, rtSettings, intermediateBuffer0, intermediateBuffer1); + BindRayTracedReflectionData(cmd, hdCamera, reflectionShader, settings, lightClusterSettings, intermediateBuffer0, intermediateBuffer1); // Only use the shader variant that has multi bounce if the bounce count > 1 CoreUtils.SetKeyword(cmd, "MULTI_BOUNCE_INDIRECT", settings.bounceCount.value > 1); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDReflectionDenoiser.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDReflectionDenoiser.cs index b0cf11ec1a0..88192bfabdc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDReflectionDenoiser.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDReflectionDenoiser.cs @@ -75,7 +75,6 @@ public void DenoiseBuffer(CommandBuffer cmd, HDCamera hdCamera, int maxKernelSiz cmd.SetComputeTextureParam(m_ReflectionDenoiserCS, s_BilateralFilterHKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); cmd.SetComputeTextureParam(m_ReflectionDenoiserCS, s_BilateralFilterHKernel, HDShaderIDs._DenoiseOutputTextureRW, intermediateBuffer1); cmd.SetComputeTextureParam(m_ReflectionDenoiserCS, s_BilateralFilterHKernel, HDShaderIDs._ReflectionFilterMapping, m_ReflectionFilterMapping); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingReflectionMinSmoothness, settings.minSmoothness.value); cmd.DispatchCompute(m_ReflectionDenoiserCS, s_BilateralFilterHKernel, numTilesX, numTilesY, hdCamera.viewCount); // Horizontal pass of the bilateral filter @@ -85,7 +84,6 @@ public void DenoiseBuffer(CommandBuffer cmd, HDCamera hdCamera, int maxKernelSiz cmd.SetComputeTextureParam(m_ReflectionDenoiserCS, s_BilateralFilterVKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); cmd.SetComputeTextureParam(m_ReflectionDenoiserCS, s_BilateralFilterVKernel, HDShaderIDs._DenoiseOutputTextureRW, outputSignal); cmd.SetComputeTextureParam(m_ReflectionDenoiserCS, s_BilateralFilterVKernel, HDShaderIDs._ReflectionFilterMapping, m_ReflectionFilterMapping); - cmd.SetGlobalFloat(HDShaderIDs._RaytracingReflectionMinSmoothness, settings.minSmoothness.value); cmd.DispatchCompute(m_ReflectionDenoiserCS, s_BilateralFilterVKernel, numTilesX, numTilesY, hdCamera.viewCount); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs new file mode 100644 index 00000000000..8a29680643a --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs @@ -0,0 +1,34 @@ +namespace UnityEngine.Rendering.HighDefinition +{ + [GenerateHLSL(needAccessors = false, generateCBuffer = true, constantRegister = (int)ConstantRegister.RayTracing)] + unsafe struct ShaderVariablesRaytracing + { + // Global ray bias used for all trace rays + public float _RaytracingRayBias; + // Maximal ray length for trace ray (in case an other one does not override it) + public float _RaytracingRayMaxLength; + // Number of samples that will be used to evaluate an effect + public int _RaytracingNumSamples; + // Index of the current sample + public int _RaytracingSampleIndex; + // Value used to clamp the intensity of the signal to reduce the signal/noise ratio + public float _RaytracingIntensityClamp; + // Flag that tracks if ray counting is enabled + public int _RayCountEnabled; + // Flag that tracks if a ray traced signal should be pre-exposed + public int _RaytracingPreExposition; + // Near plane distance of the camera used for ray tracing + public float _RaytracingCameraNearPlane; + // Angle of a pixel (used for texture filtering) + public float _RaytracingPixelSpreadAngle; + // Flag that tracks if only diffuse lighting should be computed + public uint _RaytracingDiffuseRay; + // Ray traced reflection Data + public float _RaytracingReflectionMinSmoothness; + public float _RaytracingReflectionSmoothnessFadeStart; + public int _RaytracingIncludeSky; + // Path tracing parameters + public int _RaytracingMinRecursion; + public int _RaytracingMaxRecursion; + } +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.hlsl new file mode 100644 index 00000000000..091cc63a53e --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.hlsl @@ -0,0 +1,28 @@ +// +// This file was automatically generated. Please don't edit by hand. +// + +#ifndef SHADERVARIABLESRAYTRACING_CS_HLSL +#define SHADERVARIABLESRAYTRACING_CS_HLSL +// Generated from UnityEngine.Rendering.HighDefinition.ShaderVariablesRaytracing +// PackingRules = Exact +GLOBAL_CBUFFER_START(ShaderVariablesRaytracing, b3) + float _RaytracingRayBias; + float _RaytracingRayMaxLength; + int _RaytracingNumSamples; + int _RaytracingSampleIndex; + float _RaytracingIntensityClamp; + int _RayCountEnabled; + int _RaytracingPreExposition; + float _RaytracingCameraNearPlane; + float _RaytracingPixelSpreadAngle; + uint _RaytracingDiffuseRay; + float _RaytracingReflectionMinSmoothness; + float _RaytracingReflectionSmoothnessFadeStart; + int _RaytracingIncludeSky; + int _RaytracingMinRecursion; + int _RaytracingMaxRecursion; +CBUFFER_END + + +#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.hlsl.meta new file mode 100644 index 00000000000..00fcd01f23d --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.hlsl.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 97464d610af37e74bac6dd66d1532218 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.meta b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.meta new file mode 100644 index 00000000000..0ce94c1a611 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2103ac3cc7c4e9b429bc457a4bf0f8db +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.hlsl index 239acf7d27f..9ff1710085d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.hlsl @@ -1,40 +1,10 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRayTracingManager.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracing.cs.hlsl" // The target acceleration acceleration structure should only be defined for non compute shaders #ifndef SHADER_STAGE_COMPUTE GLOBAL_RESOURCE(RaytracingAccelerationStructure, _RaytracingAccelerationStructure, RAY_TRACING_ACCELERATION_STRUCTURE_REGISTER); #endif -GLOBAL_CBUFFER_START(UnityRayTracingGlobals, UNITY_RAY_TRACING_GLOBAL_CBUFFER_REGISTER) - // Global ray bias used for all trace rays - float _RaytracingRayBias; - // Maximal ray length for trace ray (in case an other one does not override it) - float _RaytracingRayMaxLength; - // Number of samples that will be used to evaluate an effect - int _RaytracingNumSamples; - // Index of the current sample - int _RaytracingSampleIndex; - // Value used to clamp the intensity of the signal to reduce the signal/noise ratio - float _RaytracingIntensityClamp; - // Flag that tracks if ray counting is enabled - int _RayCountEnabled; - // Flag that tracks if a ray traced signal should be pre-exposed - int _RaytracingPreExposition; - // Near plane distance of the camera used for ray tracing - float _RaytracingCameraNearPlane; - // Angle of a pixel (used for texture filtering) - float _RaytracingPixelSpreadAngle; - // Flag that tracks if only diffuse lighting should be computed - uint _RaytracingDiffuseRay; - // Ray traced reflection Data - float _RaytracingReflectionMaxDistance; - float _RaytracingReflectionMinSmoothness; - float _RaytracingReflectionSmoothnessFadeStart; - int _RaytracingIncludeSky; - // Path tracing parameters - int _RaytracingMinRecursion; - int _RaytracingMaxRecursion; -CBUFFER_END - RW_TEXTURE2D_ARRAY(uint, _RayCountTexture); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index 2c987bfc6b2..b21bbef9c1f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -6,6 +6,7 @@ enum ConstantRegister Global = 0, XR = 1, PBRSky = 2, + RayTracing = 3, RayTracingLightLoop = 4, } From b1ccff995c32332e9d0434453136076715c938ec Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 26 Mar 2020 11:14:50 +0100 Subject: [PATCH 65/92] Removed obsolete comment --- .../Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index f7c80313897..010ba9d99fb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -327,9 +327,6 @@ TextureHandle RenderSSR( RenderGraph renderGraph, } } - // TODO RENDERGRAPH - //cmd.SetGlobalInt(HDShaderIDs._UseRayTracedReflections, usesRaytracedReflections ? 1 : 0); - PushFullScreenDebugTexture(renderGraph, result, FullScreenDebugMode.ScreenSpaceReflections); return result; } From fdca8020a46960d15eb06d69a5eff137469dc7a7 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 26 Mar 2020 12:04:28 +0100 Subject: [PATCH 66/92] Post merge fix --- .../Runtime/RenderPipeline/HDRenderPipeline.cs | 7 ++++++- .../Runtime/RenderPipeline/HDStringConstants.cs | 13 ++++++------- .../Raytracing/HDRaytracingRecursiveRenderer.cs | 1 - .../Runtime/ShaderLibrary/ShaderVariablesGlobal.cs | 2 +- .../ShaderLibrary/ShaderVariablesGlobal.cs.hlsl | 2 +- 5 files changed, 14 insertions(+), 11 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 42958ad8c6c..58acc24fb54 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -1009,15 +1009,20 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) m_ShaderVariablesGlobalCB._RaytracingFrameIndex = RayTracingFrameIndex(hdCamera); if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) { - var settings = hdCamera.volumeStack.GetComponent(); + // Check if recursive rendering is enabled or not. This will control the cull of primitive + // during the gbuffer and forward pass + RecursiveRendering recursiveSettings = hdCamera.volumeStack.GetComponent(); + ScreenSpaceReflection settings = hdCamera.volumeStack.GetComponent(); bool usesRaytracedReflections = hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value; m_ShaderVariablesGlobalCB._UseRayTracedReflections = usesRaytracedReflections ? 1 : 0; m_ShaderVariablesGlobalCB._RaytracedIndirectDiffuse = ValidIndirectDiffuseState(hdCamera) ? 1 : 0; + m_ShaderVariablesGlobalCB._EnableRecursiveRayTracing = recursiveSettings.enable.value ? 1u : 0u; } else { m_ShaderVariablesGlobalCB._UseRayTracedReflections = 0; m_ShaderVariablesGlobalCB._RaytracedIndirectDiffuse = 0; + m_ShaderVariablesGlobalCB._EnableRecursiveRayTracing = 0; } ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 9209d1b497e..a74fd71b921 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -46,7 +46,7 @@ static class HDShaderPassNames public static readonly ShaderTagId s_TransparentDepthPrepassName = new ShaderTagId(s_TransparentDepthPrepassStr); public static readonly ShaderTagId s_TransparentBackfaceName = new ShaderTagId(s_TransparentBackfaceStr); public static readonly ShaderTagId s_TransparentDepthPostpassName = new ShaderTagId(s_TransparentDepthPostpassStr); - public static readonly ShaderTagId s_RayTracingPrepassName = new ShaderTagId(s_RayTracingPrepassStr); + public static readonly ShaderTagId s_RayTracingPrepassName = new ShaderTagId(s_RayTracingPrepassStr); public static readonly ShaderTagId s_MeshDecalsMName = new ShaderTagId(s_MeshDecalsMStr); public static readonly ShaderTagId s_MeshDecalsSName = new ShaderTagId(s_MeshDecalsSStr); public static readonly ShaderTagId s_MeshDecalsMSName = new ShaderTagId(s_MeshDecalsMSStr); @@ -253,7 +253,7 @@ static class HDShaderIDs public static readonly int _ColorTextureMS = Shader.PropertyToID("_ColorTextureMS"); public static readonly int _DepthTextureMS = Shader.PropertyToID("_DepthTextureMS"); public static readonly int _NormalTextureMS = Shader.PropertyToID("_NormalTextureMS"); - public static readonly int _RaytracePrepassBufferMS = Shader.PropertyToID("_RaytracePrepassBufferMS"); + public static readonly int _RaytracePrepassBufferMS = Shader.PropertyToID("_RaytracePrepassBufferMS"); public static readonly int _MotionVectorTextureMS = Shader.PropertyToID("_MotionVectorTextureMS"); public static readonly int _CameraDepthValuesTexture = Shader.PropertyToID("_CameraDepthValues"); @@ -295,7 +295,7 @@ static class HDShaderIDs public static readonly int _SSSBufferTexture = Shader.PropertyToID("_SSSBufferTexture"); public static readonly int _NormalBufferTexture = Shader.PropertyToID("_NormalBufferTexture"); - public static readonly int _RaytracePrepassBufferTexture = Shader.PropertyToID("_RaytracePrepassBufferTexture"); + public static readonly int _RaytracePrepassBufferTexture = Shader.PropertyToID("_RaytracePrepassBufferTexture"); public static readonly int _SsrIterLimit = Shader.PropertyToID("_SsrIterLimit"); public static readonly int _SsrThicknessScale = Shader.PropertyToID("_SsrThicknessScale"); @@ -466,7 +466,6 @@ static class HDShaderIDs public static readonly int _RaytracingSampleIndex = Shader.PropertyToID("_RaytracingSampleIndex"); public static readonly int _RaytracingRayMaxLength = Shader.PropertyToID("_RaytracingRayMaxLength"); public static readonly int _PixelSpreadAngleTangent = Shader.PropertyToID("_PixelSpreadAngleTangent"); - public static readonly int _EnableRecursiveRayTracing = Shader.PropertyToID("_EnableRecursiveRayTracing"); public static readonly int _RaytracingPixelSpreadAngle = Shader.PropertyToID("_RaytracingPixelSpreadAngle"); public static readonly string _RaytracingAccelerationStructureName = "_RaytracingAccelerationStructure"; @@ -505,7 +504,7 @@ static class HDShaderIDs public static readonly int _VelocityBuffer = Shader.PropertyToID("_VelocityBuffer"); public static readonly int _ShadowFilterMapping = Shader.PropertyToID("_ShadowFilterMapping"); public static readonly int _DistanceTexture = Shader.PropertyToID("_DistanceTexture"); - + // Reflections public static readonly int _ReflectionHistorybufferRW = Shader.PropertyToID("_ReflectionHistorybufferRW"); public static readonly int _CurrentFrameTexture = Shader.PropertyToID("_CurrentFrameTexture"); @@ -530,7 +529,7 @@ static class HDShaderIDs public static readonly int _RaytracedAreaShadowIntegration = Shader.PropertyToID("_RaytracedAreaShadowIntegration"); public static readonly int _RaytracingDirectionBuffer = Shader.PropertyToID("_RaytracingDirectionBuffer"); public static readonly int _RaytracingDistanceBuffer = Shader.PropertyToID("_RaytracingDistanceBuffer"); - public static readonly int _RaytracingDistanceBufferRW = Shader.PropertyToID("_RaytracingDistanceBufferRW"); + public static readonly int _RaytracingDistanceBufferRW = Shader.PropertyToID("_RaytracingDistanceBufferRW"); public static readonly int _AreaShadowTexture = Shader.PropertyToID("_AreaShadowTexture"); public static readonly int _AreaShadowTextureRW = Shader.PropertyToID("_AreaShadowTextureRW"); public static readonly int _ScreenSpaceShadowsTextureRW = Shader.PropertyToID("_ScreenSpaceShadowsTextureRW"); @@ -797,7 +796,7 @@ static class HDMaterialProperties public const string kStencilRefMV = "_StencilRefMV"; public const string kStencilWriteMaskMV = "_StencilWriteMaskMV"; public const string kStencilRefDistortionVec = "_StencilRefDistortionVec"; - public const string kStencilWriteMaskDistortionVec = "_StencilWriteMaskDistortionVec"; + public const string kStencilWriteMaskDistortionVec = "_StencilWriteMaskDistortionVec"; public const string kUseSplitLighting = "_RequireSplitLighting"; public const string kZWrite = "_ZWrite"; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs index 53516b4e16f..cb22fa84fb5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs @@ -110,7 +110,6 @@ void RaytracingRecursiveRender(HDCamera hdCamera, CommandBuffer cmd, ScriptableR // Note: Just in case, we rebind the directional light data (in case they were not) cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, m_LightLoopLightData.directionalLightData); - cmd.SetGlobalInt(HDShaderIDs._DirectionalLightCount, m_lightList.directionalLights.Count); // Set the data for the ray miss cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._SkyTexture, m_SkyManager.GetSkyReflection(hdCamera)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index c212e914b02..688101dc5f3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -231,6 +231,6 @@ unsafe struct ShaderVariablesGlobal public int _RaytracedIndirectDiffuse; // Uniform variables that defines if we should be using the raytraced indirect diffuse public int _UseRayTracedReflections; public int _RaytracingFrameIndex; // Index of the current frame [0, 7] - public float _Pad7; + public uint _EnableRecursiveRayTracing; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 4b69b687da5..b12e3da66cb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -128,7 +128,7 @@ GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) int _RaytracedIndirectDiffuse; int _UseRayTracedReflections; int _RaytracingFrameIndex; - float _Pad7; + uint _EnableRecursiveRayTracing; CBUFFER_END From bca3833636760ae91f873c7746170850728dbe7a Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 2 Apr 2020 13:22:26 +0200 Subject: [PATCH 67/92] Post merge fix --- .../SubsurfaceScattering/SubsurfaceScatteringManager.cs | 2 -- .../Runtime/RenderPipeline/HDStringConstants.cs | 4 ---- 2 files changed, 6 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index 4359234258c..1d0c61a2653 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -219,7 +219,6 @@ struct SubsurfaceScatteringParameters public int numTilesX; public int numTilesY; public int numTilesZ; - public Vector4[] filterKernels; public ComputeBuffer coarseStencilBuffer; } @@ -426,7 +425,6 @@ void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle c // However, the compute can't output and MSAA target so we blend the non-MSAA target into the MSAA one. static void RenderSubsurfaceScattering(in SubsurfaceScatteringParameters parameters, in SubsurfaceScatteringResources resources, CommandBuffer cmd) { - cmd.SetComputeVectorArrayParam(parameters.subsurfaceScatteringCS, HDShaderIDs._FilterKernels, parameters.filterKernels); cmd.SetComputeIntParam(parameters.subsurfaceScatteringCS, HDShaderIDs._SssSampleBudget, parameters.sampleBudget); cmd.SetComputeTextureParam(parameters.subsurfaceScatteringCS, parameters.subsurfaceScatteringCSKernel, HDShaderIDs._DepthTexture, resources.depthTexture); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 52d196d8799..535d7613a23 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -373,10 +373,6 @@ static class HDShaderIDs public static readonly int _BlitPaddingSize = Shader.PropertyToID("_BlitPaddingSize"); public static readonly int _BlitTexArraySlice = Shader.PropertyToID("_BlitTexArraySlice"); - public static readonly int _FilterKernels = Shader.PropertyToID("_FilterKernels"); - public static readonly int _FilterKernelsBasic = Shader.PropertyToID("_FilterKernelsBasic"); - public static readonly int _HalfRcpWeightedVariances = Shader.PropertyToID("_HalfRcpWeightedVariances"); - public static readonly int _CameraDepthTexture = Shader.PropertyToID("_CameraDepthTexture"); public static readonly int _CameraMotionVectorsTexture = Shader.PropertyToID("_CameraMotionVectorsTexture"); public static readonly int _FullScreenDebugMode = Shader.PropertyToID("_FullScreenDebugMode"); From 3b1015772a30797c54522a3a8167e94f72c1fbd6 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 2 Apr 2020 13:26:15 +0200 Subject: [PATCH 68/92] Post merge fix 2 --- ...airGraphBackThenFrontRendering.shadergraph | 23 +++++++++++-------- .../LightLoop/lightlistbuild-bigtile.compute | 2 +- .../lightlistbuild-clustered.compute | 2 +- .../ShaderLibrary/ShaderVariables.hlsl | 2 +- .../ShaderLibrary/ShaderVariablesGlobal.hlsl | 2 ++ 5 files changed, 18 insertions(+), 13 deletions(-) diff --git a/TestProjects/HDRP_Tests/Assets/GraphicTests/Scenes/8x_ShaderGraph/8105_BlendStates/HairGraph/HairGraphBackThenFrontRendering.shadergraph b/TestProjects/HDRP_Tests/Assets/GraphicTests/Scenes/8x_ShaderGraph/8105_BlendStates/HairGraph/HairGraphBackThenFrontRendering.shadergraph index 3667ae60a78..c803731507b 100644 --- a/TestProjects/HDRP_Tests/Assets/GraphicTests/Scenes/8x_ShaderGraph/8105_BlendStates/HairGraph/HairGraphBackThenFrontRendering.shadergraph +++ b/TestProjects/HDRP_Tests/Assets/GraphicTests/Scenes/8x_ShaderGraph/8105_BlendStates/HairGraph/HairGraphBackThenFrontRendering.shadergraph @@ -2,32 +2,34 @@ "m_SerializedProperties": [ { "typeInfo": { - "fullName": "UnityEditor.ShaderGraph.ColorShaderProperty" + "fullName": "UnityEditor.ShaderGraph.Internal.ColorShaderProperty" }, - "JSONnodeData": "{\n \"m_Name\": \"Color\",\n \"m_GeneratePropertyBlock\": true,\n \"m_Guid\": {\n \"m_GuidSerialized\": \"2971aabd-a98b-48ee-9c11-53d995a62524\"\n },\n \"m_DefaultReferenceName\": \"Color_5381F0F4\",\n \"m_OverrideReferenceName\": \"_Color\",\n \"m_Value\": {\n \"r\": 1.0,\n \"g\": 0.0,\n \"b\": 0.0,\n \"a\": 1.0\n },\n \"m_ColorMode\": 0,\n \"m_Hidden\": false\n}" + "JSONnodeData": "{\n \"m_Guid\": {\n \"m_GuidSerialized\": \"2971aabd-a98b-48ee-9c11-53d995a62524\"\n },\n \"m_Name\": \"Color\",\n \"m_DefaultReferenceName\": \"Color_5381F0F4\",\n \"m_OverrideReferenceName\": \"_Color\",\n \"m_GeneratePropertyBlock\": true,\n \"m_Precision\": 0,\n \"m_GPUInstanced\": false,\n \"m_Hidden\": false,\n \"m_Value\": {\n \"r\": 1.0,\n \"g\": 0.0,\n \"b\": 0.0,\n \"a\": 1.0\n },\n \"m_ColorMode\": 0\n}" } ], + "m_SerializedKeywords": [], "m_SerializableNodes": [ { "typeInfo": { - "fullName": "UnityEditor.Experimental.Rendering.HDPipeline.HairMasterNode" + "fullName": "UnityEditor.ShaderGraph.PropertyNode" }, - "JSONnodeData": "{\n \"m_GuidSerialized\": \"b718f756-342e-4a56-a1e2-4a0632af185e\",\n \"m_GroupGuidSerialized\": \"00000000-0000-0000-0000-000000000000\",\n \"m_Name\": \"Hair Master\",\n \"m_DrawState\": {\n \"m_Expanded\": true,\n \"m_Position\": {\n \"serializedVersion\": \"2\",\n \"x\": 0.0,\n \"y\": 0.0,\n \"width\": 0.0,\n \"height\": 0.0\n }\n },\n \"m_SerializableSlots\": [\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.PositionMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 0,\\n \\\"m_DisplayName\\\": \\\"Position\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Position\\\",\\n \\\"m_StageCapability\\\": 1,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_Space\\\": 0\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.ColorRGBMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 1,\\n \\\"m_DisplayName\\\": \\\"DiffuseColor\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Albedo\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.7353569269180298,\\n \\\"y\\\": 0.7353569269180298,\\n \\\"z\\\": 0.7353569269180298\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_ColorMode\\\": 0\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.NormalMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 2,\\n \\\"m_DisplayName\\\": \\\"Normal\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Normal\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_Space\\\": 3\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.NormalMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 4,\\n \\\"m_DisplayName\\\": \\\"BentNormal\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"BentNormal\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_Space\\\": 3\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 9,\\n \\\"m_DisplayName\\\": \\\"Smoothness\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Smoothness\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": 0.5,\\n \\\"m_DefaultValue\\\": 0.5,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 10,\\n \\\"m_DisplayName\\\": \\\"AmbientOcclusion\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Occlusion\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": 1.0,\\n \\\"m_DefaultValue\\\": 1.0,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector3MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 7,\\n \\\"m_DisplayName\\\": \\\"Transmittance\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Transmittance\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.30000001192092898,\\n \\\"y\\\": 0.19500000774860383,\\n \\\"z\\\": 0.09000000357627869\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 8,\\n \\\"m_DisplayName\\\": \\\"RimTransmissionIntensity\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"RimTransmissionIntensity\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": 0.20000000298023225,\\n \\\"m_DefaultValue\\\": 0.20000000298023225,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector3MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 5,\\n \\\"m_DisplayName\\\": \\\"HairStrandDirection\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"HairStrandDirection\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": -1.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 12,\\n \\\"m_DisplayName\\\": \\\"Alpha\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Alpha\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": 1.0,\\n \\\"m_DefaultValue\\\": 1.0,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.ColorRGBMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 18,\\n \\\"m_DisplayName\\\": \\\"SpecularTint\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"SpecularTint\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 1.0,\\n \\\"y\\\": 1.0,\\n \\\"z\\\": 1.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_ColorMode\\\": 0\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 19,\\n \\\"m_DisplayName\\\": \\\"SpecularShift\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"SpecularShift\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": 0.10000000149011612,\\n \\\"m_DefaultValue\\\": 0.10000000149011612,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.ColorRGBMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 20,\\n \\\"m_DisplayName\\\": \\\"SecondarySpecularTint\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"SecondarySpecularTint\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.5,\\n \\\"y\\\": 0.5,\\n \\\"z\\\": 0.5\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_ColorMode\\\": 0\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 21,\\n \\\"m_DisplayName\\\": \\\"SecondarySmoothness\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"SecondarySmoothness\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": 0.5,\\n \\\"m_DefaultValue\\\": 0.5,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 22,\\n \\\"m_DisplayName\\\": \\\"SecondarySpecularShift\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"SecondarySpecularShift\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": -0.10000000149011612,\\n \\\"m_DefaultValue\\\": -0.10000000149011612,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n }\n ],\n \"m_PreviewExpanded\": true,\n \"m_SerializableSubShaders\": [\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.Experimental.Rendering.HDPipeline.HairSubShader\"\n },\n \"JSONnodeData\": \"{}\"\n }\n ],\n \"m_SurfaceType\": 1,\n \"m_AlphaMode\": 0,\n \"m_BlendPreserveSpecular\": true,\n \"m_TransparencyFog\": true,\n \"m_AlphaTest\": false,\n \"m_AlphaTestDepthPrepass\": false,\n \"m_AlphaTestDepthPostpass\": false,\n \"m_TransparentWritesMotionVec\": false,\n \"m_AlphaTestShadow\": false,\n \"m_BackThenFrontRendering\": true,\n \"m_SortPriority\": 0,\n \"m_DoubleSidedMode\": 0,\n \"m_MaterialType\": 0,\n \"m_ReceiveDecals\": true,\n \"m_ReceivesSSR\": true,\n \"m_UseLightFacingNormal\": false,\n \"m_SpecularAA\": false,\n \"m_SpecularAAScreenSpaceVariance\": 0.0,\n \"m_SpecularAAThreshold\": 0.0,\n \"m_SpecularOcclusionMode\": 0,\n \"m_overrideBakedGI\": false,\n \"m_depthOffset\": false,\n \"m_ZWrite\": false,\n \"m_transparentCullMode\": 2,\n \"m_ZTest\": 4\n}" + "JSONnodeData": "{\n \"m_GuidSerialized\": \"44caf900-a073-48b5-9fac-9c6c60ad6197\",\n \"m_GroupGuidSerialized\": \"00000000-0000-0000-0000-000000000000\",\n \"m_Name\": \"Property\",\n \"m_NodeVersion\": 0,\n \"m_DrawState\": {\n \"m_Expanded\": true,\n \"m_Position\": {\n \"serializedVersion\": \"2\",\n \"x\": -389.0,\n \"y\": 66.0,\n \"width\": 100.0,\n \"height\": 34.0\n }\n },\n \"m_SerializableSlots\": [\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector4MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 0,\\n \\\"m_DisplayName\\\": \\\"Color\\\",\\n \\\"m_SlotType\\\": 1,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Out\\\",\\n \\\"m_StageCapability\\\": 3,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0,\\n \\\"w\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0,\\n \\\"w\\\": 0.0\\n }\\n}\"\n }\n ],\n \"m_Precision\": 0,\n \"m_PreviewExpanded\": true,\n \"m_CustomColors\": {\n \"m_SerializableColors\": []\n },\n \"m_PropertyGuidSerialized\": \"2971aabd-a98b-48ee-9c11-53d995a62524\"\n}" }, { "typeInfo": { - "fullName": "UnityEditor.ShaderGraph.PropertyNode" + "fullName": "UnityEditor.ShaderGraph.SplitNode" }, - "JSONnodeData": "{\n \"m_GuidSerialized\": \"44caf900-a073-48b5-9fac-9c6c60ad6197\",\n \"m_GroupGuidSerialized\": \"00000000-0000-0000-0000-000000000000\",\n \"m_Name\": \"Property\",\n \"m_DrawState\": {\n \"m_Expanded\": true,\n \"m_Position\": {\n \"serializedVersion\": \"2\",\n \"x\": -389.0,\n \"y\": 66.0,\n \"width\": 100.0,\n \"height\": 34.0\n }\n },\n \"m_SerializableSlots\": [\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector4MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 0,\\n \\\"m_DisplayName\\\": \\\"Color\\\",\\n \\\"m_SlotType\\\": 1,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Out\\\",\\n \\\"m_StageCapability\\\": 3,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0,\\n \\\"w\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0,\\n \\\"w\\\": 0.0\\n }\\n}\"\n }\n ],\n \"m_PreviewExpanded\": true,\n \"m_PropertyGuidSerialized\": \"2971aabd-a98b-48ee-9c11-53d995a62524\"\n}" + "JSONnodeData": "{\n \"m_GuidSerialized\": \"670d6270-0cd3-4fe7-9861-015c0c0fa774\",\n \"m_GroupGuidSerialized\": \"00000000-0000-0000-0000-000000000000\",\n \"m_Name\": \"Split\",\n \"m_NodeVersion\": 0,\n \"m_DrawState\": {\n \"m_Expanded\": true,\n \"m_Position\": {\n \"serializedVersion\": \"2\",\n \"x\": -272.0,\n \"y\": 147.0,\n \"width\": 114.0,\n \"height\": 149.0\n }\n },\n \"m_SerializableSlots\": [\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.DynamicVectorMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 0,\\n \\\"m_DisplayName\\\": \\\"In\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"In\\\",\\n \\\"m_StageCapability\\\": 3,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0,\\n \\\"w\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0,\\n \\\"w\\\": 0.0\\n }\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 1,\\n \\\"m_DisplayName\\\": \\\"R\\\",\\n \\\"m_SlotType\\\": 1,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"R\\\",\\n \\\"m_StageCapability\\\": 3,\\n \\\"m_Value\\\": 0.0,\\n \\\"m_DefaultValue\\\": 0.0,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 2,\\n \\\"m_DisplayName\\\": \\\"G\\\",\\n \\\"m_SlotType\\\": 1,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"G\\\",\\n \\\"m_StageCapability\\\": 3,\\n \\\"m_Value\\\": 0.0,\\n \\\"m_DefaultValue\\\": 0.0,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 3,\\n \\\"m_DisplayName\\\": \\\"B\\\",\\n \\\"m_SlotType\\\": 1,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"B\\\",\\n \\\"m_StageCapability\\\": 3,\\n \\\"m_Value\\\": 0.0,\\n \\\"m_DefaultValue\\\": 0.0,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 4,\\n \\\"m_DisplayName\\\": \\\"A\\\",\\n \\\"m_SlotType\\\": 1,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"A\\\",\\n \\\"m_StageCapability\\\": 3,\\n \\\"m_Value\\\": 0.0,\\n \\\"m_DefaultValue\\\": 0.0,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n }\n ],\n \"m_Precision\": 0,\n \"m_PreviewExpanded\": true,\n \"m_CustomColors\": {\n \"m_SerializableColors\": []\n }\n}" }, { "typeInfo": { - "fullName": "UnityEditor.ShaderGraph.SplitNode" + "fullName": "UnityEditor.Rendering.HighDefinition.HairMasterNode" }, - "JSONnodeData": "{\n \"m_GuidSerialized\": \"670d6270-0cd3-4fe7-9861-015c0c0fa774\",\n \"m_GroupGuidSerialized\": \"00000000-0000-0000-0000-000000000000\",\n \"m_Name\": \"Split\",\n \"m_DrawState\": {\n \"m_Expanded\": true,\n \"m_Position\": {\n \"serializedVersion\": \"2\",\n \"x\": -272.0,\n \"y\": 147.0,\n \"width\": 114.0,\n \"height\": 149.0\n }\n },\n \"m_SerializableSlots\": [\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.DynamicVectorMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 0,\\n \\\"m_DisplayName\\\": \\\"In\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"In\\\",\\n \\\"m_StageCapability\\\": 3,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0,\\n \\\"w\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0,\\n \\\"w\\\": 0.0\\n }\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 1,\\n \\\"m_DisplayName\\\": \\\"R\\\",\\n \\\"m_SlotType\\\": 1,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"R\\\",\\n \\\"m_StageCapability\\\": 3,\\n \\\"m_Value\\\": 0.0,\\n \\\"m_DefaultValue\\\": 0.0,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 2,\\n \\\"m_DisplayName\\\": \\\"G\\\",\\n \\\"m_SlotType\\\": 1,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"G\\\",\\n \\\"m_StageCapability\\\": 3,\\n \\\"m_Value\\\": 0.0,\\n \\\"m_DefaultValue\\\": 0.0,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 3,\\n \\\"m_DisplayName\\\": \\\"B\\\",\\n \\\"m_SlotType\\\": 1,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"B\\\",\\n \\\"m_StageCapability\\\": 3,\\n \\\"m_Value\\\": 0.0,\\n \\\"m_DefaultValue\\\": 0.0,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 4,\\n \\\"m_DisplayName\\\": \\\"A\\\",\\n \\\"m_SlotType\\\": 1,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"A\\\",\\n \\\"m_StageCapability\\\": 3,\\n \\\"m_Value\\\": 0.0,\\n \\\"m_DefaultValue\\\": 0.0,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n }\n ],\n \"m_PreviewExpanded\": true\n}" + "JSONnodeData": "{\n \"m_GuidSerialized\": \"b718f756-342e-4a56-a1e2-4a0632af185e\",\n \"m_GroupGuidSerialized\": \"00000000-0000-0000-0000-000000000000\",\n \"m_Name\": \"Hair Master\",\n \"m_NodeVersion\": 0,\n \"m_DrawState\": {\n \"m_Expanded\": true,\n \"m_Position\": {\n \"serializedVersion\": \"2\",\n \"x\": 0.0,\n \"y\": 0.0,\n \"width\": 0.0,\n \"height\": 0.0\n }\n },\n \"m_SerializableSlots\": [\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.PositionMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 0,\\n \\\"m_DisplayName\\\": \\\"Vertex Position\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Vertex Position\\\",\\n \\\"m_StageCapability\\\": 1,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_Space\\\": 0\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.NormalMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 27,\\n \\\"m_DisplayName\\\": \\\"Vertex Normal\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Vertex Normal\\\",\\n \\\"m_StageCapability\\\": 1,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_Space\\\": 0\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.TangentMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 28,\\n \\\"m_DisplayName\\\": \\\"Vertex Tangent\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Vertex Tangent\\\",\\n \\\"m_StageCapability\\\": 1,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_Space\\\": 0\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.ColorRGBMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 1,\\n \\\"m_DisplayName\\\": \\\"DiffuseColor\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Albedo\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.7353569269180298,\\n \\\"y\\\": 0.7353569269180298,\\n \\\"z\\\": 0.7353569269180298\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_ColorMode\\\": 0\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.NormalMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 2,\\n \\\"m_DisplayName\\\": \\\"Normal\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Normal\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_Space\\\": 3\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.NormalMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 4,\\n \\\"m_DisplayName\\\": \\\"BentNormal\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"BentNormal\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_Space\\\": 3\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 9,\\n \\\"m_DisplayName\\\": \\\"Smoothness\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Smoothness\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": 0.5,\\n \\\"m_DefaultValue\\\": 0.5,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 10,\\n \\\"m_DisplayName\\\": \\\"AmbientOcclusion\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Occlusion\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": 1.0,\\n \\\"m_DefaultValue\\\": 1.0,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector3MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 7,\\n \\\"m_DisplayName\\\": \\\"Transmittance\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Transmittance\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.30000001192092898,\\n \\\"y\\\": 0.19500000774860383,\\n \\\"z\\\": 0.09000000357627869\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 8,\\n \\\"m_DisplayName\\\": \\\"RimTransmissionIntensity\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"RimTransmissionIntensity\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": 0.20000000298023225,\\n \\\"m_DefaultValue\\\": 0.20000000298023225,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector3MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 5,\\n \\\"m_DisplayName\\\": \\\"HairStrandDirection\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"HairStrandDirection\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": -1.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 12,\\n \\\"m_DisplayName\\\": \\\"Alpha\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"Alpha\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": 1.0,\\n \\\"m_DefaultValue\\\": 1.0,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.ColorRGBMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 18,\\n \\\"m_DisplayName\\\": \\\"SpecularTint\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"SpecularTint\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 1.0,\\n \\\"y\\\": 1.0,\\n \\\"z\\\": 1.0\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_ColorMode\\\": 0\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 19,\\n \\\"m_DisplayName\\\": \\\"SpecularShift\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"SpecularShift\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": 0.10000000149011612,\\n \\\"m_DefaultValue\\\": 0.10000000149011612,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.ColorRGBMaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 20,\\n \\\"m_DisplayName\\\": \\\"SecondarySpecularTint\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"SecondarySpecularTint\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": {\\n \\\"x\\\": 0.5,\\n \\\"y\\\": 0.5,\\n \\\"z\\\": 0.5\\n },\\n \\\"m_DefaultValue\\\": {\\n \\\"x\\\": 0.0,\\n \\\"y\\\": 0.0,\\n \\\"z\\\": 0.0\\n },\\n \\\"m_Labels\\\": [\\n \\\"X\\\",\\n \\\"Y\\\",\\n \\\"Z\\\"\\n ],\\n \\\"m_ColorMode\\\": 0\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 21,\\n \\\"m_DisplayName\\\": \\\"SecondarySmoothness\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"SecondarySmoothness\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": 0.5,\\n \\\"m_DefaultValue\\\": 0.5,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n },\n {\n \"typeInfo\": {\n \"fullName\": \"UnityEditor.ShaderGraph.Vector1MaterialSlot\"\n },\n \"JSONnodeData\": \"{\\n \\\"m_Id\\\": 22,\\n \\\"m_DisplayName\\\": \\\"SecondarySpecularShift\\\",\\n \\\"m_SlotType\\\": 0,\\n \\\"m_Priority\\\": 2147483647,\\n \\\"m_Hidden\\\": false,\\n \\\"m_ShaderOutputName\\\": \\\"SecondarySpecularShift\\\",\\n \\\"m_StageCapability\\\": 2,\\n \\\"m_Value\\\": -0.10000000149011612,\\n \\\"m_DefaultValue\\\": -0.10000000149011612,\\n \\\"m_Labels\\\": [\\n \\\"X\\\"\\n ]\\n}\"\n }\n ],\n \"m_Precision\": 0,\n \"m_PreviewExpanded\": true,\n \"m_CustomColors\": {\n \"m_SerializableColors\": []\n },\n \"m_SurfaceType\": 1,\n \"m_AlphaMode\": 0,\n \"m_BlendPreserveSpecular\": true,\n \"m_TransparencyFog\": true,\n \"m_AlphaTest\": false,\n \"m_AlphaToMask\": false,\n \"m_AlphaTestDepthPrepass\": false,\n \"m_AlphaTestDepthPostpass\": false,\n \"m_TransparentWritesMotionVec\": false,\n \"m_AlphaTestShadow\": false,\n \"m_BackThenFrontRendering\": true,\n \"m_SortPriority\": 0,\n \"m_DoubleSidedMode\": 0,\n \"m_MaterialType\": 0,\n \"m_ReceiveDecals\": true,\n \"m_ReceivesSSR\": true,\n \"m_AddPrecomputedVelocity\": false,\n \"m_UseLightFacingNormal\": false,\n \"m_SpecularAA\": false,\n \"m_SpecularAAScreenSpaceVariance\": 0.0,\n \"m_SpecularAAThreshold\": 0.0,\n \"m_SpecularOcclusionMode\": 0,\n \"m_overrideBakedGI\": false,\n \"m_depthOffset\": false,\n \"m_ZWrite\": false,\n \"m_transparentCullMode\": 2,\n \"m_ZTest\": 4,\n \"m_SupportLodCrossFade\": false,\n \"m_DOTSInstancing\": false,\n \"m_MaterialNeedsUpdateHash\": 3,\n \"m_ShaderGUIOverride\": \"\",\n \"m_OverrideEnabled\": false\n}" } ], "m_Groups": [], + "m_StickyNotes": [], "m_SerializableEdges": [ { "typeInfo": { @@ -39,13 +41,13 @@ "typeInfo": { "fullName": "UnityEditor.Graphing.Edge" }, - "JSONnodeData": "{\n \"m_OutputSlot\": {\n \"m_SlotId\": 4,\n \"m_NodeGUIDSerialized\": \"670d6270-0cd3-4fe7-9861-015c0c0fa774\"\n },\n \"m_InputSlot\": {\n \"m_SlotId\": 12,\n \"m_NodeGUIDSerialized\": \"b718f756-342e-4a56-a1e2-4a0632af185e\"\n }\n}" + "JSONnodeData": "{\n \"m_OutputSlot\": {\n \"m_SlotId\": 0,\n \"m_NodeGUIDSerialized\": \"44caf900-a073-48b5-9fac-9c6c60ad6197\"\n },\n \"m_InputSlot\": {\n \"m_SlotId\": 1,\n \"m_NodeGUIDSerialized\": \"b718f756-342e-4a56-a1e2-4a0632af185e\"\n }\n}" }, { "typeInfo": { "fullName": "UnityEditor.Graphing.Edge" }, - "JSONnodeData": "{\n \"m_OutputSlot\": {\n \"m_SlotId\": 0,\n \"m_NodeGUIDSerialized\": \"44caf900-a073-48b5-9fac-9c6c60ad6197\"\n },\n \"m_InputSlot\": {\n \"m_SlotId\": 1,\n \"m_NodeGUIDSerialized\": \"b718f756-342e-4a56-a1e2-4a0632af185e\"\n }\n}" + "JSONnodeData": "{\n \"m_OutputSlot\": {\n \"m_SlotId\": 4,\n \"m_NodeGUIDSerialized\": \"670d6270-0cd3-4fe7-9861-015c0c0fa774\"\n },\n \"m_InputSlot\": {\n \"m_SlotId\": 12,\n \"m_NodeGUIDSerialized\": \"b718f756-342e-4a56-a1e2-4a0632af185e\"\n }\n}" } ], "m_PreviewData": { @@ -55,5 +57,6 @@ } }, "m_Path": "Shader Graphs", + "m_ConcretePrecision": 0, "m_ActiveOutputNodeGuidSerialized": "b718f756-342e-4a56-a1e2-4a0632af185e" } \ No newline at end of file diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute index 4c57d8df412..aa9b402db5d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute @@ -3,7 +3,7 @@ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightingConvexHullUtils.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/SortingComputeUtils.hlsl" diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute index c3bf8ab4935..963ca59defe 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute @@ -15,7 +15,7 @@ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderBase.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightingConvexHullUtils.hlsl" diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl index a5e6fee36f2..aeb382dd305 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl @@ -10,7 +10,7 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/TextureXR.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" // CAUTION: // Currently the shaders compiler always include regualr Unity shaderVariables, so I get a conflict here were UNITY_SHADER_VARIABLES_INCLUDED is already define, this need to be fixed. diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl index 01e07bcc567..1571c0c7d0d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl @@ -26,4 +26,6 @@ #define RAY_TRACING_LIGHT_DATA_REGISTER t3 #define RAY_TRACING_ENV_LIGHT_DATA_REGISTER t4 +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl" + #endif // UNITY_SHADER_VARIABLES_GLOBAL_INCLUDED From 6cf20d836079064c39e624da49d418838155566b Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 2 Apr 2020 16:29:52 +0200 Subject: [PATCH 69/92] Double inclusion fix. --- .../Runtime/ShaderLibrary/ShaderVariables.hlsl | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl index aeb382dd305..4a129104259 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl @@ -6,10 +6,8 @@ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Version.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" -// This must be included first before we declare any global constant buffer and will onyl affect ray tracing shaders -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/TextureXR.hlsl" +// This must be included first before we declare any global constant buffer and will onyl affect ray tracing shaders #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" // CAUTION: From dfb7015f429c3f09f9aa203425995c325e22df73 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 3 Apr 2020 10:01:29 +0200 Subject: [PATCH 70/92] Fixed CB visibility --- .../Runtime/Common/ConstantBuffer.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs index 6a80e273a94..c0c013511ac 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs @@ -12,28 +12,28 @@ public class ConstantBuffer where CBType : struct ComputeBuffer m_GPUConstantBuffer = null; static ConstantBuffer m_TypedConstantBuffer = new ConstantBuffer(); - internal ConstantBuffer() + ConstantBuffer() { m_GPUConstantBuffer = new ComputeBuffer(1, UnsafeUtility.SizeOf(), ComputeBufferType.Constant); } - internal void UpdateDataInternal(CommandBuffer cmd, in CBType data) + void UpdateDataInternal(CommandBuffer cmd, in CBType data) { m_Data[0] = data; cmd.SetComputeBufferData(m_GPUConstantBuffer, m_Data); } - internal void SetGlobalInternal(CommandBuffer cmd, int shaderId) + void SetGlobalInternal(CommandBuffer cmd, int shaderId) { cmd.SetGlobalConstantBuffer(m_GPUConstantBuffer, shaderId, 0, m_GPUConstantBuffer.stride); } - internal void SetInternal(CommandBuffer cmd, ComputeShader cs, int shaderId) + void SetInternal(CommandBuffer cmd, ComputeShader cs, int shaderId) { cmd.SetComputeConstantBufferParam(cs, shaderId, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); } - internal void SetInternal(Material mat, int shaderId) + void SetInternal(Material mat, int shaderId) { // This isn't done via command buffer because as long as the buffer itself is not destroyed, // the binding stays valid. Only the commit of data needs to go through the command buffer. @@ -41,7 +41,7 @@ internal void SetInternal(Material mat, int shaderId) mat.SetConstantBuffer(shaderId, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); } - internal void Release() + void Release() { CoreUtils.SafeRelease(m_GPUConstantBuffer); } From 1d5e3e38c8ab6428570025a26197b896c2a76e55 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 3 Apr 2020 10:32:47 +0200 Subject: [PATCH 71/92] Fixed compilation after the merge --- .../Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl index cf25b4f3096..bdc2e64d12f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl @@ -5,8 +5,8 @@ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl" #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/VolumeRendering.hlsl" #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Sampling.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs.hlsl" TEXTURE2D(_GroundIrradianceTexture); From 0f14fe9db3f37110c1127abc5767468530e4b1ca Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 3 Apr 2020 10:44:44 +0200 Subject: [PATCH 72/92] Indentation fix --- .../Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 3ac9bf47f7b..9e31523d1ac 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -737,7 +737,7 @@ static void GetHexagonalClosePackedSpheres7(Vector2[] coords) struct VolumetricLightingParameters { public ComputeShader volumetricLightingCS; - public ComputeShader volumetricLightingFilteringCS; + public ComputeShader volumetricLightingFilteringCS; public int volumetricLightingKernel; public int volumetricFilteringKernelX; public int volumetricFilteringKernelY; From 1c0fae51c3912f61a9a4982f98a52aa9b1f61422 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 3 Apr 2020 10:52:09 +0200 Subject: [PATCH 73/92] Removed temporary comments. --- .../Runtime/ShaderLibrary/ShaderVariablesGlobal.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index a3022a95ddd..feb97583d13 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -47,7 +47,7 @@ unsafe struct ShaderVariablesGlobal #if !USING_STEREO_MATRICES public Vector3 _WorldSpaceCameraPos_Internal; public float _Pad0; - public Vector3 _PrevCamPosRWS_Internal; // $$$ + public Vector3 _PrevCamPosRWS_Internal; public float _Pad1; #endif public Vector4 _ScreenSize; // { w, h, 1 / w, 1 / h } @@ -84,7 +84,7 @@ unsafe struct ShaderVariablesGlobal // y = height // z = 1 + 1.0/width // w = 1 + 1.0/height - public Vector4 _ScreenParams; // $$$ used only by vfx? + public Vector4 _ScreenParams; [HLSLArray(6, typeof(Vector4))] public fixed float _FrustumPlanes[6 * 4]; // { (a, b, c) = N, d = -dot(N, P) } [L, R, T, B, N, F] From 56200ca2f071fe724b8f84a2440d354eda2942ba Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 3 Apr 2020 11:26:24 +0200 Subject: [PATCH 74/92] Moved some constants around. --- .../Runtime/ShaderLibrary/ShaderVariablesGlobal.cs | 8 ++++---- .../Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index feb97583d13..67da43aa6ff 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -156,20 +156,20 @@ unsafe struct ShaderVariablesGlobal public int _DirectionalShadowIndex; public uint _EnableLightLayers; - public float _ReplaceDiffuseForIndirect; public uint _EnableSkyReflection; public uint _EnableSSRefraction; - public float _MicroShadowOpacity; + public float _SSRefractionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback + public float _ColorPyramidLodCount; public float _DirectionalTransmissionMultiplier; public float _ProbeExposureScale; public float _ContactShadowOpacity; - public float _ColorPyramidLodCount; + public float _ReplaceDiffuseForIndirect; public Vector4 _AmbientOcclusionParam; // xyz occlusion color, w directLightStrenght public Vector4 _IndirectLightingMultiplier; // .x indirect diffuse multiplier (use with indirect lighting volume controler) - public float _SSRefractionInvScreenWeightDistance; // Distance for screen space smoothstep with fallback + public float _MicroShadowOpacity; public float _Pad3; public float _Pad4; public float _Pad5; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index a146d9ee009..00ac5a0cb3f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -79,17 +79,17 @@ GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) uint _CascadeShadowCount; int _DirectionalShadowIndex; uint _EnableLightLayers; - float _ReplaceDiffuseForIndirect; uint _EnableSkyReflection; uint _EnableSSRefraction; - float _MicroShadowOpacity; + float _SSRefractionInvScreenWeightDistance; + float _ColorPyramidLodCount; float _DirectionalTransmissionMultiplier; float _ProbeExposureScale; float _ContactShadowOpacity; - float _ColorPyramidLodCount; + float _ReplaceDiffuseForIndirect; float4 _AmbientOcclusionParam; float4 _IndirectLightingMultiplier; - float _SSRefractionInvScreenWeightDistance; + float _MicroShadowOpacity; float _Pad3; float _Pad4; float _Pad5; From 98d7b06937e327d0d5e32271157209e77970205c Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Mon, 6 Apr 2020 18:37:16 +0200 Subject: [PATCH 75/92] Post merge fix + Port ProbeVolume global variables to constant buffers. --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 71 +++-------- .../Lighting/LightLoop/LightLoop.cs.hlsl | 1 + .../ProbeVolume/ProbeVolumeLighting.cs | 119 ++++++++---------- .../ProbeVolumeShaderVariables.hlsl | 9 -- .../RenderPipeline/HDRenderPipeline.cs | 10 +- .../RenderPipeline/HDStringConstants.cs | 15 --- .../ShaderLibrary/ShaderVariablesGlobal.cs | 17 ++- .../ShaderVariablesGlobal.cs.hlsl | 12 +- 8 files changed, 104 insertions(+), 150 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index cddbcd5fd2c..a747b63cc00 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -233,6 +233,7 @@ unsafe struct ShaderVariablesLightList public int _DecalIndexShift; public int _DensityVolumeIndexShift; + public int _ProbeVolumeIndexShift; } internal struct ProcessedLightData @@ -2383,7 +2384,7 @@ void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu // Allocate a light data LightData lightData = new LightData(); - + // Punctual, area, projector lights - the rendering side. GetLightData(cmd, hdCamera, hdShadowSettings, light, lightComponent, in m_ProcessedLightData[lightIndex], shadowIndex, contactShadowScalableSetting, isRasterization: true, ref lightDimensions, ref m_ScreenSpaceShadowIndex, ref m_ScreenSpaceShadowChannelSlot, ref lightData); @@ -2763,11 +2764,6 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu } UpdateDataBuffers(); - - int probeVolumeIndexShift = (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.LightLoop) - ? (m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount + m_densityVolumeCount) - : 0; - cmd.SetGlobalInt(HDShaderIDs._ProbeVolumeIndexShift, probeVolumeIndexShift); } m_enableBakeShadowMask = m_enableBakeShadowMask && hdCamera.frameSettings.IsEnabled(FrameSettingsField.Shadowmask); @@ -3228,9 +3224,16 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera h cb._DecalIndexShift = m_lightList.lights.Count + m_lightList.envLights.Count; cb._DensityVolumeIndexShift = m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount; + int probeVolumeIndexShift = (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.LightLoop) + ? (m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount + m_densityVolumeCount) + : 0; + cb._ProbeVolumeIndexShift = probeVolumeIndexShift; + parameters.lightListCB = m_ShaderVariablesLightListCB; parameters.runLightList = m_TotalLightCount > 0; parameters.clearLightLists = false; + parameters.probeVolumesRunLightList = (m_ProbeVolumeList.bounds != null && m_ProbeVolumeList.bounds.Count > 0) ? true : false; + parameters.probeVolumesClearLightLists = false; // Always build the light list in XR mode to avoid issues with multi-pass if (hdCamera.xr.enabled) @@ -3241,6 +3244,16 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera h { parameters.clearLightLists = true; } + + if (hdCamera.xr.enabled) + { + parameters.probeVolumesRunLightList = true; + } + else if (!parameters.probeVolumesRunLightList && !m_TileAndClusterData.probeVolumesListsAreClear) + { + parameters.probeVolumesClearLightLists = true; + } + parameters.totalLightCount = m_TotalLightCount; parameters.viewCount = hdCamera.viewCount; parameters.enableFeatureVariants = GetFeatureVariantsEnabled(hdCamera.frameSettings); @@ -3340,19 +3353,9 @@ static void PushProbeVolumeLightListGlobalParams(in LightLoopGlobalParameters pa cmd.SetGlobalInt(HDShaderIDs._NumTileBigTileX, GetNumTileBigTileX(param.hdCamera)); cmd.SetGlobalInt(HDShaderIDs._NumTileBigTileY, GetNumTileBigTileY(param.hdCamera)); - cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredX, GetNumTileClusteredX(param.hdCamera)); - cmd.SetGlobalInt(HDShaderIDs._NumTileClusteredY, GetNumTileClusteredY(param.hdCamera)); - if (param.hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass)) cmd.SetGlobalBuffer(HDShaderIDs.g_vBigTileLightList, param.tileAndClusterData.probeVolumesBigTileLightList); - cmd.SetGlobalFloat(HDShaderIDs.g_fClustScale, param.clusterScale); - cmd.SetGlobalFloat(HDShaderIDs.g_fClustBase, k_ClustLogBase); - cmd.SetGlobalFloat(HDShaderIDs.g_fNearPlane, camera.nearClipPlane); - cmd.SetGlobalFloat(HDShaderIDs.g_fFarPlane, camera.farClipPlane); - cmd.SetGlobalInt(HDShaderIDs.g_iLog2NumClusters, k_Log2NumClusters); - - // int useDepthBuffer = 0; // cmd.SetGlobalInt(HDShaderIDs.g_isLogBaseBufferEnabled, useDepthBuffer); cmd.SetGlobalBuffer(HDShaderIDs.g_vProbeVolumesLayeredOffsetsBuffer, param.tileAndClusterData.probeVolumesPerVoxelOffset); @@ -3423,16 +3426,10 @@ static void GenerateProbeVolumesScreenSpaceAABBs(in BuildGPULightListParameters { var tileAndCluster = resources.tileAndClusterData; - cmd.SetComputeIntParam(parameters.screenSpaceAABBShader, HDShaderIDs.g_isOrthographic, parameters.isOrthographic ? 1 : 0); - // With XR single-pass, we have one set of light bounds per view to iterate over (bounds are in view space for each view) - cmd.SetComputeIntParam(parameters.screenSpaceAABBShader, HDShaderIDs.g_iNrVisibLights, probeVolumesCount); cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_data, tileAndCluster.probeVolumesConvexBoundsBuffer); cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_vBoundsBuffer, tileAndCluster.probeVolumesAABBBoundsBuffer); - cmd.SetComputeMatrixArrayParam(parameters.screenSpaceAABBShader, HDShaderIDs.g_mProjectionArr, parameters.lightListProjHMatrices); - cmd.SetComputeMatrixArrayParam(parameters.screenSpaceAABBShader, HDShaderIDs.g_mInvProjectionArr, parameters.lightListInvProjHMatrices); - cmd.DispatchCompute(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, (probeVolumesCount + 7) / 8, parameters.viewCount, 1); } } @@ -3448,19 +3445,6 @@ static void ProbeVolumesBigTilePrepass(in BuildGPULightListParameters parameters { var tileAndCluster = resources.tileAndClusterData; - cmd.SetComputeIntParam(parameters.bigTilePrepassShader, HDShaderIDs.g_iNrVisibLights, probeVolumesCount); - cmd.SetComputeIntParam(parameters.bigTilePrepassShader, HDShaderIDs.g_isOrthographic, parameters.isOrthographic ? 1 : 0); - cmd.SetComputeIntParams(parameters.bigTilePrepassShader, HDShaderIDs.g_viDimensions, s_TempScreenDimArray); - - // TODO: These two aren't actually used... - cmd.SetComputeIntParam(parameters.bigTilePrepassShader, HDShaderIDs._EnvLightIndexShift, parameters.lightList.lights.Count); - cmd.SetComputeIntParam(parameters.bigTilePrepassShader, HDShaderIDs._DecalIndexShift, parameters.lightList.lights.Count + parameters.lightList.envLights.Count); - - cmd.SetComputeMatrixArrayParam(parameters.bigTilePrepassShader, HDShaderIDs.g_mScrProjectionArr, parameters.lightListProjscrMatrices); - cmd.SetComputeMatrixArrayParam(parameters.bigTilePrepassShader, HDShaderIDs.g_mInvScrProjectionArr, parameters.lightListInvProjscrMatrices); - - cmd.SetComputeFloatParam(parameters.bigTilePrepassShader, HDShaderIDs.g_fNearPlane, parameters.nearClipPlane); - cmd.SetComputeFloatParam(parameters.bigTilePrepassShader, HDShaderIDs.g_fFarPlane, parameters.farClipPlane); cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_vLightList, tileAndCluster.probeVolumesBigTileLightList); cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_vBoundsBuffer, tileAndCluster.probeVolumesAABBBoundsBuffer); cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs._LightVolumeData, tileAndCluster.probeVolumesLightVolumeDataBuffer); @@ -3486,21 +3470,6 @@ static void ProbeVolumesVoxelLightListGeneration(in BuildGPULightListParameters cmd.DispatchCompute(parameters.clearClusterAtomicIndexShader, s_ClearVoxelAtomicKernel, 1, 1, 1); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, tileAndCluster.probeVolumesGlobalLightListAtomic); - cmd.SetComputeIntParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_isOrthographic, parameters.isOrthographic ? 1 : 0); - cmd.SetComputeIntParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_iNrVisibLights, probeVolumesCount); - cmd.SetComputeMatrixArrayParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_mScrProjectionArr, parameters.lightListProjscrMatrices); - cmd.SetComputeMatrixArrayParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_mInvScrProjectionArr, parameters.lightListInvProjscrMatrices); - - cmd.SetComputeIntParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_iLog2NumClusters, k_Log2NumClusters); - - cmd.SetComputeVectorParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_screenSize, parameters.screenSize); - cmd.SetComputeIntParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_iNumSamplesMSAA, parameters.msaaSamples); - - cmd.SetComputeFloatParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_fNearPlane, parameters.nearClipPlane); - cmd.SetComputeFloatParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_fFarPlane, parameters.farClipPlane); - - cmd.SetComputeFloatParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_fClustScale, parameters.clusterScale); - cmd.SetComputeFloatParam(parameters.buildPerVoxelLightListShader, HDShaderIDs.g_fClustBase, k_ClustLogBase); cmd.SetComputeTextureParam(parameters.buildPerVoxelLightListShader, parameters.probeVolumesBuildPerVoxelLightListKernel, HDShaderIDs.g_depth_tex, BuiltinRenderTextureType.None); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.probeVolumesBuildPerVoxelLightListKernel, HDShaderIDs.g_vLayeredLightList, tileAndCluster.probeVolumesPerVoxelLightLists); @@ -3518,7 +3487,7 @@ static void ProbeVolumesVoxelLightListGeneration(in BuildGPULightListParameters cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.probeVolumesBuildPerVoxelLightListKernel, HDShaderIDs._LightVolumeData, tileAndCluster.probeVolumesLightVolumeDataBuffer); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.probeVolumesBuildPerVoxelLightListKernel, HDShaderIDs.g_data, tileAndCluster.probeVolumesConvexBoundsBuffer); - cmd.SetComputeIntParam(parameters.buildPerVoxelLightListShader, HDShaderIDs._ProbeVolumeIndexShift, 0); // HACK: Fixme? + //cmd.SetComputeIntParam(parameters.buildPerVoxelLightListShader, HDShaderIDs._ProbeVolumeIndexShift, 0); // HACK: Fixme? cmd.DispatchCompute(parameters.buildPerVoxelLightListShader, parameters.probeVolumesBuildPerVoxelLightListKernel, parameters.numTilesClusterX, parameters.numTilesClusterY, parameters.viewCount); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index 219d4b884ce..7e14845c238 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -106,6 +106,7 @@ CBUFFER_START(ShaderVariablesLightList) int _EnvLightIndexShift; int _DecalIndexShift; int _DensityVolumeIndexShift; + int _ProbeVolumeIndexShift; CBUFFER_END // diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeLighting.cs index f26a894c8c3..dcb2388ce93 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeLighting.cs @@ -250,41 +250,55 @@ internal void OnLightingDataCleared() isClearProbeVolumeAtlasRequested = true; } - void PushProbeVolumesGlobalParams(HDCamera hdCamera, CommandBuffer cmd, int frameIndex) + unsafe void UpdateShaderVariablesGlobalProbeVolumesDefault(ref ShaderVariablesGlobal cb, HDCamera hdCamera) + { + cb._EnableProbeVolumes = 0; + cb._ProbeVolumeCount = 0; + cb._ProbeVolumeLeakMitigationMode = (int)LeakMitigationMode.NormalBias; + cb._ProbeVolumeNormalBiasWS = 0.0f; + cb._ProbeVolumeBilateralFilterWeightMin = 0.0f; + cb._ProbeVolumeBilateralFilterWeight = 0.0f; + + // Need to populate ambient probe fallback even in the default case, + // As if the feature is enabled in the ShaderConfig, but disabled in the HDRenderPipelineAsset, we need to fallback to ambient probe only. + SphericalHarmonicsL2 ambientProbeFallbackSH = m_SkyManager.GetAmbientProbe(hdCamera); + SphericalHarmonicMath.PackCoefficients(s_AmbientProbeFallbackPackedCoeffs, ambientProbeFallbackSH); + for (int i = 0; i < 7; ++i) + for (int j = 0; j < 4; ++j) + cb._ProbeVolumeAmbientProbeFallbackPackedCoeffs[i * 4 + j] = s_AmbientProbeFallbackPackedCoeffs[i][j]; + } + + unsafe void UpdateShaderVariablesGlobalProbeVolumes(ref ShaderVariablesGlobal cb, HDCamera hdCamera) { if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.Disabled) return; if (!m_SupportProbeVolume) { - PushProbeVolumesGlobalParamsDefault(hdCamera, cmd, frameIndex); + UpdateShaderVariablesGlobalProbeVolumesDefault(ref cb, hdCamera); return; } - cmd.SetGlobalInt(HDShaderIDs._EnableProbeVolumes, hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) ? 1 : 0); - cmd.SetGlobalBuffer(HDShaderIDs._ProbeVolumeBounds, s_VisibleProbeVolumeBoundsBuffer); - cmd.SetGlobalBuffer(HDShaderIDs._ProbeVolumeDatas, s_VisibleProbeVolumeDataBuffer); - cmd.SetGlobalInt(HDShaderIDs._ProbeVolumeCount, m_VisibleProbeVolumeBounds.Count); - cmd.SetGlobalTexture(HDShaderIDs._ProbeVolumeAtlasSH, m_ProbeVolumeAtlasSHRTHandle); - cmd.SetGlobalVector(HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCount, new Vector4( + cb._EnableProbeVolumes = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) ? 1u : 0u; + cb._ProbeVolumeCount = (uint)m_VisibleProbeVolumeBounds.Count; + cb._ProbeVolumeAtlasResolutionAndSliceCount = new Vector4( s_ProbeVolumeAtlasWidth, s_ProbeVolumeAtlasHeight, s_ProbeVolumeAtlasDepth, m_ProbeVolumeAtlasSHRTDepthSliceCount - )); - cmd.SetGlobalVector(HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCountInverse, new Vector4( + ); + cb._ProbeVolumeAtlasResolutionAndSliceCountInverse = new Vector4( 1.0f / (float)s_ProbeVolumeAtlasWidth, 1.0f / (float)s_ProbeVolumeAtlasHeight, 1.0f / (float)s_ProbeVolumeAtlasDepth, 1.0f / (float)m_ProbeVolumeAtlasSHRTDepthSliceCount - )); - cmd.SetGlobalTexture(HDShaderIDs._ProbeVolumeAtlasOctahedralDepth, m_ProbeVolumeAtlasOctahedralDepthRTHandle); - cmd.SetGlobalVector(HDShaderIDs._ProbeVolumeAtlasOctahedralDepthResolutionAndInverse, new Vector4( + ); + cb._ProbeVolumeAtlasOctahedralDepthResolutionAndInverse = new Vector4( m_ProbeVolumeAtlasOctahedralDepthRTHandle.rt.width, m_ProbeVolumeAtlasOctahedralDepthRTHandle.rt.height, 1.0f / (float)m_ProbeVolumeAtlasOctahedralDepthRTHandle.rt.width, 1.0f / (float)m_ProbeVolumeAtlasOctahedralDepthRTHandle.rt.height - )); + ); var settings = hdCamera.volumeStack.GetComponent(); LeakMitigationMode leakMitigationMode = (settings == null) @@ -307,38 +321,41 @@ void PushProbeVolumesGlobalParams(HDCamera hdCamera, CommandBuffer cmd, int fram } } - cmd.SetGlobalInt(HDShaderIDs._ProbeVolumeLeakMitigationMode, (int)leakMitigationMode); - cmd.SetGlobalFloat(HDShaderIDs._ProbeVolumeNormalBiasWS, normalBiasWS); - cmd.SetGlobalFloat(HDShaderIDs._ProbeVolumeBilateralFilterWeightMin, 1e-5f); - cmd.SetGlobalFloat(HDShaderIDs._ProbeVolumeBilateralFilterWeight, bilateralFilterWeight); + cb._ProbeVolumeLeakMitigationMode = (int)leakMitigationMode; + cb._ProbeVolumeNormalBiasWS = normalBiasWS; + cb._ProbeVolumeBilateralFilterWeightMin = 1e-5f; + cb._ProbeVolumeBilateralFilterWeight = bilateralFilterWeight; + + SphericalHarmonicsL2 ambientProbeFallbackSH = m_SkyManager.GetAmbientProbe(hdCamera); + SphericalHarmonicMath.PackCoefficients(s_AmbientProbeFallbackPackedCoeffs, ambientProbeFallbackSH); + for (int i = 0; i < 7; ++i) + for (int j = 0; j < 4; ++j) + cb._ProbeVolumeAmbientProbeFallbackPackedCoeffs[i * 4 + j] = s_AmbientProbeFallbackPackedCoeffs[i][j]; + } + + void PushProbeVolumesGlobalParams(HDCamera hdCamera, CommandBuffer cmd, int frameIndex) + { + if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.Disabled) + return; + if (!m_SupportProbeVolume) { - SphericalHarmonicsL2 ambientProbeFallbackSH = m_SkyManager.GetAmbientProbe(hdCamera); - SphericalHarmonicMath.PackCoefficients(s_AmbientProbeFallbackPackedCoeffs, ambientProbeFallbackSH); - cmd.SetGlobalVectorArray(HDShaderIDs._ProbeVolumeAmbientProbeFallbackPackedCoeffs, s_AmbientProbeFallbackPackedCoeffs); + PushProbeVolumesGlobalParamsDefault(hdCamera, cmd, frameIndex); + return; } + + cmd.SetGlobalBuffer(HDShaderIDs._ProbeVolumeBounds, s_VisibleProbeVolumeBoundsBuffer); + cmd.SetGlobalBuffer(HDShaderIDs._ProbeVolumeDatas, s_VisibleProbeVolumeDataBuffer); + cmd.SetGlobalTexture(HDShaderIDs._ProbeVolumeAtlasSH, m_ProbeVolumeAtlasSHRTHandle); + cmd.SetGlobalTexture(HDShaderIDs._ProbeVolumeAtlasOctahedralDepth, m_ProbeVolumeAtlasOctahedralDepthRTHandle); } internal void PushProbeVolumesGlobalParamsDefault(HDCamera hdCamera, CommandBuffer cmd, int frameIndex) { - cmd.SetGlobalInt(HDShaderIDs._EnableProbeVolumes, 0); cmd.SetGlobalBuffer(HDShaderIDs._ProbeVolumeBounds, s_VisibleProbeVolumeBoundsBufferDefault); cmd.SetGlobalBuffer(HDShaderIDs._ProbeVolumeDatas, s_VisibleProbeVolumeDataBufferDefault); - cmd.SetGlobalInt(HDShaderIDs._ProbeVolumeCount, 0); cmd.SetGlobalTexture(HDShaderIDs._ProbeVolumeAtlasSH, TextureXR.GetBlackTexture3D()); cmd.SetGlobalTexture(HDShaderIDs._ProbeVolumeAtlasOctahedralDepth, Texture2D.blackTexture); - cmd.SetGlobalInt(HDShaderIDs._ProbeVolumeLeakMitigationMode, (int)LeakMitigationMode.NormalBias); - cmd.SetGlobalFloat(HDShaderIDs._ProbeVolumeNormalBiasWS, 0.0f); - cmd.SetGlobalFloat(HDShaderIDs._ProbeVolumeBilateralFilterWeightMin, 0.0f); - cmd.SetGlobalFloat(HDShaderIDs._ProbeVolumeBilateralFilterWeight, 0.0f); - - { - // Need to populate ambient probe fallback even in the default case, - // As if the feature is enabled in the ShaderConfig, but disabled in the HDRenderPipelineAsset, we need to fallback to ambient probe only. - SphericalHarmonicsL2 ambientProbeFallbackSH = m_SkyManager.GetAmbientProbe(hdCamera); - SphericalHarmonicMath.PackCoefficients(s_AmbientProbeFallbackPackedCoeffs, ambientProbeFallbackSH); - cmd.SetGlobalVectorArray(HDShaderIDs._ProbeVolumeAmbientProbeFallbackPackedCoeffs, s_AmbientProbeFallbackPackedCoeffs); - } } internal void ReleaseProbeVolumeFromAtlas(ProbeVolume volume) @@ -400,18 +417,6 @@ internal bool EnsureProbeVolumeInAtlas(ScriptableRenderContext renderContext, Co cmd.SetComputeVectorParam(s_ProbeVolumeAtlasBlitCS, HDShaderIDs._ProbeVolumeAtlasBias, volume.parameters.bias ); - cmd.SetComputeVectorParam(s_ProbeVolumeAtlasBlitCS, HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCount, new Vector4( - s_ProbeVolumeAtlasWidth, - s_ProbeVolumeAtlasHeight, - s_ProbeVolumeAtlasDepth, - m_ProbeVolumeAtlasSHRTDepthSliceCount - )); - cmd.SetComputeVectorParam(s_ProbeVolumeAtlasBlitCS, HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCountInverse, new Vector4( - 1.0f / (float)s_ProbeVolumeAtlasWidth, - 1.0f / (float)s_ProbeVolumeAtlasHeight, - 1.0f / (float)s_ProbeVolumeAtlasDepth, - 1.0f / (float)m_ProbeVolumeAtlasSHRTDepthSliceCount - )); Debug.Assert(data.Length == size, "ProbeVolume: The probe volume baked data and its resolution are out of sync! Volume data length is " + data.Length + ", but resolution size is " + size + "."); Debug.Assert(size < s_MaxProbeVolumeProbeCount, "ProbeVolume: probe volume baked data size exceeds the currently max supported blitable size. Volume data size is " + size + ", but s_MaxProbeVolumeProbeCount is " + s_MaxProbeVolumeProbeCount + ". Please decrease ProbeVolume resolution, or increase ProbeVolumeLighting.s_MaxProbeVolumeProbeCount."); @@ -479,12 +484,6 @@ internal bool EnsureProbeVolumeInAtlasOctahedralDepth(ScriptableRenderContext re cmd.SetComputeVectorParam(s_ProbeVolumeAtlasOctahedralDepthBlitCS, HDShaderIDs._ProbeVolumeAtlasOctahedralDepthScaleBias, volume.parameters.octahedralDepthScaleBias ); - cmd.SetComputeVectorParam(s_ProbeVolumeAtlasOctahedralDepthBlitCS, HDShaderIDs._ProbeVolumeAtlasOctahedralDepthResolutionAndInverse, new Vector4( - m_ProbeVolumeAtlasOctahedralDepthRTHandle.rt.width, - m_ProbeVolumeAtlasOctahedralDepthRTHandle.rt.height, - 1.0f / (float)m_ProbeVolumeAtlasOctahedralDepthRTHandle.rt.width, - 1.0f / (float)m_ProbeVolumeAtlasOctahedralDepthRTHandle.rt.height - )); Debug.Assert(dataOctahedralDepth.Length == size, "ProbeVolume: The probe volume baked data and its resolution are out of sync! Volume data length is " + dataOctahedralDepth.Length + ", but resolution size is " + size + "."); @@ -795,19 +794,7 @@ void DisplayProbeVolumeAtlas(CommandBuffer cmd, Material debugMaterial, float sc propertyBlock.SetVector(HDShaderIDs._TextureViewScale, textureViewScale); propertyBlock.SetVector(HDShaderIDs._TextureViewBias, textureViewBias); propertyBlock.SetVector(HDShaderIDs._TextureViewResolution, textureViewResolution); - cmd.SetGlobalVector(HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCount, new Vector4( - s_ProbeVolumeAtlasWidth, - s_ProbeVolumeAtlasHeight, - s_ProbeVolumeAtlasDepth, - m_ProbeVolumeAtlasSHRTDepthSliceCount - )); - cmd.SetGlobalVector(HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCountInverse, new Vector4( - 1.0f / (float)s_ProbeVolumeAtlasWidth, - 1.0f / (float)s_ProbeVolumeAtlasHeight, - 1.0f / (float)s_ProbeVolumeAtlasDepth, - 1.0f / (float)m_ProbeVolumeAtlasSHRTDepthSliceCount - )); - propertyBlock.SetTexture(HDShaderIDs._AtlasTextureOctahedralDepth, m_ProbeVolumeAtlasOctahedralDepthRTHandle.rt); + propertyBlock.SetTexture(HDShaderIDs._AtlasTextureOctahedralDepth, m_ProbeVolumeAtlasOctahedralDepthRTHandle); propertyBlock.SetVector(HDShaderIDs._AtlasTextureOctahedralDepthScaleBias, atlasTextureOctahedralDepthScaleBias); propertyBlock.SetVector(HDShaderIDs._ValidRange, validRange); propertyBlock.SetInt(HDShaderIDs._ProbeVolumeAtlasSliceMode, sliceMode); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeShaderVariables.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeShaderVariables.hlsl index 4d5f82ed525..cd95990c98c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeShaderVariables.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeShaderVariables.hlsl @@ -15,16 +15,7 @@ StructuredBuffer _ProbeVolumeDatas; TEXTURE3D(_ProbeVolumeAtlasSH); - float4 _ProbeVolumeAtlasResolutionAndSliceCount; - float4 _ProbeVolumeAtlasResolutionAndSliceCountInverse; TEXTURE2D(_ProbeVolumeAtlasOctahedralDepth); - float4 _ProbeVolumeAtlasOctahedralDepthResolutionAndInverse; - int _ProbeVolumeLeakMitigationMode; - float _ProbeVolumeNormalBiasWS; - float _ProbeVolumeBilateralFilterWeightMin; - float _ProbeVolumeBilateralFilterWeight; - - float4 _ProbeVolumeAmbientProbeFallbackPackedCoeffs[7]; // 3 bands of SH, packed for storing global ambient probe lighting as fallback to probe volumes. #endif #endif // endof PROBE_VOLUME_SHADER_VARIABLES diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 7f07d34f741..92d10f7c84c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -993,6 +993,8 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) UpdateShaderVariablesGlobalVolumetrics(ref m_ShaderVariablesGlobalCB, RTHandles.rtHandleProperties, hdCamera); m_ShadowManager.UpdateShaderVariablesGlobalCB(ref m_ShaderVariablesGlobalCB); UpdateShaderVariablesGlobalLightLoop(ref m_ShaderVariablesGlobalCB, hdCamera); + UpdateShaderVariablesGlobalProbeVolumes(ref m_ShaderVariablesGlobalCB, hdCamera); + PushProbeVolumesGlobalParams(hdCamera, cmd, m_FrameCount); m_AmbientOcclusionSystem.UpdateShaderVariableGlobalCB(ref m_ShaderVariablesGlobalCB, hdCamera); // Misc @@ -1012,9 +1014,6 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) m_ShaderVariablesGlobalCB._EnableSkyReflection = hdCamera.frameSettings.IsEnabled(FrameSettingsField.SkyReflection) ? 1u : 0u; m_ShaderVariablesGlobalCB._ContactShadowOpacity = m_ContactShadows.opacity.value; - PushProbeVolumesGlobalParams(hdCamera, cmd, m_FrameCount); - - int coarseStencilWidth = HDUtils.DivRoundUp(hdCamera.actualWidth, 8); int coarseStencilHeight = HDUtils.DivRoundUp(hdCamera.actualHeight, 8); m_ShaderVariablesGlobalCB._CoarseStencilBufferSize = new Vector4(coarseStencilWidth, coarseStencilHeight, 1.0f / coarseStencilWidth, 1.0f / coarseStencilHeight); @@ -1046,6 +1045,7 @@ void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd) using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PushGlobalParameters))) { PushVolumetricLightingGlobalParams(hdCamera, cmd, m_FrameCount); + PushProbeVolumesGlobalParams(hdCamera, cmd, m_FrameCount); // Set up UnityPerView CBuffer. hdCamera.SetupGlobalParams(cmd, m_FrameCount); @@ -2138,7 +2138,7 @@ void Callback(CommandBuffer c, HDCamera cam) // After Depth and Normals/roughness including decals bool depthBufferModified = RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterOpaqueDepthAndNormal); - // If the depth was already copied in RenderDBuffer, we force the copy again because the custom pass modified the depth. + // If the depth was already copied in RenderDBuffer, we force the copy again because the custom pass modified the depth. if (depthBufferModified) m_IsDepthBufferCopyValid = false; @@ -3803,7 +3803,7 @@ void RenderObjectsMotionVectors(CullingResults cullResults, HDCamera hdCamera, S hdCamera.camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth; // Disable write to normal buffer for unlit shader (the normal buffer binding change when using MSAA) cmd.SetGlobalInt(HDShaderIDs._ColorMaskNormal, hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA) ? (int)ColorWriteMask.All : 0); - + RenderStateBlock? stateBlock = null; if (hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred || !hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)) stateBlock = m_AlphaToMaskBlock; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 8c85905d2d0..f7040136eba 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -98,10 +98,8 @@ static class HDShaderIDs public static readonly int _BlurWeightsStorage = Shader.PropertyToID("_BlurWeightsStorage"); public static readonly int g_LayeredSingleIdxBuffer = Shader.PropertyToID("g_LayeredSingleIdxBuffer"); - public static readonly int _ProbeVolumeIndexShift = Shader.PropertyToID("_ProbeVolumeIndexShift"); public static readonly int _DebugProbeVolumeMode = Shader.PropertyToID("_DebugProbeVolumeMode"); - public static readonly int g_depth_tex = Shader.PropertyToID("g_depth_tex"); public static readonly int g_vLayeredLightList = Shader.PropertyToID("g_vLayeredLightList"); public static readonly int g_LayeredOffset = Shader.PropertyToID("g_LayeredOffset"); @@ -132,7 +130,6 @@ static class HDShaderIDs public static readonly int _EnvLightDatas = Shader.PropertyToID("_EnvLightDatas"); public static readonly int _ProbeVolumeBounds = Shader.PropertyToID("_ProbeVolumeBounds"); public static readonly int _ProbeVolumeDatas = Shader.PropertyToID("_ProbeVolumeDatas"); - public static readonly int _ProbeVolumeCount = Shader.PropertyToID("_ProbeVolumeCount"); public static readonly int g_vProbeVolumesLayeredOffsetsBuffer = Shader.PropertyToID("g_vProbeVolumesLayeredOffsetsBuffer"); public static readonly int g_vProbeVolumesLightListGlobal = Shader.PropertyToID("g_vProbeVolumesLightListGlobal"); @@ -435,8 +432,6 @@ static class HDShaderIDs public static readonly int _VolumeData = Shader.PropertyToID("_VolumeData"); public static readonly int _VolumeMaskAtlas = Shader.PropertyToID("_VolumeMaskAtlas"); - public static readonly int _EnableProbeVolumes = Shader.PropertyToID("_EnableProbeVolumes"); - public static readonly int _GroundIrradianceTexture = Shader.PropertyToID("_GroundIrradianceTexture"); public static readonly int _GroundIrradianceTable = Shader.PropertyToID("_GroundIrradianceTable"); public static readonly int _GroundIrradianceTableOrder = Shader.PropertyToID("_GroundIrradianceTableOrder"); @@ -824,14 +819,7 @@ static class HDShaderIDs // Probe Volumes public static readonly int _ProbeVolumeAtlasSH = Shader.PropertyToID("_ProbeVolumeAtlasSH"); - public static readonly int _ProbeVolumeAtlasResolutionAndSliceCount = Shader.PropertyToID("_ProbeVolumeAtlasResolutionAndSliceCount"); - public static readonly int _ProbeVolumeAtlasResolutionAndSliceCountInverse = Shader.PropertyToID("_ProbeVolumeAtlasResolutionAndSliceCountInverse"); public static readonly int _ProbeVolumeAtlasOctahedralDepth = Shader.PropertyToID("_ProbeVolumeAtlasOctahedralDepth"); - public static readonly int _ProbeVolumeAtlasOctahedralDepthResolutionAndInverse = Shader.PropertyToID("_ProbeVolumeAtlasOctahedralDepthResolutionAndInverse"); - public static readonly int _ProbeVolumeLeakMitigationMode = Shader.PropertyToID("_ProbeVolumeLeakMitigationMode"); - public static readonly int _ProbeVolumeNormalBiasWS = Shader.PropertyToID("_ProbeVolumeNormalBiasWS"); - public static readonly int _ProbeVolumeBilateralFilterWeightMin = Shader.PropertyToID("_ProbeVolumeBilateralFilterWeightMin"); - public static readonly int _ProbeVolumeBilateralFilterWeight = Shader.PropertyToID("_ProbeVolumeBilateralFilterWeight"); public static readonly int _ProbeVolumeResolution = Shader.PropertyToID("_ProbeVolumeResolution"); public static readonly int _ProbeVolumeResolutionInverse = Shader.PropertyToID("_ProbeVolumeResolutionInverse"); public static readonly int _ProbeVolumeAtlasScale = Shader.PropertyToID("_ProbeVolumeAtlasScale"); @@ -856,9 +844,6 @@ static class HDShaderIDs public static readonly int _AtlasTextureOctahedralDepthScaleBias = Shader.PropertyToID("_AtlasTextureOctahedralDepthScaleBias"); public static readonly int _ValidRange = Shader.PropertyToID("_ValidRange"); public static readonly int _ProbeVolumeAtlasSliceMode = Shader.PropertyToID("_ProbeVolumeAtlasSliceMode"); - public static readonly int _ProbeVolumeAmbientProbeFallbackPackedCoeffs = Shader.PropertyToID("_ProbeVolumeAmbientProbeFallbackPackedCoeffs"); - - } // Shared material property names diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index 67da43aa6ff..294faf951ec 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -170,8 +170,8 @@ unsafe struct ShaderVariablesGlobal public Vector4 _IndirectLightingMultiplier; // .x indirect diffuse multiplier (use with indirect lighting volume controler) public float _MicroShadowOpacity; - public float _Pad3; - public float _Pad4; + public uint _EnableProbeVolumes; + public uint _ProbeVolumeCount; public float _Pad5; public Vector4 _CookieAtlasSize; @@ -229,5 +229,18 @@ unsafe struct ShaderVariablesGlobal public int _UseRayTracedReflections; public int _RaytracingFrameIndex; // Index of the current frame [0, 7] public uint _EnableRecursiveRayTracing; + + // Probe Volumes + public Vector4 _ProbeVolumeAtlasResolutionAndSliceCount; + public Vector4 _ProbeVolumeAtlasResolutionAndSliceCountInverse; + public Vector4 _ProbeVolumeAtlasOctahedralDepthResolutionAndInverse; + + public int _ProbeVolumeLeakMitigationMode; + public float _ProbeVolumeNormalBiasWS; + public float _ProbeVolumeBilateralFilterWeightMin; + public float _ProbeVolumeBilateralFilterWeight; + + [HLSLArray(7, typeof(Vector4))] + public fixed float _ProbeVolumeAmbientProbeFallbackPackedCoeffs[7 * 4]; // 3 bands of SH, packed for storing global ambient probe lighting as fallback to probe volumes. } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 00ac5a0cb3f..f952d600063 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -90,8 +90,8 @@ GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) float4 _AmbientOcclusionParam; float4 _IndirectLightingMultiplier; float _MicroShadowOpacity; - float _Pad3; - float _Pad4; + uint _EnableProbeVolumes; + uint _ProbeVolumeCount; float _Pad5; float4 _CookieAtlasSize; float4 _CookieAtlasData; @@ -128,6 +128,14 @@ GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) int _UseRayTracedReflections; int _RaytracingFrameIndex; uint _EnableRecursiveRayTracing; + float4 _ProbeVolumeAtlasResolutionAndSliceCount; + float4 _ProbeVolumeAtlasResolutionAndSliceCountInverse; + float4 _ProbeVolumeAtlasOctahedralDepthResolutionAndInverse; + int _ProbeVolumeLeakMitigationMode; + float _ProbeVolumeNormalBiasWS; + float _ProbeVolumeBilateralFilterWeightMin; + float _ProbeVolumeBilateralFilterWeight; + float4 _ProbeVolumeAmbientProbeFallbackPackedCoeffs[7]; CBUFFER_END From 7852ca96dfdc6cfc7aa6933461ab6e7d7563c3b6 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 7 Apr 2020 11:00:25 +0200 Subject: [PATCH 76/92] Fixed deallocation of constant buffers --- .../Runtime/Common/ConstantBuffer.cs | 50 ++++++++++++++++++- .../Runtime/Lighting/LightLoop/LightLoop.cs | 6 ++- .../RenderPipeline/HDRenderPipeline.cs | 4 ++ 3 files changed, 56 insertions(+), 4 deletions(-) diff --git a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs index c0c013511ac..5de12150962 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs @@ -1,3 +1,4 @@ +using System; using Unity.Collections.LowLevel.Unsafe; namespace UnityEngine.Rendering @@ -10,7 +11,7 @@ public class ConstantBuffer where CBType : struct { CBType[] m_Data = new CBType[1]; // Array is required by the ComputeBuffer SetData API ComputeBuffer m_GPUConstantBuffer = null; - static ConstantBuffer m_TypedConstantBuffer = new ConstantBuffer(); + static ConstantBuffer m_TypedConstantBuffer; ConstantBuffer() { @@ -41,11 +42,35 @@ void SetInternal(Material mat, int shaderId) mat.SetConstantBuffer(shaderId, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); } - void Release() + void ReleaseInternal() { CoreUtils.SafeRelease(m_GPUConstantBuffer); } + /// + /// Allocates GPU resources for this type of constant buffer. + /// This needs to be called once before using the constant buffer. + /// + public static void Allocate() + { + if (m_TypedConstantBuffer != null) + throw new InvalidOperationException($"Constant Buffer {m_TypedConstantBuffer.GetType()} was already allocated"); + + m_TypedConstantBuffer = new ConstantBuffer(); + } + + /// + /// Release GPU resources for this type of constant buffer. + /// + public static void Release() + { + if (m_TypedConstantBuffer == null) + throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + + m_TypedConstantBuffer.ReleaseInternal(); + m_TypedConstantBuffer = null; + } + /// /// Update the GPU data of the constant buffer and bind it globally. /// @@ -54,6 +79,9 @@ void Release() /// Shader porperty id to bind the constant buffer to. public static void PushGlobal(CommandBuffer cmd, in CBType data, int shaderId) { + if (m_TypedConstantBuffer == null) + throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + m_TypedConstantBuffer.UpdateDataInternal(cmd, data); m_TypedConstantBuffer.SetGlobalInternal(cmd, shaderId); } @@ -67,6 +95,9 @@ public static void PushGlobal(CommandBuffer cmd, in CBType data, int shaderId) /// Shader porperty id to bind the constant buffer to. public static void Push(CommandBuffer cmd, in CBType data, ComputeShader cs, int shaderId) { + if (m_TypedConstantBuffer == null) + throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + m_TypedConstantBuffer.UpdateDataInternal(cmd, data); m_TypedConstantBuffer.SetInternal(cmd, cs, shaderId); } @@ -80,6 +111,9 @@ public static void Push(CommandBuffer cmd, in CBType data, ComputeShader cs, int /// Shader porperty id to bind the constant buffer to. public static void Push(CommandBuffer cmd, in CBType data, Material mat, int shaderId) { + if (m_TypedConstantBuffer == null) + throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + m_TypedConstantBuffer.UpdateDataInternal(cmd, data); m_TypedConstantBuffer.SetInternal(mat, shaderId); } @@ -91,6 +125,9 @@ public static void Push(CommandBuffer cmd, in CBType data, Material mat, int sha /// Input data of the constant buffer. public static void UpdateData(CommandBuffer cmd, in CBType data) { + if (m_TypedConstantBuffer == null) + throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + m_TypedConstantBuffer.UpdateDataInternal(cmd, data); } @@ -101,6 +138,9 @@ public static void UpdateData(CommandBuffer cmd, in CBType data) /// Shader porperty id to bind the constant buffer to. public static void SetGlobal(CommandBuffer cmd, int shaderId) { + if (m_TypedConstantBuffer == null) + throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + m_TypedConstantBuffer.SetGlobalInternal(cmd, shaderId); } @@ -112,6 +152,9 @@ public static void SetGlobal(CommandBuffer cmd, int shaderId) /// Shader porperty id to bind the constant buffer to. public static void Set(CommandBuffer cmd, ComputeShader cs, int shaderId) { + if (m_TypedConstantBuffer == null) + throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + m_TypedConstantBuffer.SetInternal(cmd, cs, shaderId); } @@ -122,6 +165,9 @@ public static void Set(CommandBuffer cmd, ComputeShader cs, int shaderId) /// Shader porperty id to bind the constant buffer to. public static void Set(Material mat, int shaderId) { + if (m_TypedConstantBuffer == null) + throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + m_TypedConstantBuffer.SetInternal(mat, shaderId); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index a747b63cc00..9671a645f5b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -307,6 +307,8 @@ internal class LightLoopTextureCaches public void Initialize(HDRenderPipelineAsset hdrpAsset, RenderPipelineResources defaultResources, IBLFilterBSDF[] iBLFilterBSDFArray) { + ConstantBuffer.Allocate(); + var lightLoopSettings = hdrpAsset.currentPlatformRenderPipelineSettings.lightLoopSettings; m_CubeToPanoMaterial = CoreUtils.CreateEngineMaterial(defaultResources.shaders.cubeToPanoPS); @@ -343,6 +345,8 @@ public void Cleanup() lightCookieManager.Release(); CoreUtils.Destroy(m_CubeToPanoMaterial); + + ConstantBuffer.Release(); } public void NewFrame() @@ -3487,8 +3491,6 @@ static void ProbeVolumesVoxelLightListGeneration(in BuildGPULightListParameters cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.probeVolumesBuildPerVoxelLightListKernel, HDShaderIDs._LightVolumeData, tileAndCluster.probeVolumesLightVolumeDataBuffer); cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.probeVolumesBuildPerVoxelLightListKernel, HDShaderIDs.g_data, tileAndCluster.probeVolumesConvexBoundsBuffer); - //cmd.SetComputeIntParam(parameters.buildPerVoxelLightListShader, HDShaderIDs._ProbeVolumeIndexShift, 0); // HACK: Fixme? - cmd.DispatchCompute(parameters.buildPerVoxelLightListShader, parameters.probeVolumesBuildPerVoxelLightListKernel, parameters.numTilesClusterX, parameters.numTilesClusterY, parameters.viewCount); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 92d10f7c84c..58f42d6ff90 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -501,6 +501,8 @@ public HDRenderPipeline(HDRenderPipelineAsset asset, HDRenderPipelineAsset defau m_ColorResolveMaterial = CoreUtils.CreateEngineMaterial(asset.renderPipelineResources.shaders.colorResolvePS); InitializeProbeVolumes(); + + ConstantBuffer.Allocate(); } #if UNITY_EDITOR @@ -957,6 +959,8 @@ void DisposeProbeCameraPool() #endif } + ConstantBuffer.Release(); + CameraCaptureBridge.enabled = false; } From 8fcb2cca9a6ce0fc3cdfa910a7c8af41d087e9b0 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 7 Apr 2020 12:35:06 +0200 Subject: [PATCH 77/92] Properly release Volumetric constant buffers. --- .../Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 9e31523d1ac..96e7d962f42 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -256,6 +256,8 @@ void InitializeVolumetricLighting() m_PixelCoordToViewDirWS = new Matrix4x4[ShaderConfig.s_XrMaxViews]; + ConstantBuffer.Allocate(); + CreateVolumetricLightingBuffers(); } @@ -403,6 +405,8 @@ void CleanupVolumetricLighting() m_VolumeVoxelizationCS = null; m_VolumetricLightingCS = null; m_VolumetricLightingFilteringCS = null; + + ConstantBuffer.Release(); } static int ComputeVBufferTileSize(VolumetricLightingPreset preset) From f47fcfc5576237ed7b5382d0d9c30d03e5aff00b Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 8 Apr 2020 11:54:26 +0200 Subject: [PATCH 78/92] Another update to CB API --- .../Runtime/Common/ConstantBuffer.cs | 196 +++++++++--------- .../Runtime/Lighting/LightLoop/LightLoop.cs | 10 +- .../Runtime/Lighting/Shadow/HDShadowAtlas.cs | 2 +- .../VolumetricLighting/VolumetricLighting.cs | 14 +- .../HDRenderPipeline.LightLoop.cs | 2 +- .../HDRenderPipeline.RenderGraph.cs | 4 +- .../RenderPipeline/HDRenderPipeline.cs | 16 +- 7 files changed, 120 insertions(+), 124 deletions(-) diff --git a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs index 5de12150962..75d4f2097d8 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs @@ -1,4 +1,4 @@ -using System; +using System.Collections.Generic; using Unity.Collections.LowLevel.Unsafe; namespace UnityEngine.Rendering @@ -6,70 +6,9 @@ namespace UnityEngine.Rendering /// /// Constant Buffer management class. /// - /// Type of the structure that represent the constant buffer data. - public class ConstantBuffer where CBType : struct + public class ConstantBuffer { - CBType[] m_Data = new CBType[1]; // Array is required by the ComputeBuffer SetData API - ComputeBuffer m_GPUConstantBuffer = null; - static ConstantBuffer m_TypedConstantBuffer; - - ConstantBuffer() - { - m_GPUConstantBuffer = new ComputeBuffer(1, UnsafeUtility.SizeOf(), ComputeBufferType.Constant); - } - - void UpdateDataInternal(CommandBuffer cmd, in CBType data) - { - m_Data[0] = data; - cmd.SetComputeBufferData(m_GPUConstantBuffer, m_Data); - } - - void SetGlobalInternal(CommandBuffer cmd, int shaderId) - { - cmd.SetGlobalConstantBuffer(m_GPUConstantBuffer, shaderId, 0, m_GPUConstantBuffer.stride); - } - - void SetInternal(CommandBuffer cmd, ComputeShader cs, int shaderId) - { - cmd.SetComputeConstantBufferParam(cs, shaderId, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); - } - - void SetInternal(Material mat, int shaderId) - { - // This isn't done via command buffer because as long as the buffer itself is not destroyed, - // the binding stays valid. Only the commit of data needs to go through the command buffer. - // We do it here anyway for now to simplify user API. - mat.SetConstantBuffer(shaderId, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); - } - - void ReleaseInternal() - { - CoreUtils.SafeRelease(m_GPUConstantBuffer); - } - - /// - /// Allocates GPU resources for this type of constant buffer. - /// This needs to be called once before using the constant buffer. - /// - public static void Allocate() - { - if (m_TypedConstantBuffer != null) - throw new InvalidOperationException($"Constant Buffer {m_TypedConstantBuffer.GetType()} was already allocated"); - - m_TypedConstantBuffer = new ConstantBuffer(); - } - - /// - /// Release GPU resources for this type of constant buffer. - /// - public static void Release() - { - if (m_TypedConstantBuffer == null) - throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); - - m_TypedConstantBuffer.ReleaseInternal(); - m_TypedConstantBuffer = null; - } + static List m_RegisteredConstantBuffers = new List(); /// /// Update the GPU data of the constant buffer and bind it globally. @@ -77,13 +16,12 @@ public static void Release() /// Command Buffer used to execute the graphic commands. /// Input data of the constant buffer. /// Shader porperty id to bind the constant buffer to. - public static void PushGlobal(CommandBuffer cmd, in CBType data, int shaderId) + public static void PushGlobal(CommandBuffer cmd, in CBType data, int shaderId) where CBType : struct { - if (m_TypedConstantBuffer == null) - throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + var cb = TypedConstantBuffer.instance; - m_TypedConstantBuffer.UpdateDataInternal(cmd, data); - m_TypedConstantBuffer.SetGlobalInternal(cmd, shaderId); + cb.UpdateData(cmd, data); + cb.SetGlobal(cmd, shaderId); } /// @@ -93,13 +31,12 @@ public static void PushGlobal(CommandBuffer cmd, in CBType data, int shaderId) /// Input data of the constant buffer. /// Compute shader to which the constant buffer should be bound. /// Shader porperty id to bind the constant buffer to. - public static void Push(CommandBuffer cmd, in CBType data, ComputeShader cs, int shaderId) + public static void Push(CommandBuffer cmd, in CBType data, ComputeShader cs, int shaderId) where CBType : struct { - if (m_TypedConstantBuffer == null) - throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + var cb = TypedConstantBuffer.instance; - m_TypedConstantBuffer.UpdateDataInternal(cmd, data); - m_TypedConstantBuffer.SetInternal(cmd, cs, shaderId); + cb.UpdateData(cmd, data); + cb.Set(cmd, cs, shaderId); } /// @@ -109,13 +46,12 @@ public static void Push(CommandBuffer cmd, in CBType data, ComputeShader cs, int /// Input data of the constant buffer. /// Material to which the constant buffer should be bound. /// Shader porperty id to bind the constant buffer to. - public static void Push(CommandBuffer cmd, in CBType data, Material mat, int shaderId) + public static void Push(CommandBuffer cmd, in CBType data, Material mat, int shaderId) where CBType : struct { - if (m_TypedConstantBuffer == null) - throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + var cb = TypedConstantBuffer.instance; - m_TypedConstantBuffer.UpdateDataInternal(cmd, data); - m_TypedConstantBuffer.SetInternal(mat, shaderId); + cb.UpdateData(cmd, data); + cb.Set(mat, shaderId); } /// @@ -123,12 +59,11 @@ public static void Push(CommandBuffer cmd, in CBType data, Material mat, int sha /// /// Command Buffer used to execute the graphic commands. /// Input data of the constant buffer. - public static void UpdateData(CommandBuffer cmd, in CBType data) + public static void UpdateData(CommandBuffer cmd, in CBType data) where CBType : struct { - if (m_TypedConstantBuffer == null) - throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + var cb = TypedConstantBuffer.instance; - m_TypedConstantBuffer.UpdateDataInternal(cmd, data); + cb.UpdateData(cmd, data); } /// @@ -136,12 +71,11 @@ public static void UpdateData(CommandBuffer cmd, in CBType data) /// /// Command Buffer used to execute the graphic commands. /// Shader porperty id to bind the constant buffer to. - public static void SetGlobal(CommandBuffer cmd, int shaderId) + public static void SetGlobal(CommandBuffer cmd, int shaderId) where CBType : struct { - if (m_TypedConstantBuffer == null) - throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + var cb = TypedConstantBuffer.instance; - m_TypedConstantBuffer.SetGlobalInternal(cmd, shaderId); + cb.SetGlobal(cmd, shaderId); } /// @@ -150,12 +84,11 @@ public static void SetGlobal(CommandBuffer cmd, int shaderId) /// Command Buffer used to execute the graphic commands. /// Compute shader to which the constant buffer should be bound. /// Shader porperty id to bind the constant buffer to. - public static void Set(CommandBuffer cmd, ComputeShader cs, int shaderId) + public static void Set(CommandBuffer cmd, ComputeShader cs, int shaderId) where CBType : struct { - if (m_TypedConstantBuffer == null) - throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + var cb = TypedConstantBuffer.instance; - m_TypedConstantBuffer.SetInternal(cmd, cs, shaderId); + cb.Set(cmd, cs, shaderId); } /// @@ -163,12 +96,85 @@ public static void Set(CommandBuffer cmd, ComputeShader cs, int shaderId) /// /// Material to which the constant buffer should be bound. /// Shader porperty id to bind the constant buffer to. - public static void Set(Material mat, int shaderId) + public static void Set(Material mat, int shaderId) where CBType : struct { - if (m_TypedConstantBuffer == null) - throw new InvalidOperationException($"Constant Buffer of type {typeof(CBType)} was never allocated"); + var cb = TypedConstantBuffer.instance; - m_TypedConstantBuffer.SetInternal(mat, shaderId); + cb.Set(mat, shaderId); + } + + public static void ReleaseAll() + { + foreach (var cb in m_RegisteredConstantBuffers) + cb.Release(); + + m_RegisteredConstantBuffers.Clear(); + } + + internal abstract class ConstantBufferBase + { + public abstract void Release(); + } + + internal static void Register(ConstantBufferBase cb) + { + m_RegisteredConstantBuffers.Add(cb); + } + + class TypedConstantBuffer : ConstantBufferBase where CBType : struct + { + CBType[] m_Data = new CBType[1]; // Array is required by the ComputeBuffer SetData API + static TypedConstantBuffer s_Instance = null; + internal static TypedConstantBuffer instance + { + get + { + if (s_Instance == null) + s_Instance = new TypedConstantBuffer(); + return s_Instance; + } + set + { + s_Instance = value; + } + } + ComputeBuffer m_GPUConstantBuffer = null; + + TypedConstantBuffer() + { + m_GPUConstantBuffer = new ComputeBuffer(1, UnsafeUtility.SizeOf(), ComputeBufferType.Constant); + ConstantBuffer.Register(this); + } + + public void UpdateData(CommandBuffer cmd, in CBType data) + { + m_Data[0] = data; + cmd.SetComputeBufferData(m_GPUConstantBuffer, m_Data); + } + + public void SetGlobal(CommandBuffer cmd, int shaderId) + { + cmd.SetGlobalConstantBuffer(m_GPUConstantBuffer, shaderId, 0, m_GPUConstantBuffer.stride); + } + + public void Set(CommandBuffer cmd, ComputeShader cs, int shaderId) + { + cmd.SetComputeConstantBufferParam(cs, shaderId, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); + } + + public void Set(Material mat, int shaderId) + { + // This isn't done via command buffer because as long as the buffer itself is not destroyed, + // the binding stays valid. Only the commit of data needs to go through the command buffer. + // We do it here anyway for now to simplify user API. + mat.SetConstantBuffer(shaderId, m_GPUConstantBuffer, 0, m_GPUConstantBuffer.stride); + } + + public override void Release() + { + CoreUtils.SafeRelease(m_GPUConstantBuffer); + s_Instance = null; + } } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 9671a645f5b..736f5e1c946 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -307,8 +307,6 @@ internal class LightLoopTextureCaches public void Initialize(HDRenderPipelineAsset hdrpAsset, RenderPipelineResources defaultResources, IBLFilterBSDF[] iBLFilterBSDFArray) { - ConstantBuffer.Allocate(); - var lightLoopSettings = hdrpAsset.currentPlatformRenderPipelineSettings.lightLoopSettings; m_CubeToPanoMaterial = CoreUtils.CreateEngineMaterial(defaultResources.shaders.cubeToPanoPS); @@ -345,8 +343,6 @@ public void Cleanup() lightCookieManager.Release(); CoreUtils.Destroy(m_CubeToPanoMaterial); - - ConstantBuffer.Release(); } public void NewFrame() @@ -2938,7 +2934,7 @@ static void ClearLightLists( in BuildGPULightListParameters parameters, CommandBuffer cmd) { // ClearLightLists is the first pass, we push the global parameters for light list building here. - ConstantBuffer.PushGlobal(cmd, parameters.lightListCB, HDShaderIDs._ShaderVariablesLightList); + ConstantBuffer.PushGlobal(cmd, parameters.lightListCB, HDShaderIDs._ShaderVariablesLightList); if (parameters.clearLightLists && !parameters.runLightList) { @@ -3029,7 +3025,7 @@ static void BuildPerTileLightList(in BuildGPULightListParameters parameters, in var localLightListCB = parameters.lightListCB; localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; - ConstantBuffer.PushGlobal(cmd, localLightListCB, HDShaderIDs._ShaderVariablesLightList); + ConstantBuffer.PushGlobal(cmd, localLightListCB, HDShaderIDs._ShaderVariablesLightList); cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_TileFeatureFlags, tileAndCluster.tileFeatureFlags); tileFlagsWritten = true; @@ -3116,7 +3112,7 @@ static void BuildDispatchIndirectArguments(in BuildGPULightListParameters parame var localLightListCB = parameters.lightListCB; localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; - ConstantBuffer.PushGlobal(cmd, localLightListCB, HDShaderIDs._ShaderVariablesLightList); + ConstantBuffer.PushGlobal(cmd, localLightListCB, HDShaderIDs._ShaderVariablesLightList); cmd.SetComputeBufferParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, tileAndCluster.tileFeatureFlags); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs index 87e4c8a95cd..f83708478b2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs @@ -533,7 +533,7 @@ static void RenderShadows( in RenderShadowsParameters parameters, globalCB._ViewProjMatrix = viewProjection; globalCB._InvViewProjMatrix = viewProjection.inverse; - ConstantBuffer.PushGlobal(cmd, globalCB, HDShaderIDs._ShaderVariablesGlobal); + ConstantBuffer.PushGlobal(cmd, globalCB, HDShaderIDs._ShaderVariablesGlobal); cmd.SetGlobalVectorArray(HDShaderIDs._ShadowFrustumPlanes, shadowRequest.frustumPlanes); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 96e7d962f42..17c538d3adb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -256,8 +256,6 @@ void InitializeVolumetricLighting() m_PixelCoordToViewDirWS = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - ConstantBuffer.Allocate(); - CreateVolumetricLightingBuffers(); } @@ -405,8 +403,6 @@ void CleanupVolumetricLighting() m_VolumeVoxelizationCS = null; m_VolumetricLightingCS = null; m_VolumetricLightingFilteringCS = null; - - ConstantBuffer.Release(); } static int ComputeVBufferTileSize(VolumetricLightingPreset preset) @@ -683,8 +679,8 @@ static void VolumeVoxelizationPass( in VolumeVoxelizationParameters parameters, cmd.SetComputeBufferParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs._VolumeData, visibleVolumeDataBuffer); cmd.SetComputeTextureParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs._VolumeMaskAtlas, parameters.volumeAtlas); - ConstantBuffer.Push(cmd, parameters.volumetricCB, parameters.voxelizationCS, HDShaderIDs._ShaderVariablesVolumetric); - ConstantBuffer.Set(cmd, parameters.voxelizationCS, HDShaderIDs._ShaderVariablesLightList); + ConstantBuffer.Push(cmd, parameters.volumetricCB, parameters.voxelizationCS, HDShaderIDs._ShaderVariablesVolumetric); + ConstantBuffer.Set(cmd, parameters.voxelizationCS, HDShaderIDs._ShaderVariablesLightList); // The shader defines GROUP_SIZE_1D = 8. cmd.DispatchCompute(parameters.voxelizationCS, parameters.voxelizationKernel, ((int)parameters.resolution.x + 7) / 8, ((int)parameters.resolution.y + 7) / 8, parameters.viewCount); @@ -832,8 +828,8 @@ static void VolumetricLightingPass( in VolumetricLightingParameters parameters, cmd.SetComputeTextureParam(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, HDShaderIDs._VBufferLightingFeedback, feedbackRT); // Write } - ConstantBuffer.Push(cmd, parameters.volumetricCB, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesVolumetric); - ConstantBuffer.Set(cmd, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesLightList); + ConstantBuffer.Push(cmd, parameters.volumetricCB, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesVolumetric); + ConstantBuffer.Set(cmd, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesLightList); // The shader defines GROUP_SIZE_1D = 8. cmd.DispatchCompute(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, ((int)parameters.resolution.x + 7) / 8, ((int)parameters.resolution.y + 7) / 8, parameters.viewCount); @@ -843,7 +839,7 @@ static void FilterVolumetricLighting(in VolumetricLightingParameters parameters, { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.VolumetricLightingFiltering))) { - ConstantBuffer.Push(cmd, parameters.volumetricCB, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesVolumetric); + ConstantBuffer.Push(cmd, parameters.volumetricCB, parameters.volumetricLightingCS, HDShaderIDs._ShaderVariablesVolumetric); // The shader defines GROUP_SIZE_1D = 8. cmd.SetComputeTextureParam(parameters.volumetricLightingFilteringCS, parameters.volumetricFilteringKernelX, HDShaderIDs._VBufferLightingFeedback, inputBuffer); // Read diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index e1c9178ea2b..c3d2f63d753 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -112,7 +112,7 @@ void PushGlobalCameraParams(RenderGraph renderGraph, HDCamera hdCamera) { data.hdCamera.UpdateShaderVariableGlobalCB(ref data.globalCB, data.frameCount); data.hdCamera.SetupGlobalParams(context.cmd, data.frameCount); - ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); + ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); }); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index ead0a02ee55..851f9cad33d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -608,12 +608,12 @@ TextureHandle RenderLowResTransparent(RenderGraph renderGraph, HDCamera hdCamera (RenderLowResTransparentPassData data, RenderGraphContext context) => { UpdateOffscreenRenderingConstants(ref data.globalCB, true, 2u); - ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); + ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, context.resources.GetRendererList(data.rendererList)); UpdateOffscreenRenderingConstants(ref data.globalCB, false, 1u); - ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); + ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); }); return passData.lowResBuffer; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 58f42d6ff90..a54e8510f2e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -501,8 +501,6 @@ public HDRenderPipeline(HDRenderPipelineAsset asset, HDRenderPipelineAsset defau m_ColorResolveMaterial = CoreUtils.CreateEngineMaterial(asset.renderPipelineResources.shaders.colorResolvePS); InitializeProbeVolumes(); - - ConstantBuffer.Allocate(); } #if UNITY_EDITOR @@ -959,7 +957,7 @@ void DisposeProbeCameraPool() #endif } - ConstantBuffer.Release(); + ConstantBuffer.ReleaseAll(); CameraCaptureBridge.enabled = false; } @@ -1041,7 +1039,7 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) m_ShaderVariablesGlobalCB._EnableRecursiveRayTracing = 0; } - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); } void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd) @@ -2254,7 +2252,7 @@ void AsyncSSAODispatch(CommandBuffer c, HDGPUAsyncTaskParams a) RenderShadowMaps(renderContext, cmd, m_ShaderVariablesGlobalCB, cullingResults, hdCamera); hdCamera.UpdateShaderVariableGlobalCB(ref m_ShaderVariablesGlobalCB, m_FrameCount); - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); } hdCamera.xr.StartSinglePass(cmd); @@ -3782,7 +3780,7 @@ void RenderLowResTransparent(CullingResults cullResults, HDCamera hdCamera, Scri using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.LowResTransparent))) { UpdateOffscreenRenderingConstants(ref m_ShaderVariablesGlobalCB, true, 2u); - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); CoreUtils.SetRenderTarget(cmd, m_LowResTransparentBuffer, m_SharedRTManager.GetLowResDepthBuffer(), clearFlag: ClearFlag.Color, Color.black); RenderQueueRange transparentRange = HDRenderQueue.k_RenderQueue_LowTransparent; @@ -3791,7 +3789,7 @@ void RenderLowResTransparent(CullingResults cullResults, HDCamera hdCamera, Scri DrawTransparentRendererList(renderContext, cmd, hdCamera.frameSettings, rendererList); UpdateOffscreenRenderingConstants(ref m_ShaderVariablesGlobalCB, false, 1u); - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); } } @@ -4650,14 +4648,14 @@ static void RenderAfterPostProcess( PostProcessParameters parameters, parameters.hdCamera.UpdateShaderVariableGlobalCB(ref parameters.globalCB, parameters.frameCount); UpdateOffscreenRenderingConstants(ref parameters.globalCB, true, 1); - ConstantBuffer.PushGlobal(cmd, parameters.globalCB, HDShaderIDs._ShaderVariablesGlobal); + ConstantBuffer.PushGlobal(cmd, parameters.globalCB, HDShaderIDs._ShaderVariablesGlobal); DrawOpaqueRendererList(renderContext, cmd, parameters.hdCamera.frameSettings, opaqueAfterPostProcessRendererList); // Setup off-screen transparency here DrawTransparentRendererList(renderContext, cmd, parameters.hdCamera.frameSettings, transparentAfterPostProcessRendererList); UpdateOffscreenRenderingConstants(ref parameters.globalCB, false, 1); - ConstantBuffer.PushGlobal(cmd, parameters.globalCB, HDShaderIDs._ShaderVariablesGlobal); + ConstantBuffer.PushGlobal(cmd, parameters.globalCB, HDShaderIDs._ShaderVariablesGlobal); } } From bdc853f08131d86f2597ef0da9ba7c0f0aacd051 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 8 Apr 2020 12:09:04 +0200 Subject: [PATCH 79/92] Updated documentation. --- .../Runtime/Common/ConstantBuffer.cs | 11 +++++++++++ .../ShaderGenerator/ShaderGeneratorAttributes.cs | 2 ++ 2 files changed, 13 insertions(+) diff --git a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs index 75d4f2097d8..74e4468bdcb 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/ConstantBuffer.cs @@ -13,6 +13,7 @@ public class ConstantBuffer /// /// Update the GPU data of the constant buffer and bind it globally. /// + /// The type of structure representing the constant buffer data. /// Command Buffer used to execute the graphic commands. /// Input data of the constant buffer. /// Shader porperty id to bind the constant buffer to. @@ -27,6 +28,7 @@ public static void PushGlobal(CommandBuffer cmd, in CBType data, int sha /// /// Update the GPU data of the constant buffer and bind it to a compute shader. /// + /// The type of structure representing the constant buffer data. /// Command Buffer used to execute the graphic commands. /// Input data of the constant buffer. /// Compute shader to which the constant buffer should be bound. @@ -42,6 +44,7 @@ public static void Push(CommandBuffer cmd, in CBType data, ComputeShader /// /// Update the GPU data of the constant buffer and bind it to a material. /// + /// The type of structure representing the constant buffer data. /// Command Buffer used to execute the graphic commands. /// Input data of the constant buffer. /// Material to which the constant buffer should be bound. @@ -57,6 +60,7 @@ public static void Push(CommandBuffer cmd, in CBType data, Material mat, /// /// Update the GPU data of the constant buffer. /// + /// The type of structure representing the constant buffer data. /// Command Buffer used to execute the graphic commands. /// Input data of the constant buffer. public static void UpdateData(CommandBuffer cmd, in CBType data) where CBType : struct @@ -69,6 +73,7 @@ public static void UpdateData(CommandBuffer cmd, in CBType data) where C /// /// Bind the constant buffer globally. /// + /// The type of structure representing the constant buffer data. /// Command Buffer used to execute the graphic commands. /// Shader porperty id to bind the constant buffer to. public static void SetGlobal(CommandBuffer cmd, int shaderId) where CBType : struct @@ -81,6 +86,7 @@ public static void SetGlobal(CommandBuffer cmd, int shaderId) where CBTy /// /// Bind the constant buffer to a compute shader. /// + /// The type of structure representing the constant buffer data. /// Command Buffer used to execute the graphic commands. /// Compute shader to which the constant buffer should be bound. /// Shader porperty id to bind the constant buffer to. @@ -94,6 +100,7 @@ public static void Set(CommandBuffer cmd, ComputeShader cs, int shaderId /// /// Bind the constant buffer to a material. /// + /// The type of structure representing the constant buffer data. /// Material to which the constant buffer should be bound. /// Shader porperty id to bind the constant buffer to. public static void Set(Material mat, int shaderId) where CBType : struct @@ -103,6 +110,10 @@ public static void Set(Material mat, int shaderId) where CBType : struct cb.Set(mat, shaderId); } + /// + /// Release all currently allocated constant buffers. + /// This needs to be called before shutting down the application. + /// public static void ReleaseAll() { foreach (var cb in m_RegisteredConstantBuffers) diff --git a/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs b/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs index 27c2445529a..f462b665016 100644 --- a/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs +++ b/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs @@ -113,6 +113,8 @@ public class GenerateHLSL : System.Attribute /// Start value of debug defines. /// Omit structure declaration. /// Contains packed fields. + /// Generate a constant buffer. + /// When generating a constant buffer, specify the optional constant register. public GenerateHLSL(PackingRules rules = PackingRules.Exact, bool needAccessors = true, bool needSetters = false, bool needParamDebug = false, int paramDefinesStart = 1, bool omitStructDeclaration = false, bool containsPackedFields = false, bool generateCBuffer = false, int constantRegister = -1) { From 7931d30f6a636aafa23d805f8c81e48cc32b8516 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 8 Apr 2020 12:51:59 +0200 Subject: [PATCH 80/92] Missing generated file --- .../Runtime/Debug/DebugDisplay.cs.hlsl | 1 + 1 file changed, 1 insertion(+) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl index ffc2248c367..58894ef6ba6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl @@ -63,6 +63,7 @@ CBUFFER_START(ShaderVariablesDebugDisplay) int _MatcapMixAlbedo; float _MatcapViewScale; int _DebugSingleShadowIndex; + int _DebugProbeVolumeMode; CBUFFER_END From 23cb219003a2a9e09d5df9a1b14145548195961f Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Wed, 8 Apr 2020 14:31:53 +0200 Subject: [PATCH 81/92] Post merge fix --- .../Lighting/Shadow/ScreenSpaceShadowManager.cs | 8 ++++---- .../SubsurfaceScatteringManager.cs | 2 +- .../Runtime/RenderPipeline/HDRenderPipeline.cs | 2 +- .../RenderPipeline/PathTracing/PathTracing.cs | 2 +- .../Raytracing/HDRaytracingAmbientOcclusion.cs | 2 +- .../Raytracing/HDRaytracingDeferredLightLoop.cs | 2 +- .../Raytracing/HDRaytracingIndirectDiffuse.cs | 2 +- .../RenderPipeline/Raytracing/HDRaytracingManager.cs | 12 ++++++------ .../Raytracing/HDRaytracingRecursiveRenderer.cs | 2 +- .../Raytracing/HDRaytracingReflection.cs | 4 ++-- 10 files changed, 19 insertions(+), 19 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs index 0b720a634a6..5f235036c06 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs @@ -338,7 +338,7 @@ void RenderDirectionalLightScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamer // Update global Constant Buffer m_ShaderVariablesRayTracingCB._RaytracingSampleIndex = sampleIdx; m_ShaderVariablesRayTracingCB._RaytracingNumSamples = m_CurrentSunLightAdditionalLightData.numRayTracingSamples; - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind the light & sampling data cmd.SetComputeBufferParam(m_ScreenSpaceShadowsCS, m_RaytracingDirectionalShadowSample, HDShaderIDs._DirectionalLightDatas, m_LightLoopLightData.directionalLightData); @@ -534,7 +534,7 @@ void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera cmd.SetComputeIntParam(m_ScreenSpaceShadowsCS, HDShaderIDs._RaytracingTargetAreaLight, lightIndex); m_ShaderVariablesRayTracingCB._RaytracingNumSamples = additionalLightData.numRayTracingSamples; - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind the input buffers cmd.SetComputeTextureParam(m_ScreenSpaceShadowsCS, m_AreaRaytracingAreaShadowPrepassKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); @@ -591,7 +591,7 @@ void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera // Update global Constant Buffer m_ShaderVariablesRayTracingCB._RaytracingNumSamples = additionalLightData.numRayTracingSamples; m_ShaderVariablesRayTracingCB._RaytracingSampleIndex = sampleIndex; - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind the light data cmd.SetComputeBufferParam(m_ScreenSpaceShadowsCS, m_AreaRaytracingAreaShadowNewSampleKernel, HDShaderIDs._LightDatas, m_LightLoopLightData.lightData); @@ -774,7 +774,7 @@ void RenderPunctualScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera // Update global constant buffer m_ShaderVariablesRayTracingCB._RaytracingSampleIndex = sampleIdx; m_ShaderVariablesRayTracingCB._RaytracingNumSamples = additionalLightData.numRayTracingSamples; - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind the right kernel int shadowKernel = lightData.lightType == GPULightType.Point ? m_RaytracingPointShadowSample : m_RaytracingSpotShadowSample; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index 705b79fa46a..7bbfc60965d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -322,7 +322,7 @@ void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle c // Inject the ray generation data m_ShaderVariablesRayTracingCB._RaytracingNumSamples = settings.sampleCount.value; m_ShaderVariablesRayTracingCB._RaytracingSampleIndex = sampleIndex; - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind the textures for ray generation cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._DepthTexture, sharedRTManager.GetDepthStencilBuffer()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 5755fe5f7d4..b704b54009c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -1074,7 +1074,7 @@ void UpdateShaderVariablesRaytracingCB(HDCamera hdCamera, CommandBuffer cmd) m_ShaderVariablesRayTracingCB._RaytracingReflectionMinSmoothness = screenSpaceReflection.minSmoothness.value; m_ShaderVariablesRayTracingCB._RaytracingReflectionSmoothnessFadeStart = screenSpaceReflection.smoothnessFadeStart.value; - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); } void CopyDepthBufferIfNeeded(HDCamera hdCamera, CommandBuffer cmd) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs index 18f4f0ca94c..fa7d6ba4865 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs @@ -248,7 +248,7 @@ void RenderPathTracing(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputText m_ShaderVariablesRayTracingCB._RaytracingMaxRecursion = m_PathTracingSettings.maximumDepth.value; m_ShaderVariablesRayTracingCB._RaytracingIntensityClamp = m_PathTracingSettings.maximumIntensity.value; m_ShaderVariablesRayTracingCB._RaytracingSampleIndex = (int)m_SubFrameManager.iteration; - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // LightLoop data cmd.SetGlobalBuffer(HDShaderIDs._RaytracingLightCluster, lightCluster.GetCluster()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs index 6f0ceea9e21..f1c25001cb7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs @@ -88,7 +88,7 @@ public void RenderAO(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputTextur // Inject the ray generation data (be careful of the global constant buffer limitation) globalCB._RaytracingRayMaxLength = aoSettings.rayLength.value; globalCB._RaytracingNumSamples = aoSettings.sampleCount.value; - ConstantBuffer.PushGlobal(cmd, globalCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, globalCB, HDShaderIDs._ShaderVariablesRaytracing); // Set the data for the ray generation cmd.SetRayTracingTextureParam(aoShader, HDShaderIDs._DepthTexture, m_RenderPipeline.sharedRTManager.GetDepthStencilBuffer()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.cs index 3a3488d7ca0..77cbc5d6eec 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.cs @@ -183,7 +183,7 @@ static void RenderRaytracingDeferredLighting(CommandBuffer cmd, in DeferredLight } // Inject the global parameters - ConstantBuffer.PushGlobal(cmd, parameters.globalCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, parameters.globalCB, HDShaderIDs._ShaderVariablesRaytracing); // Define the shader pass to use for the reflection pass cmd.SetRayTracingShaderPass(parameters.gBufferRaytracingRT, "GBufferDXR"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs index b01effa2c9f..e044c41d4bd 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs @@ -281,7 +281,7 @@ void BindRayTracedIndirectDiffuseData(CommandBuffer cmd, HDCamera hdCamera m_ShaderVariablesRayTracingCB._RaytracingNumSamples = settings.sampleCount.value; m_ShaderVariablesRayTracingCB._RaytracingIntensityClamp = settings.clampValue.value; m_ShaderVariablesRayTracingCB._RaytracingMaxRecursion = settings.bounceCount.value; - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); } void RenderIndirectDiffuseQuality(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, int frameCount) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs index 1712da69e75..6a2bfbe54ab 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs @@ -562,7 +562,7 @@ internal int RayTracingFrameIndex(HDCamera hdCamera) #endif return hdCamera.IsTAAEnabled() ? hdCamera.taaFrameIndex : (int)m_FrameCount % 8; } - + internal bool RayTracingLightClusterRequired(HDCamera hdCamera) { ScreenSpaceReflection reflSettings = hdCamera.volumeStack.GetComponent(); @@ -571,10 +571,10 @@ internal bool RayTracingLightClusterRequired(HDCamera hdCamera) PathTracing pathTracingSettings = hdCamera.volumeStack.GetComponent(); SubSurfaceScattering subSurface = hdCamera.volumeStack.GetComponent(); - return (m_ValidRayTracingState && (reflSettings.rayTracing.value - || giSettings.rayTracing.value - || recursiveSettings.enable.value - || pathTracingSettings.enable.value + return (m_ValidRayTracingState && (reflSettings.rayTracing.value + || giSettings.rayTracing.value + || recursiveSettings.enable.value + || pathTracingSettings.enable.value || subSurface.rayTracing.value)); } @@ -615,7 +615,7 @@ void UpdateShaderVariablesRaytracingLightLoopCB(HDCamera hdCamera, CommandBuffer m_ShaderVariablesRaytracingLightLoopCB._AreaLightCountRT = (uint)m_RayTracingLightCluster.GetAreaLightCount(); m_ShaderVariablesRaytracingLightLoopCB._EnvLightCountRT = (uint)m_RayTracingLightCluster.GetEnvLightCount(); - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRaytracingLightLoopCB, HDShaderIDs._ShaderVariablesRaytracingLightLoop); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRaytracingLightLoopCB, HDShaderIDs._ShaderVariablesRaytracingLightLoop); } internal RayTracingAccelerationStructure RequestAccelerationStructure() diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs index 83d73d2f704..32d1f876c97 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs @@ -80,7 +80,7 @@ void RaytracingRecursiveRender(HDCamera hdCamera, CommandBuffer cmd, ScriptableR // Update Global Constant Buffer. m_ShaderVariablesRayTracingCB._RaytracingRayMaxLength = recursiveSettings.rayLength.value; m_ShaderVariablesRayTracingCB._RaytracingMaxRecursion = recursiveSettings.maxDepth.value; - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Fecth the temporary buffers we shall be using RTHandle flagBuffer = GetRayTracingBuffer(InternalRayTracingBuffers.R0); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs index 9719542ff11..e5e8205ad1c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs @@ -65,7 +65,7 @@ void BindRayTracedReflectionData(CommandBuffer cmd, HDCamera hdCamera, RayTracin m_ShaderVariablesRayTracingCB._RaytracingNumSamples = settings.sampleCount.value; // Set the number of bounces for reflections m_ShaderVariablesRayTracingCB._RaytracingMaxRecursion = settings.bounceCount.value; - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Inject the ray-tracing sampling data blueNoise.BindDitheredRNGData8SPP(cmd); @@ -191,7 +191,7 @@ void RenderReflectionsPerformance(HDCamera hdCamera, CommandBuffer cmd, RTHandle // Bind all the required scalars m_ShaderVariablesRayTracingCB._RaytracingIntensityClamp = settings.clampValue.value; m_ShaderVariablesRayTracingCB._RaytracingIncludeSky = settings.reflectSky.value ? 1 : 0; - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind the output buffers cmd.SetComputeTextureParam(reflectionShaderCS, currentKernel, HDShaderIDs._RaytracingDirectionBuffer, intermediateBuffer1); From 1b1a370510365caccdf9069b78e0f5e8b09e4a7e Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 9 Apr 2020 12:04:33 +0200 Subject: [PATCH 82/92] Fixed various issues with light probe volumes. --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 8 ++-- .../ProbeVolume/ProbeVolumeLighting.cs | 39 ++++++++++++++++++- .../HDRenderPipeline.LightLoop.cs | 2 +- .../RenderPipeline/HDStringConstants.cs | 2 + 4 files changed, 44 insertions(+), 7 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 3b96b4457d3..963544640d6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3150,7 +3150,7 @@ static bool DeferredUseComputeAsPixel(FrameSettings frameSettings) return frameSettings.IsEnabled(FrameSettingsField.DeferredTile) && (!frameSettings.IsEnabled(FrameSettingsField.ComputeLightEvaluation) || k_PreferFragment); } - unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera hdCamera) + unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera hdCamera, bool buildForProbeVolumes) { BuildGPULightListParameters parameters = new BuildGPULightListParameters(); @@ -3203,7 +3203,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera h cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); - cb.g_iNrVisibLights = m_TotalLightCount; + cb.g_iNrVisibLights = buildForProbeVolumes ? m_TotalLightCount : m_probeVolumeCount; cb.g_isOrthographic = camera.orthographic ? 1u : 0u; cb.g_BaseFeatureFlags = 0; // Filled for each individual pass. cb.g_iNumSamplesMSAA = (int)hdCamera.msaaSamples; @@ -3383,7 +3383,7 @@ void BuildGPULightListProbeVolumesCommon(HDCamera hdCamera, CommandBuffer cmd) { // TODO: (Nick): These parameters can be cached and shared between BuildGPULightListProbeVolumesCommon and BuildGPULightListsCommon. // Currently, we are generated them twice. - var parameters = PrepareBuildGPULightListParameters(hdCamera); + var parameters = PrepareBuildGPULightListParameters(hdCamera, true); var resources = PrepareBuildGPULightListResources( m_TileAndClusterData, m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), @@ -3478,7 +3478,7 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BuildLightList))) { - var parameters = PrepareBuildGPULightListParameters(hdCamera); + var parameters = PrepareBuildGPULightListParameters(hdCamera, false); var resources = PrepareBuildGPULightListResources( m_TileAndClusterData, m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeLighting.cs index 512251f27bc..8d3803f4235 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeLighting.cs @@ -417,7 +417,18 @@ internal bool EnsureProbeVolumeInAtlas(ScriptableRenderContext renderContext, Co cmd.SetComputeVectorParam(s_ProbeVolumeAtlasBlitCS, HDShaderIDs._ProbeVolumeAtlasBias, volume.parameters.bias ); - + cmd.SetComputeVectorParam(s_ProbeVolumeAtlasBlitCS, HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCount, new Vector4( + s_ProbeVolumeAtlasWidth, + s_ProbeVolumeAtlasHeight, + s_ProbeVolumeAtlasDepth, + m_ProbeVolumeAtlasSHRTDepthSliceCount + )); + cmd.SetComputeVectorParam(s_ProbeVolumeAtlasBlitCS, HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCountInverse, new Vector4( + 1.0f / (float)s_ProbeVolumeAtlasWidth, + 1.0f / (float)s_ProbeVolumeAtlasHeight, + 1.0f / (float)s_ProbeVolumeAtlasDepth, + 1.0f / (float)m_ProbeVolumeAtlasSHRTDepthSliceCount + )); Debug.Assert(data.Length == size, "ProbeVolume: The probe volume baked data and its resolution are out of sync! Volume data length is " + data.Length + ", but resolution size is " + size + "."); Debug.Assert(size < s_MaxProbeVolumeProbeCount, "ProbeVolume: probe volume baked data size exceeds the currently max supported blitable size. Volume data size is " + size + ", but s_MaxProbeVolumeProbeCount is " + s_MaxProbeVolumeProbeCount + ". Please decrease ProbeVolume resolution, or increase ProbeVolumeLighting.s_MaxProbeVolumeProbeCount."); @@ -484,7 +495,18 @@ internal bool EnsureProbeVolumeInAtlasOctahedralDepth(ScriptableRenderContext re cmd.SetComputeVectorParam(s_ProbeVolumeAtlasOctahedralDepthBlitCS, HDShaderIDs._ProbeVolumeAtlasOctahedralDepthScaleBias, volume.parameters.octahedralDepthScaleBias ); - + cmd.SetComputeVectorParam(s_ProbeVolumeAtlasOctahedralDepthBlitCS, HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCount, new Vector4( + s_ProbeVolumeAtlasWidth, + s_ProbeVolumeAtlasHeight, + s_ProbeVolumeAtlasDepth, + m_ProbeVolumeAtlasSHRTDepthSliceCount + )); + cmd.SetComputeVectorParam(s_ProbeVolumeAtlasOctahedralDepthBlitCS, HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCountInverse, new Vector4( + 1.0f / (float)s_ProbeVolumeAtlasWidth, + 1.0f / (float)s_ProbeVolumeAtlasHeight, + 1.0f / (float)s_ProbeVolumeAtlasDepth, + 1.0f / (float)m_ProbeVolumeAtlasSHRTDepthSliceCount + )); Debug.Assert(dataOctahedralDepth.Length == size, "ProbeVolume: The probe volume baked data and its resolution are out of sync! Volume data length is " + dataOctahedralDepth.Length + ", but resolution size is " + size + "."); s_ProbeVolumeAtlasOctahedralDepthBuffer.SetData(dataOctahedralDepth); @@ -796,6 +818,19 @@ void DisplayProbeVolumeAtlas(CommandBuffer cmd, Material debugMaterial, float sc propertyBlock.SetVector(HDShaderIDs._TextureViewScale, textureViewScale); propertyBlock.SetVector(HDShaderIDs._TextureViewBias, textureViewBias); propertyBlock.SetVector(HDShaderIDs._TextureViewResolution, textureViewResolution); + cmd.SetGlobalVector(HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCount, new Vector4( + s_ProbeVolumeAtlasWidth, + s_ProbeVolumeAtlasHeight, + s_ProbeVolumeAtlasDepth, + m_ProbeVolumeAtlasSHRTDepthSliceCount + )); + cmd.SetGlobalVector(HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCountInverse, new Vector4( + 1.0f / (float)s_ProbeVolumeAtlasWidth, + 1.0f / (float)s_ProbeVolumeAtlasHeight, + 1.0f / (float)s_ProbeVolumeAtlasDepth, + 1.0f / (float)m_ProbeVolumeAtlasSHRTDepthSliceCount + )); + propertyBlock.SetTexture(HDShaderIDs._AtlasTextureOctahedralDepth, m_ProbeVolumeAtlasOctahedralDepthRTHandle); propertyBlock.SetVector(HDShaderIDs._AtlasTextureOctahedralDepthScaleBias, atlasTextureOctahedralDepthScaleBias); propertyBlock.SetVector(HDShaderIDs._ValidRange, validRange); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 561925bf85b..d80da1bbf3f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -46,7 +46,7 @@ void BuildGPULightList(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle passData.shadowGlobalParameters = PrepareShadowGlobalParameters(hdCamera); passData.lightLoopGlobalParameters = PrepareLightLoopGlobalParameters(hdCamera); - passData.buildGPULightListParameters = PrepareBuildGPULightListParameters(hdCamera); + passData.buildGPULightListParameters = PrepareBuildGPULightListParameters(hdCamera, false); // TODO: Move this inside the render function onces compute buffers are RenderGraph ready passData.buildGPULightListResources = PrepareBuildGPULightListResources(m_TileAndClusterData, null, null, isGBufferNeeded: true); passData.depthBuffer = builder.ReadTexture(depthStencilBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index e37d9b9ef33..5aae2d21c6d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -767,6 +767,8 @@ static class HDShaderIDs // Probe Volumes public static readonly int _ProbeVolumeAtlasSH = Shader.PropertyToID("_ProbeVolumeAtlasSH"); + public static readonly int _ProbeVolumeAtlasResolutionAndSliceCount = Shader.PropertyToID("_ProbeVolumeAtlasResolutionAndSliceCount"); + public static readonly int _ProbeVolumeAtlasResolutionAndSliceCountInverse = Shader.PropertyToID("_ProbeVolumeAtlasResolutionAndSliceCountInverse"); public static readonly int _ProbeVolumeAtlasOctahedralDepth = Shader.PropertyToID("_ProbeVolumeAtlasOctahedralDepth"); public static readonly int _ProbeVolumeResolution = Shader.PropertyToID("_ProbeVolumeResolution"); public static readonly int _ProbeVolumeResolutionInverse = Shader.PropertyToID("_ProbeVolumeResolutionInverse"); From cccf44e48b5fe5f8989866bc3a6a7ab89e6f3dcc Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 9 Apr 2020 16:42:31 +0200 Subject: [PATCH 83/92] Fixed light list build parameters and a nullref exception when probe volumes aren't enable and there are volumes in the scene. --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 2 +- .../Runtime/Lighting/ProbeVolume/ProbeVolume.cs | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 963544640d6..b8e7bf382ac 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3203,7 +3203,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera h cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); - cb.g_iNrVisibLights = buildForProbeVolumes ? m_TotalLightCount : m_probeVolumeCount; + cb.g_iNrVisibLights = buildForProbeVolumes ? m_probeVolumeCount : m_TotalLightCount; cb.g_isOrthographic = camera.orthographic ? 1u : 0u; cb.g_BaseFeatureFlags = 0; // Filled for each individual pass. cb.g_iNumSamplesMSAA = (int)hdCamera.msaaSamples; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolume.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolume.cs index 7238b18e7e2..e5b42e8642c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolume.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolume.cs @@ -601,6 +601,9 @@ private void SetupProbePositions() private static bool ShouldDrawGizmos(ProbeVolume probeVolume) { + if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.Disabled) + return false; + UnityEditor.SceneView sceneView = UnityEditor.SceneView.currentDrawingSceneView; if (sceneView == null) From 7510e08abaa78388b215f75d17b27c9c54b74f40 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Thu, 9 Apr 2020 18:19:40 +0200 Subject: [PATCH 84/92] Final fix for probe volumes --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index b8e7bf382ac..efaf3c8cc34 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3351,7 +3351,10 @@ static void ClearLightListsProbeVolumes( in BuildGPULightListResources resources, CommandBuffer cmd) { - if(parameters.probeVolumesClearLightLists && !parameters.probeVolumesRunLightList) + // ClearLightLists is the first pass, we push the global parameters for light list building here. + ConstantBuffer.PushGlobal(cmd, parameters.lightListCB, HDShaderIDs._ShaderVariablesLightList); + + if (parameters.probeVolumesClearLightLists && !parameters.probeVolumesRunLightList) { // Note we clear the whole content and not just the header since it is fast enough, happens only in one frame and is a bit more robust // to changes to the inner workings of the lists. From f6cddbe2aee6c17ba7ef16caeb4cf0087b20f199 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 10 Apr 2020 10:50:35 +0200 Subject: [PATCH 85/92] Fixed a warning in shader compilation --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 16 ++++++++-------- .../Runtime/Lighting/LightLoop/LightLoop.cs.hlsl | 8 ++++---- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index efaf3c8cc34..7f4462edf89 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -229,11 +229,11 @@ unsafe struct ShaderVariablesLightList public uint g_BaseFeatureFlags; public int g_iNumSamplesMSAA; - public int _EnvLightIndexShift; - public int _DecalIndexShift; + public uint _EnvLightIndexShift; + public uint _DecalIndexShift; - public int _DensityVolumeIndexShift; - public int _ProbeVolumeIndexShift; + public uint _DensityVolumeIndexShift; + public uint _ProbeVolumeIndexShift; } internal struct ProcessedLightData @@ -3207,14 +3207,14 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera h cb.g_isOrthographic = camera.orthographic ? 1u : 0u; cb.g_BaseFeatureFlags = 0; // Filled for each individual pass. cb.g_iNumSamplesMSAA = (int)hdCamera.msaaSamples; - cb._EnvLightIndexShift = m_lightList.lights.Count; - cb._DecalIndexShift = m_lightList.lights.Count + m_lightList.envLights.Count; - cb._DensityVolumeIndexShift = m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount; + cb._EnvLightIndexShift = (uint)m_lightList.lights.Count; + cb._DecalIndexShift = (uint)(m_lightList.lights.Count + m_lightList.envLights.Count); + cb._DensityVolumeIndexShift = (uint)(m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount); int probeVolumeIndexShift = (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.LightLoop) ? (m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount + m_densityVolumeCount) : 0; - cb._ProbeVolumeIndexShift = probeVolumeIndexShift; + cb._ProbeVolumeIndexShift = (uint)probeVolumeIndexShift; parameters.lightListCB = m_ShaderVariablesLightListCB; parameters.runLightList = m_TotalLightCount > 0; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index 7e14845c238..d103a40977a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -103,10 +103,10 @@ CBUFFER_START(ShaderVariablesLightList) uint g_isOrthographic; uint g_BaseFeatureFlags; int g_iNumSamplesMSAA; - int _EnvLightIndexShift; - int _DecalIndexShift; - int _DensityVolumeIndexShift; - int _ProbeVolumeIndexShift; + uint _EnvLightIndexShift; + uint _DecalIndexShift; + uint _DensityVolumeIndexShift; + uint _ProbeVolumeIndexShift; CBUFFER_END // From 224a7185eb615044c1e0dfc5ac17f7edd43a0fc9 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 10 Apr 2020 11:49:09 +0200 Subject: [PATCH 86/92] Changes from review feedback --- .../Runtime/Debug/DebugDisplay.cs | 3 ++- .../Runtime/Debug/DebugDisplay.cs.hlsl | 1 + .../Runtime/Lighting/LightLoop/LightLoop.cs | 4 ++-- .../ShaderVariablesScreenSpaceReflection.cs | 1 + .../ShaderVariablesScreenSpaceReflection.cs.hlsl | 1 + .../Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs | 2 +- .../Runtime/RenderPipeline/HDRenderPipeline.cs | 2 +- 7 files changed, 9 insertions(+), 5 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs index 5e2194946d2..fd4582b518c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs @@ -11,7 +11,7 @@ unsafe struct ShaderVariablesDebugDisplay [HLSLArray(32, typeof(Vector4))] public fixed float _DebugRenderingLayersColors[32 * 4]; [HLSLArray(11, typeof(ShaderGenUInt4))] - public fixed int _DebugViewMaterialArray[11 * 4]; // Contain the id (define in various materialXXX.cs.hlsl) of the property to display + public fixed uint _DebugViewMaterialArray[11 * 4]; // Contain the id (define in various materialXXX.cs.hlsl) of the property to display public int _DebugLightingMode; // Match enum DebugLightingMode public int _DebugLightLayersMask; @@ -41,6 +41,7 @@ unsafe struct ShaderVariablesDebugDisplay public int _DebugSingleShadowIndex; public int _DebugProbeVolumeMode; + public Vector3 _Pad0; } /// diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl index 58894ef6ba6..f28e0f68e71 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl @@ -64,6 +64,7 @@ CBUFFER_START(ShaderVariablesDebugDisplay) float _MatcapViewScale; int _DebugSingleShadowIndex; int _DebugProbeVolumeMode; + float3 _Pad0; CBUFFER_END diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 7f4462edf89..f51c0cda105 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3386,7 +3386,7 @@ void BuildGPULightListProbeVolumesCommon(HDCamera hdCamera, CommandBuffer cmd) { // TODO: (Nick): These parameters can be cached and shared between BuildGPULightListProbeVolumesCommon and BuildGPULightListsCommon. // Currently, we are generated them twice. - var parameters = PrepareBuildGPULightListParameters(hdCamera, true); + var parameters = PrepareBuildGPULightListParameters(hdCamera, buildForProbeVolumes: true); var resources = PrepareBuildGPULightListResources( m_TileAndClusterData, m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), @@ -3481,7 +3481,7 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BuildLightList))) { - var parameters = PrepareBuildGPULightListParameters(hdCamera, false); + var parameters = PrepareBuildGPULightListParameters(hdCamera, buildForProbeVolumes: false); var resources = PrepareBuildGPULightListResources( m_TileAndClusterData, m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs index 14519878cd4..0b132d26320 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs @@ -18,5 +18,6 @@ unsafe struct ShaderVariablesScreenSpaceReflection public int _SsrDepthPyramidMaxMip; public int _SsrColorPyramidMaxMip; public int _SsrReflectsSky; + public float _Pad0; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl index 11b4e9287f0..45b2a5ec4d5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl @@ -19,6 +19,7 @@ CBUFFER_START(ShaderVariablesScreenSpaceReflection) int _SsrDepthPyramidMaxMip; int _SsrColorPyramidMaxMip; int _SsrReflectsSky; + float _Pad0; CBUFFER_END diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index d80da1bbf3f..af2f4eff735 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -46,7 +46,7 @@ void BuildGPULightList(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle passData.shadowGlobalParameters = PrepareShadowGlobalParameters(hdCamera); passData.lightLoopGlobalParameters = PrepareLightLoopGlobalParameters(hdCamera); - passData.buildGPULightListParameters = PrepareBuildGPULightListParameters(hdCamera, false); + passData.buildGPULightListParameters = PrepareBuildGPULightListParameters(hdCamera, buildForProbeVolumes: false); // TODO: Move this inside the render function onces compute buffers are RenderGraph ready passData.buildGPULightListResources = PrepareBuildGPULightListResources(m_TileAndClusterData, null, null, isGBufferNeeded: true); passData.depthBuffer = builder.ReadTexture(depthStencilBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 63ba34fb5ab..cfae6bf8bca 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -4135,7 +4135,7 @@ unsafe void ApplyDebugDisplaySettings(HDCamera hdCamera, CommandBuffer cmd) var debugMaterialIndices = m_CurrentDebugDisplaySettings.GetDebugMaterialIndexes(); for (int i = 0; i < 11; ++i) { - cb._DebugViewMaterialArray[i * 4] = (int)debugMaterialIndices[i]; // Only x component is used. + cb._DebugViewMaterialArray[i * 4] = (uint)debugMaterialIndices[i]; // Only x component is used. } for (int i = 0; i < 32; ++i) { From 2963ec6e097235d0277bb911835cae940d36c9e6 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 10 Apr 2020 12:09:18 +0200 Subject: [PATCH 87/92] Compilation fix. --- .../Runtime/Debug/DebugDisplay.cs | 2 +- .../Runtime/Debug/DebugDisplay.cs.hlsl | 2 +- .../ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs | 2 +- .../ShaderVariablesScreenSpaceReflection.cs.hlsl | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs index fd4582b518c..83734e5133b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs @@ -41,7 +41,7 @@ unsafe struct ShaderVariablesDebugDisplay public int _DebugSingleShadowIndex; public int _DebugProbeVolumeMode; - public Vector3 _Pad0; + public Vector3 _DebugDisplayPad0; } /// diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl index f28e0f68e71..527e6c9998c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl @@ -64,7 +64,7 @@ CBUFFER_START(ShaderVariablesDebugDisplay) float _MatcapViewScale; int _DebugSingleShadowIndex; int _DebugProbeVolumeMode; - float3 _Pad0; + float3 _DebugDisplayPad0; CBUFFER_END diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs index 0b132d26320..d0be0791579 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs @@ -18,6 +18,6 @@ unsafe struct ShaderVariablesScreenSpaceReflection public int _SsrDepthPyramidMaxMip; public int _SsrColorPyramidMaxMip; public int _SsrReflectsSky; - public float _Pad0; + public float _ScreenSpaceReflectionPad0; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl index 45b2a5ec4d5..c9eb01809ca 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ShaderVariablesScreenSpaceReflection.cs.hlsl @@ -19,7 +19,7 @@ CBUFFER_START(ShaderVariablesScreenSpaceReflection) int _SsrDepthPyramidMaxMip; int _SsrColorPyramidMaxMip; int _SsrReflectsSky; - float _Pad0; + float _ScreenSpaceReflectionPad0; CBUFFER_END From 1e4112ab9c1cf2fed2d1c2e533933911b343e511 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 10 Apr 2020 14:05:37 +0200 Subject: [PATCH 88/92] Post merge fix --- .../Runtime/RenderPipeline/HDRenderPipeline.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 72546ac39eb..b55befa9b83 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -178,6 +178,7 @@ internal static Volume GetOrCreateDefaultVolume() ShaderVariablesGlobal m_ShaderVariablesGlobalCB = new ShaderVariablesGlobal(); ShaderVariablesXR m_ShaderVariablesXRCB = new ShaderVariablesXR(); ShaderVariablesDebugDisplay m_ShaderVariablesDebugDisplayCB = new ShaderVariablesDebugDisplay(); + ShaderVariablesRaytracing m_ShaderVariablesRayTracingCB = new ShaderVariablesRaytracing(); // The current MSAA count MSAASamples m_MSAASamples; @@ -1051,13 +1052,14 @@ void UpdateShaderVariablesGlobalCB(HDCamera hdCamera, CommandBuffer cmd) } ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); + } void UpdateShaderVariablesXRCB(HDCamera hdCamera, CommandBuffer cmd) + { hdCamera.UpdateShaderVariablesXRCB(ref m_ShaderVariablesXRCB); ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesXRCB, HDShaderIDs._ShaderVariablesXR); } - ShaderVariablesRaytracing m_ShaderVariablesRayTracingCB = new ShaderVariablesRaytracing(); void UpdateShaderVariablesRaytracingCB(HDCamera hdCamera, CommandBuffer cmd) { From 2c4a73c59d4e2c5b6a201eb2747946c0b745a4d9 Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Fri, 10 Apr 2020 14:41:42 +0200 Subject: [PATCH 89/92] Removed useless constant --- .../Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl | 4 ---- 1 file changed, 4 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl index 1b96dc02fd1..6ef4ea2a0f7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl @@ -12,10 +12,6 @@ #define GLOBAL_CBUFFER_START(name, reg) CBUFFER_START(name) #endif -// Global Constant Buffers - b registers. Unity supports a maximum of 16 global constant buffers. - // Ray tracing specific constant buffers -#define UNITY_RAY_TRACING_GLOBAL_CBUFFER_REGISTER b3 - // Global Input Resources - t registers. Unity supports a maximum of 64 global input resources (compute buffers, textures, acceleration structure). #define RAY_TRACING_ACCELERATION_STRUCTURE_REGISTER t0 #define RAY_TRACING_LIGHT_CLUSTER_REGISTER t1 From eb32060aab2a333cf38be6785ea4262b1d8a379a Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 5 May 2020 18:02:54 +0200 Subject: [PATCH 90/92] Crash fix --- .../RenderPipeline/Raytracing/HDRaytracingLightCluster.cs | 7 +++++++ .../RenderPipeline/Raytracing/HDRaytracingManager.cs | 2 ++ 2 files changed, 9 insertions(+) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs index 0e0be43a642..3f2bf953156 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs @@ -731,7 +731,14 @@ public void CullForRayTracing(CommandBuffer cmd, HDCamera hdCamera, HDRayTracing // Evaluate the volume of the cluster EvaluateClusterVolume(hdCamera); + } + public void BuildLightClusterBuffer(CommandBuffer cmd, HDCamera hdCamera, HDRayTracingLights rayTracingLights) + { + // If there is no lights to process or no environment not the shader is missing + if (totalLightCount == 0 || rayTracingLights.lightCount == 0 || !m_RenderPipeline.GetRayTracingState()) + return; + // Cull the lights within the evaluated cluster range CullLights(cmd); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs index 6a2bfbe54ab..69cbb1d5db1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs @@ -603,6 +603,8 @@ internal void BuildRayTracingLightData(CommandBuffer cmd, HDCamera hdCamera, Deb m_ValidRayTracingCluster = true; UpdateShaderVariablesRaytracingLightLoopCB(hdCamera, cmd); + + m_RayTracingLightCluster.BuildLightClusterBuffer(cmd, hdCamera, m_RayTracingLights); } } From 61d1ef27d61cc7e6d59abda8d9fe7430ce802b9b Mon Sep 17 00:00:00 2001 From: Julien Ignace Date: Tue, 19 May 2020 14:33:00 +0200 Subject: [PATCH 91/92] Post merge fix --- .../ScreenSpaceGlobalIllumination.cs | 18 +++++++++++------- .../Runtime/RenderPipeline/HDRenderPipeline.cs | 3 +++ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.cs index 9a0d4ee6cd4..44bd8e5a50e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.cs @@ -28,7 +28,7 @@ void InitScreenSpaceGlobalIllumination() m_IndirectDiffuseBuffer0 = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, dimension: TextureXR.dimension, enableRandomWrite: true, useDynamicScale: true, useMipMap: false, autoGenerateMips: false, name: "IndirectDiffuseBuffer0"); m_IndirectDiffuseBuffer1 = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, dimension: TextureXR.dimension, enableRandomWrite: true, useDynamicScale: true, useMipMap: false, autoGenerateMips: false, name: "IndirectDiffuseBuffer1"); m_IndirectDiffuseHitPointBuffer = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R16G16_SFloat, dimension: TextureXR.dimension, enableRandomWrite: true, useDynamicScale: true, useMipMap: false, autoGenerateMips: false, name: "IndirectDiffuseHitBuffer"); - + // Grab the sets of shaders that we'll be using ComputeShader ssGICS = m_Asset.renderPipelineResources.shaders.screenSpaceGlobalIlluminationCS; ComputeShader bilateralUpsampleCS = m_Asset.renderPipelineResources.shaders.bilateralUpsampleCS; @@ -68,7 +68,7 @@ void BindIndirectDiffuseTexture(CommandBuffer cmd) cmd.SetGlobalTexture(HDShaderIDs._IndirectDiffuseTexture, m_IndirectDiffuseBuffer0); } - // If there is no SSGI, bind a black 1x1 texture + // If there is no SSGI, bind a black 1x1 texture void BindBlackIndirectDiffuseTexture(CommandBuffer cmd) { cmd.SetGlobalTexture(HDShaderIDs._IndirectDiffuseTexture, TextureXR.GetBlackTexture()); @@ -152,10 +152,14 @@ void RenderSSGI(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext re // Fetch the right kernel to use currentKernel = giSettings.fullResolutionSS ? m_ReprojectGlobalIlluminationKernel : m_ReprojectGlobalIlluminationHalfKernel; + // Update global constant buffer. + // This should probably be a shader specific uniform instead of reusing the global constant buffer one since it's the only one udpated here. + m_ShaderVariablesRayTracingCB._RaytracingIntensityClamp = giSettings.clampValueSS; + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); + // Inject all the input scalars - cmd.SetComputeFloatParam(ssGICS, HDShaderIDs._RaytracingIntensityClamp, giSettings.clampValueSS); cmd.SetComputeVectorParam(ssGICS, HDShaderIDs._ColorPyramidUvScaleAndLimitPrevFrame, HDUtils.ComputeViewportScaleAndLimit(hdCamera.historyRTHandleProperties.previousViewportSize, hdCamera.historyRTHandleProperties.previousRenderTargetSize)); - + // Bind all the input buffers cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); @@ -165,7 +169,7 @@ void RenderSSGI(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext re var historyDepthBuffer = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Depth); cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._HistoryDepthTexture, historyDepthBuffer != null ? historyDepthBuffer : TextureXR.GetBlackTexture()); cmd.SetComputeBufferParam(ssGICS, currentKernel, HDShaderIDs._DepthPyramidMipLevelOffsets, info.GetOffsetBufferData(m_DepthPyramidMipLevelOffsetsBuffer)); - + // Bind the output texture cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._IndirectDiffuseTextureRW, buffer1); @@ -189,12 +193,12 @@ void RenderSSGI(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext re cmd.SetComputeVectorParam(bilateralUpsampleCS, HDShaderIDs._HalfScreenSize, halfScreenSize); firstMipOffset.Set(HDShadowUtils.Asfloat((uint)info.mipLevelOffsets[1].x), HDShadowUtils.Asfloat((uint)info.mipLevelOffsets[1].y)); cmd.SetComputeVectorParam(bilateralUpsampleCS, HDShaderIDs._DepthPyramidFirstMipLevelOffset, firstMipOffset); - + // Inject all the input buffers cmd.SetComputeTextureParam(bilateralUpsampleCS, m_BilateralUpSampleColorTMKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthTexture()); cmd.SetComputeTextureParam(bilateralUpsampleCS, m_BilateralUpSampleColorTMKernel, HDShaderIDs._LowResolutionTexture, buffer1); cmd.SetComputeBufferParam(bilateralUpsampleCS, m_BilateralUpSampleColorTMKernel, HDShaderIDs._DepthPyramidMipLevelOffsets, info.GetOffsetBufferData(m_DepthPyramidMipLevelOffsetsBuffer)); - + // Inject the output textures cmd.SetComputeTextureParam(bilateralUpsampleCS, m_BilateralUpSampleColorTMKernel, HDShaderIDs._OutputUpscaledTexture, buffer0); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 2161e17bb06..4e49ddb1ef3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -1157,6 +1157,9 @@ void UpdateShaderVariablesXRCB(HDCamera hdCamera, CommandBuffer cmd) void UpdateShaderVariablesRaytracingCB(HDCamera hdCamera, CommandBuffer cmd) { + if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) + return; + RayTracingSettings rayTracingSettings = hdCamera.volumeStack.GetComponent(); ScreenSpaceReflection screenSpaceReflection = hdCamera.volumeStack.GetComponent(); From 8430b48d0cb6cc66f33c670649d58c16ce5cc5e7 Mon Sep 17 00:00:00 2001 From: Sebastien Lagarde Date: Tue, 19 May 2020 19:06:22 +0200 Subject: [PATCH 92/92] Update 501_RecursiveRendering.png --- .../WindowsEditor/Direct3D12/None/501_RecursiveRendering.png | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TestProjects/HDRP_DXR_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D12/None/501_RecursiveRendering.png b/TestProjects/HDRP_DXR_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D12/None/501_RecursiveRendering.png index 0a8bda173c7..ab6b27f3f3c 100644 --- a/TestProjects/HDRP_DXR_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D12/None/501_RecursiveRendering.png +++ b/TestProjects/HDRP_DXR_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D12/None/501_RecursiveRendering.png @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:4fcb6d155bc04372222b20f973ef94dc3c0447e9af9fb489c4bf59d522458f02 -size 164375 +oid sha256:780cee510502590a10c34e4f73057792db144c28dd6411833131917204553304 +size 164349