コード例 #1
0
        TextureHandle TraceRTSSS(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthStencilBuffer, TextureHandle normalBuffer, TextureHandle sssColor, TextureHandle ssgiBuffer, TextureHandle diffuseLightingBuffer, TextureHandle colorBuffer)
        {
            if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering))
            {
                return(colorBuffer);
            }

            using (var builder = renderGraph.AddRenderPass <TraceRTSSSPassData>("Composing the result of RTSSS", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingSSSTrace)))
            {
                builder.EnableAsyncCompute(false);

                // Grab the SSS params
                var settings = hdCamera.volumeStack.GetComponent <SubSurfaceScattering>();
                passData.parameters          = PrepareSSSRayTracingParameters(hdCamera, settings);
                passData.depthStencilBuffer  = builder.UseDepthBuffer(depthStencilBuffer, DepthAccess.Read);
                passData.normalBuffer        = builder.ReadTexture(normalBuffer);
                passData.sssColor            = builder.ReadTexture(sssColor);
                passData.intermediateBuffer0 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Texture 0"
                });
                passData.intermediateBuffer1 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Texture 1"
                });
                passData.intermediateBuffer2 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Texture 2"
                });
                passData.intermediateBuffer3 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Texture 3"
                });
                passData.directionBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Distance buffer"
                });
                passData.outputBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Ray Traced SSS"
                }));

                builder.SetRenderFunc(
                    (TraceRTSSSPassData data, RenderGraphContext ctx) =>
                {
                    // We need to fill the structure that holds the various resources
                    SSSRayTracingResources ssstResources = new SSSRayTracingResources();
                    ssstResources.depthStencilBuffer     = data.depthStencilBuffer;
                    ssstResources.normalBuffer           = data.normalBuffer;
                    ssstResources.sssColor            = data.sssColor;
                    ssstResources.intermediateBuffer0 = data.intermediateBuffer0;
                    ssstResources.intermediateBuffer1 = data.intermediateBuffer1;
                    ssstResources.intermediateBuffer2 = data.intermediateBuffer2;
                    ssstResources.intermediateBuffer3 = data.intermediateBuffer3;
                    ssstResources.directionBuffer     = data.directionBuffer;
                    ssstResources.outputBuffer        = data.outputBuffer;
                    ExecuteRTSubsurfaceScattering(ctx.cmd, data.parameters, ssstResources);
                });

                return(passData.outputBuffer);
            }
        }
コード例 #2
0
        TextureHandle UpscaleRTR(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthPyramid, TextureHandle lightingTexture)
        {
            using (var builder = renderGraph.AddRenderPass <UpscaleRTRPassData>("Upscale RTR", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingReflectionUpscale)))
            {
                builder.EnableAsyncCompute(false);

                passData.texWidth           = hdCamera.actualWidth;
                passData.texHeight          = hdCamera.actualHeight;
                passData.viewCount          = hdCamera.viewCount;
                passData.reflectionFilterCS = m_Asset.renderPipelineRayTracingResources.reflectionBilateralFilterCS;
                passData.upscaleKernel      = m_ReflectionUpscaleKernel;

                passData.depthStencilBuffer = builder.ReadTexture(depthPyramid);
                passData.lightingTexture    = builder.ReadTexture(lightingTexture);
                passData.outputTexture      = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Reflection Ray Reflections"
                }));

                builder.SetRenderFunc(
                    (UpscaleRTRPassData data, RenderGraphContext ctx) =>
                {
                    // Input textures
                    ctx.cmd.SetComputeTextureParam(data.reflectionFilterCS, data.upscaleKernel, HDShaderIDs._DepthTexture, data.depthStencilBuffer);
                    ctx.cmd.SetComputeTextureParam(data.reflectionFilterCS, data.upscaleKernel, HDShaderIDs._SsrLightingTextureRW, data.lightingTexture);

                    // Output texture
                    ctx.cmd.SetComputeTextureParam(data.reflectionFilterCS, data.upscaleKernel, HDShaderIDs._RaytracingReflectionTexture, data.outputTexture);

                    // Compute the texture
                    int numTilesXHR = (data.texWidth + (rtReflectionsComputeTileSize - 1)) / rtReflectionsComputeTileSize;
                    int numTilesYHR = (data.texHeight + (rtReflectionsComputeTileSize - 1)) / rtReflectionsComputeTileSize;
                    ctx.cmd.DispatchCompute(data.reflectionFilterCS, data.upscaleKernel, numTilesXHR, numTilesYHR, data.viewCount);
                });

                return(passData.outputTexture);
            }
        }
コード例 #3
0
        TextureHandle DirGenRTR(RenderGraph renderGraph, HDCamera hdCamera, ScreenSpaceReflection settings, TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle clearCoatTexture, bool transparent)
        {
            using (var builder = renderGraph.AddRenderPass <DirGenRTRPassData>("Generating the rays for RTR", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingIndirectDiffuseDirectionGeneration)))
            {
                builder.EnableAsyncCompute(false);

                // Set the camera parameters
                passData.texWidth  = settings.fullResolution ? hdCamera.actualWidth : hdCamera.actualWidth / 2;
                passData.texHeight = settings.fullResolution ? hdCamera.actualHeight : hdCamera.actualHeight / 2;
                passData.viewCount = hdCamera.viewCount;

                // Set the generation parameters
                passData.minSmoothness = settings.minSmoothness;

                // Grab the right kernel
                passData.directionGenCS = m_Asset.renderPipelineRayTracingResources.reflectionRaytracingCS;
                if (settings.fullResolution)
                {
                    passData.dirGenKernel = transparent ? m_RaytracingReflectionsTransparentFullResKernel : m_RaytracingReflectionsFullResKernel;
                }
                else
                {
                    passData.dirGenKernel = transparent ? m_RaytracingReflectionsTransparentHalfResKernel : m_RaytracingReflectionsHalfResKernel;
                }

                // Grab the additional parameters
                passData.ditheredTextureSet          = GetBlueNoiseManager().DitheredTextureSet8SPP();
                passData.shaderVariablesRayTracingCB = m_ShaderVariablesRayTracingCB;

                passData.depthBuffer          = builder.ReadTexture(depthPyramid);
                passData.stencilBuffer        = builder.ReadTexture(stencilBuffer);
                passData.normalBuffer         = builder.ReadTexture(normalBuffer);
                passData.clearCoatMaskTexture = builder.ReadTexture(clearCoatTexture);
                passData.outputBuffer         = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Reflection Ray Directions"
                }));

                builder.SetRenderFunc(
                    (DirGenRTRPassData data, RenderGraphContext ctx) =>
                {
                    // TODO: check if this is required, i do not think so
                    CoreUtils.SetRenderTarget(ctx.cmd, data.outputBuffer, ClearFlag.Color, clearColor: Color.black);

                    // Inject the ray-tracing sampling data
                    BlueNoise.BindDitheredTextureSet(ctx.cmd, data.ditheredTextureSet);

                    // Bind all the required scalars to the CB
                    data.shaderVariablesRayTracingCB._RaytracingReflectionMinSmoothness = data.minSmoothness;
                    ConstantBuffer.PushGlobal(ctx.cmd, data.shaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing);

                    // Bind all the required textures
                    ctx.cmd.SetComputeTextureParam(data.directionGenCS, data.dirGenKernel, HDShaderIDs._DepthTexture, data.depthBuffer);
                    ctx.cmd.SetComputeTextureParam(data.directionGenCS, data.dirGenKernel, HDShaderIDs._NormalBufferTexture, data.normalBuffer);
                    ctx.cmd.SetComputeTextureParam(data.directionGenCS, data.dirGenKernel, HDShaderIDs._SsrClearCoatMaskTexture, data.clearCoatMaskTexture);
                    ctx.cmd.SetComputeIntParam(data.directionGenCS, HDShaderIDs._SsrStencilBit, (int)StencilUsage.TraceReflectionRay);
                    ctx.cmd.SetComputeTextureParam(data.directionGenCS, data.dirGenKernel, HDShaderIDs._StencilTexture, data.stencilBuffer, 0, RenderTextureSubElement.Stencil);

                    // Bind the output buffers
                    ctx.cmd.SetComputeTextureParam(data.directionGenCS, data.dirGenKernel, HDShaderIDs._RaytracingDirectionBuffer, data.outputBuffer);

                    // Evaluate the dispatch parameters
                    int numTilesX = (data.texWidth + (rtReflectionsComputeTileSize - 1)) / rtReflectionsComputeTileSize;
                    int numTilesY = (data.texHeight + (rtReflectionsComputeTileSize - 1)) / rtReflectionsComputeTileSize;
                    // Compute the directions
                    ctx.cmd.DispatchCompute(data.directionGenCS, data.dirGenKernel, numTilesX, numTilesY, data.viewCount);
                });

                return(passData.outputBuffer);
            }
        }
コード例 #4
0
        TextureHandle RaytracingRecursiveRender(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle colorBuffer, TextureHandle depthPyramid, TextureHandle flagMask, TextureHandle rayCountTexture)
        {
            // If ray tracing is disabled in the frame settings or the effect is not enabled
            RecursiveRendering recursiveSettings = hdCamera.volumeStack.GetComponent <RecursiveRendering>();

            if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) || !recursiveSettings.enable.value)
            {
                return(colorBuffer);
            }

            // Build the parameter structure
            RecursiveRendererParameters rrParams = PrepareRecursiveRendererParameters(hdCamera, recursiveSettings);

            using (var builder = renderGraph.AddRenderPass <RecursiveRenderingPassData>("Recursive Rendering Evaluation", out var passData, ProfilingSampler.Get(HDProfileId.RayTracingRecursiveRendering)))
            {
                builder.EnableAsyncCompute(false);

                passData.parameters         = rrParams;
                passData.depthStencilBuffer = builder.ReadTexture(depthPyramid);
                passData.flagMask           = builder.ReadTexture(flagMask);
                passData.rayCountTexture    = builder.ReadWriteTexture(rayCountTexture);
                passData.outputBuffer       = builder.ReadWriteTexture(colorBuffer);
                // Right now the debug buffer is written to independently of what is happening. This must be changed
                // TODO RENDERGRAPH
                passData.debugBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Recursive Rendering Debug Texture"
                }));

                builder.SetRenderFunc(
                    (RecursiveRenderingPassData data, RenderGraphContext ctx) =>
                {
                    RecursiveRendererResources rrResources = new RecursiveRendererResources();
                    rrResources.depthStencilBuffer         = data.depthStencilBuffer;
                    rrResources.flagMask        = data.flagMask;
                    rrResources.debugBuffer     = data.debugBuffer;
                    rrResources.rayCountTexture = data.rayCountTexture;
                    rrResources.outputBuffer    = data.outputBuffer;
                    ExecuteRecursiveRendering(ctx.cmd, data.parameters, rrResources);
                });

                PushFullScreenDebugTexture(m_RenderGraph, passData.debugBuffer, FullScreenDebugMode.RecursiveRayTracing);

                return(passData.outputBuffer);
            }
        }
コード例 #5
0
        public void EvaluateRayCount(CommandBuffer cmd, HDCamera camera)
        {
            if (m_IsActive)
            {
                using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingDebugOverlay)))
                {
                    // Get the size of the viewport to process
                    int currentWidth  = camera.actualWidth;
                    int currentHeight = camera.actualHeight;

                    // Grab the kernel that we will be using for the reduction
                    int currentKenel = rayCountCS.FindKernel("TextureReduction");

                    // Compute the dispatch dimensions
                    int areaTileSize   = 32;
                    int dispatchWidth  = Mathf.Max(1, (currentWidth + (areaTileSize - 1)) / areaTileSize);
                    int dispatchHeight = Mathf.Max(1, (currentHeight + (areaTileSize - 1)) / areaTileSize);

                    // Do we need three passes
                    if (dispatchHeight > 32 || dispatchWidth > 32)
                    {
                        // Bind the texture and the 256x256 buffer
                        cmd.SetComputeTextureParam(rayCountCS, currentKenel, HDShaderIDs._InputRayCountTexture, m_RayCountTexture);
                        cmd.SetComputeBufferParam(rayCountCS, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer0);
                        cmd.SetComputeIntParam(rayCountCS, HDShaderIDs._OutputBufferDimension, 256 * (int)RayCountValues.Count);
                        cmd.DispatchCompute(rayCountCS, currentKenel, dispatchWidth, dispatchHeight, 1);

                        // Let's move to the next reduction pass
                        currentWidth  /= 32;
                        currentHeight /= 32;

                        // Grab the kernel that we will be using for the reduction
                        currentKenel = rayCountCS.FindKernel("BufferReduction");

                        // Compute the dispatch dimensions
                        dispatchWidth  = Mathf.Max(1, (currentWidth + (areaTileSize - 1)) / areaTileSize);
                        dispatchHeight = Mathf.Max(1, (currentHeight + (areaTileSize - 1)) / areaTileSize);

                        cmd.SetComputeBufferParam(rayCountCS, currentKenel, HDShaderIDs._InputRayCountBuffer, m_ReducedRayCountBuffer0);
                        cmd.SetComputeBufferParam(rayCountCS, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer1);
                        cmd.SetComputeIntParam(rayCountCS, HDShaderIDs._InputBufferDimension, 256 * (int)RayCountValues.Count);
                        cmd.SetComputeIntParam(rayCountCS, HDShaderIDs._OutputBufferDimension, 32 * (int)RayCountValues.Count);
                        cmd.DispatchCompute(rayCountCS, currentKenel, dispatchWidth, dispatchHeight, 1);

                        // Let's move to the next reduction pass
                        currentWidth  /= 32;
                        currentHeight /= 32;

                        // Compute the dispatch dimensions
                        dispatchWidth  = Mathf.Max(1, (currentWidth + (areaTileSize - 1)) / areaTileSize);
                        dispatchHeight = Mathf.Max(1, (currentHeight + (areaTileSize - 1)) / areaTileSize);

                        cmd.SetComputeBufferParam(rayCountCS, currentKenel, HDShaderIDs._InputRayCountBuffer, m_ReducedRayCountBuffer1);
                        cmd.SetComputeBufferParam(rayCountCS, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer2);
                        cmd.SetComputeIntParam(rayCountCS, HDShaderIDs._InputBufferDimension, 32 * (int)RayCountValues.Count);
                        cmd.SetComputeIntParam(rayCountCS, HDShaderIDs._OutputBufferDimension, 1 * (int)RayCountValues.Count);
                        cmd.DispatchCompute(rayCountCS, currentKenel, dispatchWidth, dispatchHeight, 1);
                    }
                    else
                    {
                        cmd.SetComputeTextureParam(rayCountCS, currentKenel, HDShaderIDs._InputRayCountTexture, m_RayCountTexture);
                        cmd.SetComputeBufferParam(rayCountCS, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer1);
                        cmd.SetComputeIntParam(rayCountCS, HDShaderIDs._OutputBufferDimension, 32 * (int)RayCountValues.Count);
                        cmd.DispatchCompute(rayCountCS, currentKenel, dispatchWidth, dispatchHeight, 1);

                        // Let's move to the next reduction pass
                        currentWidth  /= 32;
                        currentHeight /= 32;

                        // Grab the kernel that we will be using for the reduction
                        currentKenel = rayCountCS.FindKernel("BufferReduction");

                        // Compute the dispatch dimensions
                        dispatchWidth  = Mathf.Max(1, (currentWidth + (areaTileSize - 1)) / areaTileSize);
                        dispatchHeight = Mathf.Max(1, (currentHeight + (areaTileSize - 1)) / areaTileSize);

                        cmd.SetComputeBufferParam(rayCountCS, currentKenel, HDShaderIDs._InputRayCountBuffer, m_ReducedRayCountBuffer1);
                        cmd.SetComputeBufferParam(rayCountCS, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer2);
                        cmd.SetComputeIntParam(rayCountCS, HDShaderIDs._InputBufferDimension, 32 * (int)RayCountValues.Count);
                        cmd.SetComputeIntParam(rayCountCS, HDShaderIDs._OutputBufferDimension, 1 * (int)RayCountValues.Count);
                        cmd.DispatchCompute(rayCountCS, currentKenel, dispatchWidth, dispatchHeight, 1);
                    }

                    // Enqueue an Async read-back for the single value
                    AsyncGPUReadbackRequest singleReadBack = AsyncGPUReadback.Request(m_ReducedRayCountBuffer2, (int)RayCountValues.Count * sizeof(uint), 0);
                    rayCountReadbacks.Enqueue(singleReadBack);
                }
            }
        }
コード例 #6
0
        Texture FilterAreaLightTexture(CommandBuffer cmd, Texture source, int finalWidth, int finalHeight)
        {
            if (m_MaterialFilterAreaLights == null)
            {
                Debug.LogError("FilterAreaLightTexture has an invalid shader. Can't filter area light cookie.");
                return(null);
            }

            int sourceWidth    = m_CookieAtlas.AtlasTexture.rt.width;
            int sourceHeight   = m_CookieAtlas.AtlasTexture.rt.height;
            int viewportWidth  = finalWidth;  // source.width;
            int viewportHeight = finalHeight; // source.height;
            int mipMapCount    = 1 + Mathf.FloorToInt(Mathf.Log(Mathf.Max(source.width, source.height), 2));

            ReserveTempTextureIfNeeded(cmd, mipMapCount);

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.AreaLightCookieConvolution)))
            {
                int targetWidth  = sourceWidth;
                int targetHeight = sourceHeight;

                if (source.dimension == TextureDimension.Cube)
                {
                    m_MPBFilterAreaLights.SetInt(s_sourceMipLevel, 0);
                    m_MPBFilterAreaLights.SetTexture(s_texCubeSource, source);

                    cmd.SetRenderTarget(m_TempRenderTexture0, 0);
                    cmd.SetViewport(new Rect(0, 0, viewportWidth, viewportHeight));
                    cmd.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 3, MeshTopology.Triangles, 3, 1, m_MPBFilterAreaLights);
                }
                else
                {
                    // Start by copying the source texture to the array slice's mip 0
                    m_MPBFilterAreaLights.SetInt(s_sourceMipLevel, 0);
                    m_MPBFilterAreaLights.SetTexture(s_texSource, source);


                    // Since we blit the cookie texture into a common texture, to avoid leaking we blit with an extra border
                    int border = 1;
                    cmd.SetRenderTarget(m_TempRenderTexture0, 0);
                    cmd.SetViewport(new Rect(0, 0, viewportWidth + border, viewportHeight + border));

                    m_MPBFilterAreaLights.SetVector(s_sourceSize, new Vector4(viewportWidth, viewportHeight, (float)(viewportWidth + border) / viewportWidth, (float)(viewportHeight + border) / viewportHeight));
                    cmd.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 0, MeshTopology.Triangles, 3, 1, m_MPBFilterAreaLights);
                }

                // Then operate on all the remaining mip levels
                Vector4 sourceSize = Vector4.zero;
                for (int mipIndex = 1; mipIndex < mipMapCount; mipIndex++)
                {
                    {   // Perform horizontal blur
                        sourceSize.Set(viewportWidth / (float)sourceWidth * 1.0f, viewportHeight / (float)sourceHeight, 1.0f / sourceWidth, 1.0f / sourceHeight);
                        Vector4 uvLimits = new Vector4(0, 0, viewportWidth / (float)sourceWidth, viewportHeight / (float)sourceHeight);

                        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.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 1, MeshTopology.Triangles, 3, 1, m_MPBFilterAreaLights);
                    }

                    sourceWidth = targetWidth;

                    {   // Perform vertical blur
                        sourceSize.Set(viewportWidth / (float)sourceWidth, viewportHeight / (float)sourceHeight * 1.0f, 1.0f / sourceWidth, 1.0f / sourceHeight);
                        Vector4 uvLimits = new Vector4(0, 0, viewportWidth / (float)sourceWidth, viewportHeight / (float)sourceHeight);

                        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.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 2, MeshTopology.Triangles, 3, 1, m_MPBFilterAreaLights);
                    }

                    sourceHeight = targetHeight;
                }
            }

            return(m_TempRenderTexture0);
        }
        TextureHandle RenderVolumetricClouds_Accumulation(RenderGraph renderGraph, HDCamera hdCamera, TVolumetricCloudsCameraType cameraType,
                                                          TextureHandle colorBuffer, TextureHandle depthPyramid, TextureHandle motionVectors, TextureHandle volumetricLighting, TextureHandle maxZMask)
        {
            using (var builder = renderGraph.AddRenderPass <VolumetricCloudsAccumulationData>("Volumetric Clouds", out var passData, ProfilingSampler.Get(HDProfileId.VolumetricClouds)))
            {
                builder.EnableAsyncCompute(false);
                VolumetricClouds settings = hdCamera.volumeStack.GetComponent <VolumetricClouds>();

                passData.parameters         = PrepareVolumetricCloudsParameters_Accumulation(hdCamera, settings, cameraType, EvaluateVolumetricCloudsHistoryValidity(hdCamera, settings.localClouds.value));
                passData.colorBuffer        = builder.ReadTexture(builder.WriteTexture(colorBuffer));
                passData.depthPyramid       = builder.ReadTexture(depthPyramid);
                passData.motionVectors      = builder.ReadTexture(motionVectors);
                passData.maxZMask           = settings.localClouds.value ? renderGraph.defaultResources.blackTextureXR : builder.ReadTexture(maxZMask);
                passData.ambientProbeBuffer = builder.ReadComputeBuffer(renderGraph.ImportComputeBuffer(m_CloudsProbeBuffer));

                passData.volumetricLighting        = builder.ReadTexture(volumetricLighting);
                passData.scatteringFallbackTexture = renderGraph.defaultResources.blackTexture3DXR;

                passData.currentHistoryBuffer0  = renderGraph.ImportTexture(RequestCurrentVolumetricCloudsHistoryTexture0(hdCamera));
                passData.previousHistoryBuffer0 = renderGraph.ImportTexture(RequestPreviousVolumetricCloudsHistoryTexture0(hdCamera));
                passData.currentHistoryBuffer1  = renderGraph.ImportTexture(RequestCurrentVolumetricCloudsHistoryTexture1(hdCamera));
                passData.previousHistoryBuffer1 = renderGraph.ImportTexture(RequestPreviousVolumetricCloudsHistoryTexture1(hdCamera));

                passData.intermediateBuffer0 = builder.CreateTransientTexture(new TextureDesc(Vector2.one * 0.5f, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Temporary Clouds Lighting Buffer 0"
                });
                passData.intermediateBuffer1 = builder.CreateTransientTexture(new TextureDesc(Vector2.one * 0.5f, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Temporary Clouds Lighting Buffer 1 "
                });
                passData.intermediateBufferDepth0 = builder.CreateTransientTexture(new TextureDesc(Vector2.one * 0.5f, true, true)
                {
                    colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "Temporary Clouds Depth Buffer 0"
                });
                passData.intermediateBufferDepth1 = builder.CreateTransientTexture(new TextureDesc(Vector2.one * 0.5f, true, true)
                {
                    colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "Temporary Clouds Depth Buffer 1"
                });

                passData.intermediateColorBufferCopy = passData.parameters.needExtraColorBufferCopy ? builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GetColorBufferFormat(), enableRandomWrite = true, name = "Temporary Color Buffer"
                }) : renderGraph.defaultResources.blackTextureXR;

                if (passData.parameters.needsTemporaryBuffer)
                {
                    passData.intermediateBufferUpscale = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true)
                    {
                        colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Temporary Clouds Upscaling Buffer"
                    });
                }
                else
                {
                    passData.intermediateBufferUpscale = renderGraph.defaultResources.blackTexture;
                }

                if (passData.parameters.commonData.cameraType == TVolumetricCloudsCameraType.PlanarReflection)
                {
                    passData.intermediateBufferDepth2 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true)
                    {
                        colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "Temporary Clouds Depth Buffer 2"
                    });
                }
                else
                {
                    passData.intermediateBufferDepth2 = renderGraph.defaultResources.blackTexture;
                }

                builder.SetRenderFunc(
                    (VolumetricCloudsAccumulationData data, RenderGraphContext ctx) =>
                {
                    TraceVolumetricClouds_Accumulation(ctx.cmd, data.parameters, data.ambientProbeBuffer,
                                                       data.colorBuffer, data.depthPyramid, data.motionVectors, data.volumetricLighting, data.scatteringFallbackTexture, data.maxZMask,
                                                       data.currentHistoryBuffer0, data.previousHistoryBuffer0, data.currentHistoryBuffer1, data.previousHistoryBuffer1,
                                                       data.intermediateBuffer0, data.intermediateBuffer1, data.intermediateBufferDepth0, data.intermediateBufferDepth1, data.intermediateBufferDepth2,
                                                       data.intermediateColorBufferCopy, data.intermediateBufferUpscale);
                });

                // Push the texture to the debug menu
                PushFullScreenDebugTexture(m_RenderGraph, passData.currentHistoryBuffer0, FullScreenDebugMode.VolumetricClouds);

                // We return the volumetric clouds buffers rendered at half resolution. We should ideally return the full resolution transmittance, but
                // this should be enough for the initial case (which is the lens flares). The transmittance can be found in the alpha channel.
                return(passData.currentHistoryBuffer0);
            }
        }
コード例 #8
0
 public RippleRenderPass()
 {
     profilingSampler = new ProfilingSampler(k_tag);
 }
コード例 #9
0
        TextureHandle RenderPostProcess(RenderGraph renderGraph,
                                        TextureHandle inputColor,
                                        TextureHandle depthBuffer,
                                        TextureHandle backBuffer,
                                        CullingResults cullResults,
                                        HDCamera hdCamera)
        {
            PostProcessParameters parameters = PreparePostProcess(cullResults, hdCamera);

            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))
            {
                // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass
                using (var builder = renderGraph.AddRenderPass <AfterPostProcessPassData>("After Post-Process", out var passData, ProfilingSampler.Get(HDProfileId.AfterPostProcessing)))
                {
                    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);
        }
コード例 #10
0
ファイル: HDShadowAtlas.cs プロジェクト: zmz0381/simulator
        unsafe static void EVSMBlurMoments(RenderShadowsParameters parameters,
                                           RTHandle atlasRenderTexture,
                                           RTHandle[] momentAtlasRenderTextures,
                                           CommandBuffer cmd)
        {
            ComputeShader shadowBlurMomentsCS = parameters.evsmShadowBlurMomentsCS;

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderEVSMShadowMaps)))
            {
                int generateAndBlurMomentsKernel = shadowBlurMomentsCS.FindKernel("ConvertAndBlur");
                int blurMomentsKernel            = shadowBlurMomentsCS.FindKernel("Blur");
                int copyMomentsKernel            = shadowBlurMomentsCS.FindKernel("CopyMoments");

                cmd.SetComputeTextureParam(shadowBlurMomentsCS, generateAndBlurMomentsKernel, HDShaderIDs._DepthTexture, atlasRenderTexture);
                cmd.SetComputeVectorArrayParam(shadowBlurMomentsCS, HDShaderIDs._BlurWeightsStorage, evsmBlurWeights);

                // We need to store in which of the two moment texture a request will have its last version stored in for a final patch up at the end.
                var finalAtlasTexture = stackalloc int[parameters.shadowRequests.Count];

                int requestIdx = 0;
                foreach (var shadowRequest in parameters.shadowRequests)
                {
                    using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderEVSMShadowMapsBlur)))
                    {
                        int downsampledWidth  = Mathf.CeilToInt(shadowRequest.atlasViewport.width * 0.5f);
                        int downsampledHeight = Mathf.CeilToInt(shadowRequest.atlasViewport.height * 0.5f);

                        Vector2 DstRectOffset = new Vector2(shadowRequest.atlasViewport.min.x * 0.5f, shadowRequest.atlasViewport.min.y * 0.5f);

                        cmd.SetComputeTextureParam(shadowBlurMomentsCS, generateAndBlurMomentsKernel, HDShaderIDs._OutputTexture, momentAtlasRenderTextures[0]);
                        cmd.SetComputeVectorParam(shadowBlurMomentsCS, HDShaderIDs._SrcRect, new Vector4(shadowRequest.atlasViewport.min.x, shadowRequest.atlasViewport.min.y, shadowRequest.atlasViewport.width, shadowRequest.atlasViewport.height));
                        cmd.SetComputeVectorParam(shadowBlurMomentsCS, HDShaderIDs._DstRect, new Vector4(DstRectOffset.x, DstRectOffset.y, 1.0f / atlasRenderTexture.rt.width, 1.0f / atlasRenderTexture.rt.height));
                        cmd.SetComputeFloatParam(shadowBlurMomentsCS, HDShaderIDs._EVSMExponent, shadowRequest.evsmParams.x);

                        int dispatchSizeX = ((int)downsampledWidth + 7) / 8;
                        int dispatchSizeY = ((int)downsampledHeight + 7) / 8;

                        cmd.DispatchCompute(shadowBlurMomentsCS, generateAndBlurMomentsKernel, dispatchSizeX, dispatchSizeY, 1);

                        int currentAtlasMomentSurface = 0;

                        RTHandle GetMomentRT()
                        {
                            return(momentAtlasRenderTextures[currentAtlasMomentSurface]);
                        }

                        RTHandle GetMomentRTCopy()
                        {
                            return(momentAtlasRenderTextures[(currentAtlasMomentSurface + 1) & 1]);
                        }

                        cmd.SetComputeVectorParam(shadowBlurMomentsCS, HDShaderIDs._SrcRect, new Vector4(DstRectOffset.x, DstRectOffset.y, downsampledWidth, downsampledHeight));
                        for (int i = 0; i < shadowRequest.evsmParams.w; ++i)
                        {
                            currentAtlasMomentSurface = (currentAtlasMomentSurface + 1) & 1;
                            cmd.SetComputeTextureParam(shadowBlurMomentsCS, blurMomentsKernel, HDShaderIDs._InputTexture, GetMomentRTCopy());
                            cmd.SetComputeTextureParam(shadowBlurMomentsCS, blurMomentsKernel, HDShaderIDs._OutputTexture, GetMomentRT());

                            cmd.DispatchCompute(shadowBlurMomentsCS, blurMomentsKernel, dispatchSizeX, dispatchSizeY, 1);
                        }

                        finalAtlasTexture[requestIdx++] = currentAtlasMomentSurface;
                    }
                }

                // We patch up the atlas with the requests that, due to different count of blur passes, remained in the copy
                for (int i = 0; i < parameters.shadowRequests.Count; ++i)
                {
                    if (finalAtlasTexture[i] != 0)
                    {
                        using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderEVSMShadowMapsCopyToAtlas)))
                        {
                            var shadowRequest     = parameters.shadowRequests[i];
                            int downsampledWidth  = Mathf.CeilToInt(shadowRequest.atlasViewport.width * 0.5f);
                            int downsampledHeight = Mathf.CeilToInt(shadowRequest.atlasViewport.height * 0.5f);

                            cmd.SetComputeVectorParam(shadowBlurMomentsCS, HDShaderIDs._SrcRect, new Vector4(shadowRequest.atlasViewport.min.x * 0.5f, shadowRequest.atlasViewport.min.y * 0.5f, downsampledWidth, downsampledHeight));
                            cmd.SetComputeTextureParam(shadowBlurMomentsCS, copyMomentsKernel, HDShaderIDs._InputTexture, momentAtlasRenderTextures[1]);
                            cmd.SetComputeTextureParam(shadowBlurMomentsCS, copyMomentsKernel, HDShaderIDs._OutputTexture, momentAtlasRenderTextures[0]);

                            int dispatchSizeX = ((int)downsampledWidth + 7) / 8;
                            int dispatchSizeY = ((int)downsampledHeight + 7) / 8;

                            cmd.DispatchCompute(shadowBlurMomentsCS, copyMomentsKernel, dispatchSizeX, dispatchSizeY, 1);
                        }
                    }
                }
            }
        }
コード例 #11
0
ファイル: HDShadowAtlas.cs プロジェクト: zmz0381/simulator
        static void IMBlurMoment(RenderShadowsParameters parameters,
                                 RTHandle atlas,
                                 RTHandle atlasMoment,
                                 RTHandle intermediateSummedAreaTexture,
                                 RTHandle summedAreaTexture,
                                 CommandBuffer cmd)
        {
            // If the target kernel is not available
            ComputeShader momentCS = parameters.imShadowBlurMomentsCS;

            if (momentCS == null)
            {
                return;
            }

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderMomentShadowMaps)))
            {
                int computeMomentKernel        = momentCS.FindKernel("ComputeMomentShadows");
                int summedAreaHorizontalKernel = momentCS.FindKernel("MomentSummedAreaTableHorizontal");
                int summedAreaVerticalKernel   = momentCS.FindKernel("MomentSummedAreaTableVertical");

                // First of all let's clear the moment shadow map
                CoreUtils.SetRenderTarget(cmd, atlasMoment, ClearFlag.Color, Color.black);
                CoreUtils.SetRenderTarget(cmd, intermediateSummedAreaTexture, ClearFlag.Color, Color.black);
                CoreUtils.SetRenderTarget(cmd, summedAreaTexture, ClearFlag.Color, Color.black);


                // Alright, so the thing here is that for every sub-shadow map of the atlas, we need to generate the moment shadow map
                foreach (var shadowRequest in parameters.shadowRequests)
                {
                    // Let's bind the resources of this
                    cmd.SetComputeTextureParam(momentCS, computeMomentKernel, HDShaderIDs._ShadowmapAtlas, atlas);
                    cmd.SetComputeTextureParam(momentCS, computeMomentKernel, HDShaderIDs._MomentShadowAtlas, atlasMoment);
                    cmd.SetComputeVectorParam(momentCS, HDShaderIDs._MomentShadowmapSlotST, new Vector4(shadowRequest.atlasViewport.width, shadowRequest.atlasViewport.height, shadowRequest.atlasViewport.min.x, shadowRequest.atlasViewport.min.y));

                    // First of all we need to compute the moments
                    int numTilesX = Math.Max((int)shadowRequest.atlasViewport.width / 8, 1);
                    int numTilesY = Math.Max((int)shadowRequest.atlasViewport.height / 8, 1);
                    cmd.DispatchCompute(momentCS, computeMomentKernel, numTilesX, numTilesY, 1);

                    // Do the horizontal pass of the summed area table
                    cmd.SetComputeTextureParam(momentCS, summedAreaHorizontalKernel, HDShaderIDs._SummedAreaTableInputFloat, atlasMoment);
                    cmd.SetComputeTextureParam(momentCS, summedAreaHorizontalKernel, HDShaderIDs._SummedAreaTableOutputInt, intermediateSummedAreaTexture);
                    cmd.SetComputeFloatParam(momentCS, HDShaderIDs._IMSKernelSize, shadowRequest.kernelSize);
                    cmd.SetComputeVectorParam(momentCS, HDShaderIDs._MomentShadowmapSize, new Vector2((float)atlasMoment.referenceSize.x, (float)atlasMoment.referenceSize.y));

                    int numLines = Math.Max((int)shadowRequest.atlasViewport.width / 64, 1);
                    cmd.DispatchCompute(momentCS, summedAreaHorizontalKernel, numLines, 1, 1);

                    // Do the horizontal pass of the summed area table
                    cmd.SetComputeTextureParam(momentCS, summedAreaVerticalKernel, HDShaderIDs._SummedAreaTableInputInt, intermediateSummedAreaTexture);
                    cmd.SetComputeTextureParam(momentCS, summedAreaVerticalKernel, HDShaderIDs._SummedAreaTableOutputInt, summedAreaTexture);
                    cmd.SetComputeVectorParam(momentCS, HDShaderIDs._MomentShadowmapSize, new Vector2((float)atlasMoment.referenceSize.x, (float)atlasMoment.referenceSize.y));
                    cmd.SetComputeFloatParam(momentCS, HDShaderIDs._IMSKernelSize, shadowRequest.kernelSize);

                    int numColumns = Math.Max((int)shadowRequest.atlasViewport.height / 64, 1);
                    cmd.DispatchCompute(momentCS, summedAreaVerticalKernel, numColumns, 1, 1);

                    // Push the global texture
                    cmd.SetGlobalTexture(HDShaderIDs._SummedAreaTableInputInt, summedAreaTexture);
                }
            }
        }
コード例 #12
0
ファイル: SSGIDenoiser.cs プロジェクト: taranovskyi/Graphics
        public SSGIDenoiserOutput Denoise(RenderGraph renderGraph, HDCamera hdCamera,
                                          TextureHandle depthPyramid, TextureHandle normalBuffer, TextureHandle motionVectorsBuffer, TextureHandle inputOutputBuffer0, TextureHandle inputOutputBuffer1,
                                          HDUtils.PackedMipChainInfo depthMipInfo, bool halfResolution = false, float historyValidity = 1.0f)
        {
            using (var builder = renderGraph.AddRenderPass <DenoiseSSGIPassData>("Denoise SSGI", out var passData, ProfilingSampler.Get(HDProfileId.SSGIDenoise)))
            {
                builder.EnableAsyncCompute(false);

                // Input buffers
                passData.depthTexture        = builder.ReadTexture(depthPyramid);
                passData.normalBuffer        = builder.ReadTexture(normalBuffer);
                passData.motionVectorsBuffer = builder.ReadTexture(motionVectorsBuffer);

                // History buffer
                bool     historyRequireClear     = false;
                RTHandle indirectDiffuseHistory0 = RequestIndirectDiffuseHistory0(hdCamera, out historyRequireClear);
                passData.indirectDiffuseHistory0 = builder.ReadTexture(builder.WriteTexture(renderGraph.ImportTexture(indirectDiffuseHistory0)));
                RTHandle indirectDiffuseHistory1 = RequestIndirectDiffuseHistory1(hdCamera, out historyRequireClear);
                passData.indirectDiffuseHistory1 = builder.ReadTexture(builder.WriteTexture(renderGraph.ImportTexture(indirectDiffuseHistory1)));
                var historyDepthBuffer = halfResolution ? hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Depth1) : hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Depth);
                passData.historyDepthBuffer = historyDepthBuffer != null?builder.ReadTexture(renderGraph.ImportTexture(historyDepthBuffer)) : renderGraph.defaultResources.blackTextureXR;

                passData.intermediateBuffer0 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Denoiser Intermediate0"
                });
                passData.intermediateBuffer1 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Denoiser Intermediate1"
                });
                passData.inputOutputBuffer0 = builder.WriteTexture(builder.ReadTexture(inputOutputBuffer0));
                passData.inputOutputBuffer1 = builder.WriteTexture(builder.ReadTexture(inputOutputBuffer1));

                passData.parameters = PrepareSSGIDenoiserParameters(hdCamera, halfResolution, historyValidity, historyRequireClear, depthMipInfo);

                builder.SetRenderFunc(
                    (DenoiseSSGIPassData data, RenderGraphContext ctx) =>
                {
                    // We need to fill the structure that holds the various resources
                    SSGIDenoiserResources resources   = new SSGIDenoiserResources();
                    resources.depthTexture            = data.depthTexture;
                    resources.normalBuffer            = data.normalBuffer;
                    resources.motionVectorsBuffer     = data.motionVectorsBuffer;
                    resources.indirectDiffuseHistory0 = data.indirectDiffuseHistory0;
                    resources.indirectDiffuseHistory1 = data.indirectDiffuseHistory1;
                    resources.historyDepthBuffer      = data.historyDepthBuffer;
                    resources.intermediateBuffer0     = data.intermediateBuffer0;
                    resources.intermediateBuffer1     = data.intermediateBuffer1;
                    resources.inputOutputBuffer0      = data.inputOutputBuffer0;
                    resources.inputOutputBuffer1      = data.inputOutputBuffer1;
                    Denoise(ctx.cmd, data.parameters, resources);
                });

                SSGIDenoiserOutput denoiserOutput = new SSGIDenoiserOutput();
                denoiserOutput.outputBuffer0 = inputOutputBuffer0;
                denoiserOutput.outputBuffer1 = inputOutputBuffer1;
                return(denoiserOutput);
            }
        }
コード例 #13
0
        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())
            {
                SetDefaultAmbientOcclusionTexture(cmd);
                return;
            }

            RayTracingShader aoShader       = m_PipelineRayTracingResources.aoRaytracing;
            var             aoSettings      = hdCamera.volumeStack.GetComponent <AmbientOcclusion>();
            RayCountManager rayCountManager = m_RenderPipeline.GetRayCountManager();

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingAmbientOcclusion)))
            {
                // Grab the acceleration structure for the target camera
                RayTracingAccelerationStructure accelerationStructure = m_RenderPipeline.RequestAccelerationStructure();

                // Define the shader pass to use for the reflection pass
                cmd.SetRayTracingShaderPass(aoShader, "VisibilityDXR");

                // Set the acceleration structure for the pass
                cmd.SetRayTracingAccelerationStructure(aoShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure);

                // Inject the ray generation data (be careful of the global constant buffer limitation)
                globalCB._RaytracingRayMaxLength = aoSettings.rayLength;
                globalCB._RaytracingNumSamples   = aoSettings.sampleCount;
                ConstantBuffer.PushGlobal(cmd, globalCB, HDShaderIDs._ShaderVariablesRaytracing);

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

                // Inject the ray-tracing sampling data
                BlueNoise blueNoise = m_RenderPipeline.GetBlueNoiseManager();
                blueNoise.BindDitheredRNGData8SPP(cmd);

                // Value used to scale the ao intensity
                cmd.SetRayTracingFloatParam(aoShader, HDShaderIDs._RaytracingAOIntensity, aoSettings.intensity.value);

                // Set the output textures
                cmd.SetRayTracingTextureParam(aoShader, HDShaderIDs._RayCountTexture, rayCountManager.GetRayCountTexture());
                cmd.SetRayTracingTextureParam(aoShader, HDShaderIDs._AmbientOcclusionTextureRW, m_AOIntermediateBuffer0);

                // Run the computation
                cmd.DispatchRays(aoShader, m_RayGenShaderName, (uint)hdCamera.actualWidth, (uint)hdCamera.actualHeight, (uint)hdCamera.viewCount);
            }

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingFilterAmbientOcclusion)))
            {
                if (aoSettings.denoise)
                {
                    // Grab the history buffer
                    RTHandle ambientOcclusionHistory = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RaytracedAmbientOcclusion)
                                                       ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RaytracedAmbientOcclusion, AmbientOcclusionHistoryBufferAllocatorFunction, 1);

                    float historyValidity = 1.0f;
                    #if UNITY_HDRP_DXR_TESTS_DEFINE
                    if (Application.isPlaying)
                    {
                        historyValidity = 0.0f;
                    }
                    else
                    #endif
                    // We need to check if something invalidated the history buffers
                    historyValidity = m_RenderPipeline.ValidRayTracingHistory(hdCamera) ? 1.0f : 0.0f;

                    // Apply the temporal denoiser
                    HDTemporalFilter temporalFilter = m_RenderPipeline.GetTemporalFilter();
                    temporalFilter.DenoiseBuffer(cmd, hdCamera, m_AOIntermediateBuffer0, ambientOcclusionHistory, m_AOIntermediateBuffer1, historyValidity: historyValidity);

                    // Apply the diffuse denoiser
                    HDDiffuseDenoiser diffuseDenoiser = m_RenderPipeline.GetDiffuseDenoiser();
                    diffuseDenoiser.DenoiseBuffer(cmd, hdCamera, m_AOIntermediateBuffer1, outputTexture, aoSettings.denoiserRadius);
                }
                else
                {
                    HDUtils.BlitCameraTexture(cmd, m_AOIntermediateBuffer0, outputTexture);
                }
            }

            // Bind the textures and the params
            cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, outputTexture);

            // TODO: All the push-debug stuff should be centralized somewhere
            (RenderPipelineManager.currentPipeline as HDRenderPipeline).PushFullScreenDebugTexture(hdCamera, cmd, outputTexture, FullScreenDebugMode.SSAO);
        }
コード例 #14
0
        TextureHandle CombineRTSSS(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle rayTracedSSS, TextureHandle depthStencilBuffer, TextureHandle sssColor, TextureHandle ssgiBuffer, TextureHandle diffuseLightingBuffer, TextureHandle colorBuffer)
        {
            using (var builder = renderGraph.AddRenderPass <ComposeRTSSSPassData>("Composing the result of RTSSS", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingSSSCompose)))
            {
                builder.EnableAsyncCompute(false);

                passData.parameters            = PrepareSSSCombineParameters(hdCamera);
                passData.depthStencilBuffer    = builder.UseDepthBuffer(depthStencilBuffer, DepthAccess.Read);
                passData.sssColor              = builder.ReadTexture(sssColor);
                passData.ssgiBuffer            = passData.parameters.validSSGI ? builder.ReadTexture(ssgiBuffer) : renderGraph.defaultResources.blackTextureXR;
                passData.diffuseLightingBuffer = builder.ReadTexture(diffuseLightingBuffer);
                passData.subsurfaceBuffer      = builder.ReadTexture(rayTracedSSS);
                passData.colorBuffer           = builder.ReadWriteTexture(colorBuffer);

                builder.SetRenderFunc(
                    (ComposeRTSSSPassData data, RenderGraphContext ctx) =>
                {
                    // We need to fill the structure that holds the various resources
                    SSSCombineResources ssscResources   = new SSSCombineResources();
                    ssscResources.depthStencilBuffer    = data.depthStencilBuffer;
                    ssscResources.sssColor              = data.sssColor;
                    ssscResources.ssgiBuffer            = data.ssgiBuffer;
                    ssscResources.diffuseLightingBuffer = data.diffuseLightingBuffer;
                    ssscResources.subsurfaceBuffer      = data.subsurfaceBuffer;
                    ssscResources.outputColorBuffer     = data.colorBuffer;
                    ExecuteCombineSubsurfaceScattering(ctx.cmd, data.parameters, ssscResources);
                });

                return(passData.colorBuffer);
            }
        }
コード例 #15
0
        void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle colorBufferRT,
                                        RTHandle diffuseBufferRT, RTHandle depthStencilBufferRT, RTHandle depthTextureRT)
        {
            if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering))
            {
                return;
            }

            BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd);

            var settings = hdCamera.volumeStack.GetComponent <SubSurfaceScattering>();

            // 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
            if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value && GetRayTracingState())
            {
                using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.SubsurfaceScattering)))
                {
                    // Evaluate the dispatch parameters
                    int areaTileSize = 8;
                    int numTilesXHR  = (hdCamera.actualWidth + (areaTileSize - 1)) / areaTileSize;
                    int numTilesYHR  = (hdCamera.actualHeight + (areaTileSize - 1)) / areaTileSize;

                    // Fetch the volume overrides that we shall be using
                    RayTracingShader subSurfaceShader   = m_Asset.renderPipelineRayTracingResources.subSurfaceRayTracing;
                    ComputeShader    deferredRayTracing = m_Asset.renderPipelineRayTracingResources.deferredRaytracingCS;

                    // Fetch all the intermediate buffers that we need
                    RTHandle intermediateBuffer0 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA0);
                    RTHandle intermediateBuffer1 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA1);
                    RTHandle intermediateBuffer2 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA2);
                    RTHandle intermediateBuffer3 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA3);
                    RTHandle intermediateBuffer4 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA4);
                    RTHandle directionBuffer     = GetRayTracingBuffer(InternalRayTracingBuffers.Direction);

                    // Clear the integration texture first
                    cmd.SetComputeTextureParam(m_ScreenSpaceShadowsCS, m_ClearShadowTexture, HDShaderIDs._RaytracedShadowIntegration, intermediateBuffer4);
                    cmd.DispatchCompute(m_ScreenSpaceShadowsCS, m_ClearShadowTexture, numTilesXHR, numTilesYHR, hdCamera.viewCount);

                    // Grab the acceleration structure for the target camera
                    RayTracingAccelerationStructure accelerationStructure = RequestAccelerationStructure();

                    // Define the shader pass to use for the reflection pass
                    cmd.SetRayTracingShaderPass(subSurfaceShader, "SubSurfaceDXR");

                    // Set the acceleration structure for the pass
                    cmd.SetRayTracingAccelerationStructure(subSurfaceShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure);

                    // Inject the ray-tracing sampling data
                    BlueNoise blueNoise = GetBlueNoiseManager();
                    blueNoise.BindDitheredRNGData8SPP(cmd);

                    // For every sample that we need to process
                    for (int sampleIndex = 0; sampleIndex < settings.sampleCount.value; ++sampleIndex)
                    {
                        // Inject the ray generation data
                        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());
                        cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._NormalBufferTexture, sharedRTManager.GetNormalBuffer());
                        cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._SSSBufferTexture, m_SSSColor);
                        cmd.SetGlobalTexture(HDShaderIDs._StencilTexture, sharedRTManager.GetDepthStencilBuffer(), RenderTextureSubElement.Stencil);

                        // Set the output textures
                        cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._ThroughputTextureRW, intermediateBuffer0);
                        cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._NormalTextureRW, intermediateBuffer1);
                        cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._PositionTextureRW, intermediateBuffer2);
                        cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._DiffuseLightingTextureRW, intermediateBuffer3);
                        cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._DirectionTextureRW, directionBuffer);

                        // Run the computation
                        cmd.DispatchRays(subSurfaceShader, m_RayGenSubSurfaceShaderName, (uint)hdCamera.actualWidth, (uint)hdCamera.actualHeight, (uint)hdCamera.viewCount);

                        // Now let's do the deferred shading pass on the samples
                        // TODO: Do this only once in the init pass
                        int currentKernel = deferredRayTracing.FindKernel("RaytracingDiffuseDeferred");

                        // Bind the lightLoop data
                        HDRaytracingLightCluster lightCluster = RequestLightCluster();
                        lightCluster.BindLightClusterData(cmd);

                        // Bind the input textures
                        cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._DepthTexture, sharedRTManager.GetDepthStencilBuffer());
                        cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._ThroughputTextureRW, intermediateBuffer0);
                        cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._NormalTextureRW, intermediateBuffer1);
                        cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._PositionTextureRW, intermediateBuffer2);
                        cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._DirectionTextureRW, directionBuffer);
                        cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._DiffuseLightingTextureRW, intermediateBuffer3);

                        // Bind the output texture (it is used for accumulation read and write)
                        cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._RaytracingLitBufferRW, intermediateBuffer4);

                        // Compute the Lighting
                        cmd.DispatchCompute(deferredRayTracing, currentKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount);
                    }

                    // Grab the history buffer
                    RTHandle subsurfaceHistory = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RayTracedSubSurface)
                                                 ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RayTracedSubSurface, SubSurfaceHistoryBufferAllocatorFunction, 1);

                    // Check if we need to invalidate the history
                    float historyValidity = 1.0f;
#if UNITY_HDRP_DXR_TESTS_DEFINE
                    if (Application.isPlaying)
                    {
                        historyValidity = 0.0f;
                    }
                    else
#endif
                    // We need to check if something invalidated the history buffers
                    historyValidity *= ValidRayTracingHistory(hdCamera) ? 1.0f : 0.0f;

                    // Apply temporal filtering to the buffer
                    HDTemporalFilter temporalFilter = GetTemporalFilter();
                    temporalFilter.DenoiseBuffer(cmd, hdCamera, intermediateBuffer4, subsurfaceHistory, intermediateBuffer0, singleChannel: false, historyValidity: historyValidity);

                    // Now based on the mask, we need to blend the subsurface and the diffuse lighting
                    ComputeShader rayTracingSubSurfaceCS    = m_Asset.renderPipelineRayTracingResources.subSurfaceRayTracingCS;
                    int           m_CombineSubSurfaceKernel = rayTracingSubSurfaceCS.FindKernel("BlendSubSurfaceData");
                    cmd.SetComputeTextureParam(rayTracingSubSurfaceCS, m_CombineSubSurfaceKernel, HDShaderIDs._SubSurfaceLightingBuffer, intermediateBuffer0);
                    cmd.SetComputeTextureParam(rayTracingSubSurfaceCS, m_CombineSubSurfaceKernel, HDShaderIDs._DiffuseLightingTextureRW, diffuseBufferRT);
                    cmd.SetComputeTextureParam(rayTracingSubSurfaceCS, m_CombineSubSurfaceKernel, HDShaderIDs._SSSBufferTexture, m_SSSColor);
                    cmd.DispatchCompute(rayTracingSubSurfaceCS, m_CombineSubSurfaceKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount);

                    // Push this version of the texture for debug
                    PushFullScreenDebugTexture(hdCamera, cmd, diffuseBufferRT, FullScreenDebugMode.RayTracedSubSurface);

                    // Combine it with the rest of the lighting
                    m_CombineLightingPass.SetTexture(HDShaderIDs._IrradianceSource, diffuseBufferRT);
                    HDUtils.DrawFullScreen(cmd, m_CombineLightingPass, colorBufferRT, depthStencilBufferRT, shaderPassId: 1);
                }
            }
            else
            {
                using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.SubsurfaceScattering)))
                {
                    var parameters = PrepareSubsurfaceScatteringParameters(hdCamera);
                    var resources  = new SubsurfaceScatteringResources();
                    resources.colorBuffer           = colorBufferRT;
                    resources.diffuseBuffer         = diffuseBufferRT;
                    resources.depthStencilBuffer    = depthStencilBufferRT;
                    resources.depthTexture          = depthTextureRT;
                    resources.cameraFilteringBuffer = m_SSSCameraFilteringBuffer;
                    resources.coarseStencilBuffer   = parameters.coarseStencilBuffer;
                    resources.sssBuffer             = m_SSSColor;

                    // For Jimenez we always need an extra buffer, for Disney it depends on platform
                    if (parameters.needTemporaryBuffer)
                    {
                        // Clear the SSS filtering target
                        using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.ClearSSSFilteringTarget)))
                        {
                            CoreUtils.SetRenderTarget(cmd, m_SSSCameraFilteringBuffer, ClearFlag.Color, Color.clear);
                        }
                    }

                    RenderSubsurfaceScattering(parameters, resources, cmd);
                }
            }
        }
コード例 #16
0
        public void EvaluateClusterDebugView(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthStencilBuffer, TextureHandle depthPyramid)
        {
            TextureHandle debugTexture;

            using (var builder = renderGraph.AddRenderPass <LightClusterDebugPassData>("Debug Texture for the Light Cluster", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingDebugCluster)))
            {
                builder.EnableAsyncCompute(false);

                passData.parameters         = PrepareLightClusterDebugParameters(hdCamera);
                passData.depthStencilBuffer = builder.UseDepthBuffer(depthStencilBuffer, DepthAccess.Read);
                passData.depthPyramid       = builder.ReadTexture(depthStencilBuffer);
                passData.outputBuffer       = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Light Cluster Debug Texture"
                }));

                builder.SetRenderFunc(
                    (LightClusterDebugPassData data, RenderGraphContext ctx) =>
                {
                    // We need to fill the structure that holds the various resources
                    LightClusterDebugResources resources = new LightClusterDebugResources();
                    resources.depthStencilBuffer         = data.depthStencilBuffer;
                    resources.depthTexture             = data.depthPyramid;
                    resources.debugLightClusterTexture = data.outputBuffer;
                    ExecuteLightClusterDebug(ctx.cmd, data.parameters, resources, ctx.renderGraphPool.GetTempMaterialPropertyBlock());
                });

                debugTexture = passData.outputBuffer;
            }

            m_RenderPipeline.PushFullScreenDebugTexture(renderGraph, debugTexture, FullScreenDebugMode.LightCluster);
        }
コード例 #17
0
        BuildGPULightListOutput BuildGPULightList(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthStencilBuffer, TextureHandle stencilBufferCopy, GBufferOutput gBuffer)
        {
            using (var builder = renderGraph.AddRenderPass <BuildGPULightListPassData>("Build Light List", out var passData, ProfilingSampler.Get(HDProfileId.BuildLightList)))
            {
                builder.EnableAsyncCompute(hdCamera.frameSettings.BuildLightListRunsAsync());

                passData.lightLoopGlobalParameters   = PrepareLightLoopGlobalParameters(hdCamera, m_TileAndClusterData);
                passData.buildGPULightListParameters = PrepareBuildGPULightListParameters(hdCamera, m_TileAndClusterData, ref m_ShaderVariablesLightListCB, m_TotalLightCount);
                passData.depthBuffer    = builder.ReadTexture(depthStencilBuffer);
                passData.stencilTexture = builder.ReadTexture(stencilBufferCopy);
                if (passData.buildGPULightListParameters.computeMaterialVariants && passData.buildGPULightListParameters.enableFeatureVariants)
                {
                    for (int i = 0; i < gBuffer.gBufferCount; ++i)
                    {
                        passData.gBuffer[i] = builder.ReadTexture(gBuffer.mrt[i]);
                    }
                    passData.gBufferCount = gBuffer.gBufferCount;
                }

                passData.lightVolumeDataBuffer = m_TileAndClusterData.lightVolumeDataBuffer;
                passData.convexBoundsBuffer    = m_TileAndClusterData.convexBoundsBuffer;
                passData.AABBBoundsBuffer      = m_TileAndClusterData.AABBBoundsBuffer;
                passData.globalLightListAtomic = m_TileAndClusterData.globalLightListAtomic;

                passData.output.tileFeatureFlags       = builder.WriteComputeBuffer(renderGraph.ImportComputeBuffer(m_TileAndClusterData.tileFeatureFlags));
                passData.output.dispatchIndirectBuffer = builder.WriteComputeBuffer(renderGraph.ImportComputeBuffer(m_TileAndClusterData.dispatchIndirectBuffer));
                passData.output.perVoxelOffset         = builder.WriteComputeBuffer(renderGraph.ImportComputeBuffer(m_TileAndClusterData.perVoxelOffset));
                passData.output.perTileLogBaseTweak    = builder.WriteComputeBuffer(renderGraph.ImportComputeBuffer(m_TileAndClusterData.perTileLogBaseTweak));
                passData.output.tileList           = builder.WriteComputeBuffer(renderGraph.ImportComputeBuffer(m_TileAndClusterData.tileList));
                passData.output.bigTileLightList   = builder.WriteComputeBuffer(renderGraph.ImportComputeBuffer(m_TileAndClusterData.bigTileLightList));
                passData.output.perVoxelLightLists = builder.WriteComputeBuffer(renderGraph.ImportComputeBuffer(m_TileAndClusterData.perVoxelLightLists));
                passData.output.lightList          = builder.WriteComputeBuffer(renderGraph.ImportComputeBuffer(m_TileAndClusterData.lightList));

                builder.SetRenderFunc(
                    (BuildGPULightListPassData data, RenderGraphContext context) =>
                {
                    bool tileFlagsWritten = false;

                    var buildLightListResources = PrepareBuildGPULightListResources(context, data);

                    ClearLightLists(data.buildGPULightListParameters, buildLightListResources, context.cmd);
                    GenerateLightsScreenSpaceAABBs(data.buildGPULightListParameters, buildLightListResources, context.cmd);
                    BigTilePrepass(data.buildGPULightListParameters, buildLightListResources, context.cmd);
                    BuildPerTileLightList(data.buildGPULightListParameters, buildLightListResources, ref tileFlagsWritten, context.cmd);
                    VoxelLightListGeneration(data.buildGPULightListParameters, buildLightListResources, context.cmd);

                    BuildDispatchIndirectArguments(data.buildGPULightListParameters, buildLightListResources, tileFlagsWritten, context.cmd);

                    // TODO RENDERGRAPH WARNING: Note that the three sets of variables are bound here, but it should be handled differently.
                    PushLightLoopGlobalParams(data.lightLoopGlobalParameters, context.cmd);
                });

                return(passData.output);
            }
        }
コード例 #18
0
 public SRPBatcherRenderPass()
 {
     profilingSampler  = new ProfilingSampler(Tag);
     renderPassEvent   = RenderPassEvent.BeforeRenderingOpaques;
     filteringSettings = new FilteringSettings(RenderQueueRange.opaque);
 }
コード例 #19
0
        static void TraceVolumetricClouds_Accumulation(CommandBuffer cmd, VolumetricCloudsParameters_Accumulation parameters, ComputeBuffer ambientProbe,
                                                       RTHandle colorBuffer, RTHandle depthPyramid, RTHandle motionVectors, RTHandle volumetricLightingTexture, RTHandle scatteringFallbackTexture, RTHandle maxZMask,
                                                       RTHandle currentHistory0Buffer, RTHandle previousHistory0Buffer,
                                                       RTHandle currentHistory1Buffer, RTHandle previousHistory1Buffer,
                                                       RTHandle intermediateLightingBuffer0, RTHandle intermediateLightingBuffer1, RTHandle intermediateDepthBuffer0, RTHandle intermediateDepthBuffer1, RTHandle intermediateDepthBuffer2,
                                                       RTHandle intermediateColorBuffer, RTHandle intermediateUpscaleBuffer)
        {
            // Compute the number of tiles to evaluate
            int traceTX = (parameters.traceWidth + (8 - 1)) / 8;
            int traceTY = (parameters.traceHeight + (8 - 1)) / 8;

            // Compute the number of tiles to evaluate
            int intermediateTX = (parameters.intermediateWidth + (8 - 1)) / 8;
            int intermediateTY = (parameters.intermediateHeight + (8 - 1)) / 8;

            // Compute the number of tiles to evaluate
            int finalTX = (parameters.finalWidth + (8 - 1)) / 8;
            int finalTY = (parameters.finalHeight + (8 - 1)) / 8;

            // Bind the sampling textures
            BlueNoise.BindDitheredTextureSet(cmd, parameters.commonData.ditheredTextureSet);

            // Set the multi compiles
            CoreUtils.SetKeyword(cmd, "LOCAL_VOLUMETRIC_CLOUDS", parameters.commonData.localClouds);

            // We only need to handle history buffers if this is not a reflection probe
            // We need to make sure that the allocated size of the history buffers and the dispatch size are perfectly equal.
            // The ideal approach would be to have a function for that returns the converted size from a viewport and texture size.
            // but for now we do it like this.
            Vector2Int previousViewportSize = previousHistory0Buffer.GetScaledSize(parameters.previousViewportSize);

            parameters.commonData.cloudsCB._HistoryViewportSize = new Vector2(previousViewportSize.x, previousViewportSize.y);
            parameters.commonData.cloudsCB._HistoryBufferSize   = new Vector2(previousHistory0Buffer.rt.width, previousHistory0Buffer.rt.height);

            // Bind the constant buffer (global as we need it for the .shader as well)
            ConstantBuffer.PushGlobal(cmd, parameters.commonData.cloudsCB, HDShaderIDs._ShaderVariablesClouds);

            RTHandle currentDepthBuffer = depthPyramid;

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.VolumetricCloudsPrepare)))
            {
                if (parameters.commonData.cameraType == TVolumetricCloudsCameraType.PlanarReflection)
                {
                    // In order to be able to work with planar
                    cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.convertObliqueDepthKernel, HDShaderIDs._DepthTexture, depthPyramid);
                    cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.convertObliqueDepthKernel, HDShaderIDs._DepthBufferRW, intermediateDepthBuffer2);
                    cmd.DispatchCompute(parameters.commonData.volumetricCloudsCS, parameters.convertObliqueDepthKernel, finalTX, finalTY, parameters.viewCount);
                    currentDepthBuffer = intermediateDepthBuffer2;
                }

                // Compute the alternative version of the mip 1 of the depth (min instead of max that is required to handle high frequency meshes (vegetation, hair)
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.depthDownscaleKernel, HDShaderIDs._DepthTexture, currentDepthBuffer);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.depthDownscaleKernel, HDShaderIDs._HalfResDepthBufferRW, intermediateDepthBuffer0);
                cmd.DispatchCompute(parameters.commonData.volumetricCloudsCS, parameters.depthDownscaleKernel, intermediateTX, intermediateTY, parameters.viewCount);
            }

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.VolumetricCloudsTrace)))
            {
                // Ray-march the clouds for this frame
                CoreUtils.SetKeyword(cmd, "PHYSICALLY_BASED_SUN", parameters.commonData.cloudsCB._PhysicallyBasedSun == 1);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.renderKernel, HDShaderIDs._MaxZMaskTexture, maxZMask);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.renderKernel, HDShaderIDs._VolumetricCloudsSourceDepth, intermediateDepthBuffer0);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.renderKernel, HDShaderIDs._Worley128RGBA, parameters.commonData.worley128RGBA);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.renderKernel, HDShaderIDs._ErosionNoise, parameters.commonData.erosionNoise);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.renderKernel, HDShaderIDs._CloudMapTexture, parameters.commonData.cloudMapTexture);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.renderKernel, HDShaderIDs._CloudLutTexture, parameters.commonData.cloudLutTexture);
                cmd.SetComputeBufferParam(parameters.commonData.volumetricCloudsCS, parameters.renderKernel, HDShaderIDs._VolumetricCloudsAmbientProbeBuffer, ambientProbe);

                // Output buffers
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.renderKernel, HDShaderIDs._CloudsLightingTextureRW, intermediateLightingBuffer0);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.renderKernel, HDShaderIDs._CloudsDepthTextureRW, intermediateDepthBuffer1);

                cmd.DispatchCompute(parameters.commonData.volumetricCloudsCS, parameters.renderKernel, traceTX, traceTY, parameters.viewCount);
                CoreUtils.SetKeyword(cmd, "PHYSICALLY_BASED_SUN", false);
            }

            // We only reproject for realtime clouds
            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.VolumetricCloudsReproject)))
            {
                if (!parameters.historyValidity)
                {
                    CoreUtils.SetRenderTarget(cmd, previousHistory1Buffer, clearFlag: ClearFlag.Color, clearColor: Color.black);
                }

                // Re-project the result from the previous frame
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.reprojectKernel, HDShaderIDs._CloudsLightingTexture, intermediateLightingBuffer0);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.reprojectKernel, HDShaderIDs._CloudsDepthTexture, intermediateDepthBuffer1);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.reprojectKernel, HDShaderIDs._HalfResDepthBuffer, intermediateDepthBuffer0);

                // History buffers
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.reprojectKernel, HDShaderIDs._HistoryVolumetricClouds0Texture, previousHistory0Buffer);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.reprojectKernel, HDShaderIDs._HistoryVolumetricClouds1Texture, previousHistory1Buffer);

                // Output textures
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.reprojectKernel, HDShaderIDs._CloudsLightingTextureRW, currentHistory0Buffer);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.reprojectKernel, HDShaderIDs._CloudsAdditionalTextureRW, currentHistory1Buffer);

                // Re-project from the previous frame
                cmd.DispatchCompute(parameters.commonData.volumetricCloudsCS, parameters.reprojectKernel, intermediateTX, intermediateTY, parameters.viewCount);
            }

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.VolumetricCloudsUpscaleAndCombine)))
            {
                if (parameters.needExtraColorBufferCopy)
                {
                    HDUtils.BlitCameraTexture(cmd, colorBuffer, intermediateColorBuffer);
                }

                // Compute the final resolution parameters
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.upscaleAndCombineKernel, HDShaderIDs._DepthStatusTexture, currentHistory1Buffer);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.upscaleAndCombineKernel, HDShaderIDs._VolumetricCloudsTexture, currentHistory0Buffer);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.upscaleAndCombineKernel, HDShaderIDs._DepthTexture, currentDepthBuffer);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.upscaleAndCombineKernel, HDShaderIDs._CameraColorTexture, intermediateColorBuffer);
                cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.upscaleAndCombineKernel, HDShaderIDs._VBufferLighting, volumetricLightingTexture);
                if (parameters.commonData.cloudsCB._PhysicallyBasedSun == 0)
                {
                    // This has to be done in the global space given that the "correct" one happens in the global space.
                    // If we do it in the local space, there are some cases when the previous frames local take precedence over the current frame global one.
                    cmd.SetGlobalTexture(HDShaderIDs._AirSingleScatteringTexture, scatteringFallbackTexture);
                    cmd.SetGlobalTexture(HDShaderIDs._AerosolSingleScatteringTexture, scatteringFallbackTexture);
                    cmd.SetGlobalTexture(HDShaderIDs._MultipleScatteringTexture, scatteringFallbackTexture);
                }

                if (parameters.needsTemporaryBuffer)
                {
                    CoreUtils.SetKeyword(cmd, "USE_INTERMEDIATE_BUFFER", true);

                    // Provide this second upscaling + combine strategy in case a temporary buffer is requested (ie MSAA).
                    // In the case of an MSAA color target, we cannot use the in-place blending of the clouds with the color target.
                    cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.upscaleAndCombineKernel, HDShaderIDs._VolumetricCloudsUpscaleTextureRW, intermediateUpscaleBuffer);

                    // Perform the upscale into an intermediate buffer.
                    cmd.DispatchCompute(parameters.commonData.volumetricCloudsCS, parameters.upscaleAndCombineKernel, finalTX, finalTY, parameters.viewCount);

                    parameters.cloudCombinePass.SetTexture(HDShaderIDs._VolumetricCloudsUpscaleTextureRW, intermediateUpscaleBuffer);

                    // Composite the clouds into the MSAA target via hardware blending.
                    HDUtils.DrawFullScreen(cmd, parameters.cloudCombinePass, colorBuffer, null, 0);

                    CoreUtils.SetKeyword(cmd, "USE_INTERMEDIATE_BUFFER", false);
                }
                else
                {
                    cmd.SetComputeTextureParam(parameters.commonData.volumetricCloudsCS, parameters.upscaleAndCombineKernel, HDShaderIDs._VolumetricCloudsUpscaleTextureRW, colorBuffer);

                    // Perform the upscale and combine with the color buffer in place.
                    cmd.DispatchCompute(parameters.commonData.volumetricCloudsCS, parameters.upscaleAndCombineKernel, finalTX, finalTY, parameters.viewCount);
                }
            }

            // Reset all the multi-compiles
            CoreUtils.SetKeyword(cmd, "LOCAL_VOLUMETRIC_CLOUDS", false);
        }
コード例 #20
0
 public HizCullPassDraw(HizCullSetting hizCullSetting)
 {
     m_hizCullSetting = hizCullSetting;
     profilingSampler = new ProfilingSampler("HizCullDraw");
 }
コード例 #21
0
        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;
            var           source       = colorBuffer;
            TextureHandle alphaTexture = renderGraph.defaultResources.whiteTextureXR;

            // Save the alpha and apply it back into the final pass if rendering in fp16 and post-processing in r11g11b10
            if (m_KeepAlpha)
            {
                using (var builder = renderGraph.AddRenderPass <AlphaCopyPassData>("Alpha Copy", out var passData, ProfilingSampler.Get(HDProfileId.AlphaCopy)))
                {
                    passData.parameters  = PrepareCopyAlphaParameters(hdCamera);
                    passData.source      = builder.ReadTexture(source);
                    passData.outputAlpha = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                    {
                        name = "Alpha Channel Copy", colorFormat = GraphicsFormat.R16_SFloat, enableRandomWrite = true
                    }));

                    builder.SetRenderFunc(
                        (AlphaCopyPassData data, RenderGraphContext ctx) =>
                    {
                        DoCopyAlpha(data.parameters,
                                    ctx.resources.GetTexture(data.source),
                                    ctx.resources.GetTexture(data.outputAlpha),
                                    ctx.cmd);
                    });

                    alphaTexture = passData.outputAlpha;
                }
            }

            // TODO RENDERGRAPH: Implement
            //            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 = camera.actualWidth;
            //                    int h = camera.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 = camera.stopNaNs && m_StopNaNFS;

            //#if UNITY_EDITOR
            //                if (isSceneView)
            //                    stopNaNs = HDAdditionalSceneViewSettings.sceneViewStopNaNs;
            //#endif

            //                if (stopNaNs)
            //                {
            //                    using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.StopNaNs)))
            //                    {
            //                        var destination = m_Pool.Get(Vector2.one, m_ColorFormat);
            //                        DoStopNaNs(cmd, camera, 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 ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.DynamicExposure)))
            //                {
            //                    if (m_Exposure.mode.value == ExposureMode.AutomaticHistogram)
            //                    {
            //                        DoHistogramBasedExposure(cmd, camera, source);
            //                    }
            //                    else
            //                    {
            //                        DoDynamicExposure(cmd, camera, source);
            //                    }

            //                    // On reset history we need to apply dynamic exposure immediately to avoid
            //                    // white or black screen flashes when the current exposure isn't anywhere
            //                    // near 0
            //                    if (camera.resetPostProcessingHistory)
            //                    {
            //                        var destination = m_Pool.Get(Vector2.one, m_ColorFormat);

            //                        var cs = m_Resources.shaders.applyExposureCS;
            //                        int kernel = cs.FindKernel("KMain");

            //                        // Note: we call GetPrevious instead of GetCurrent because the textures
            //                        // are swapped internally as the system expects the texture will be used
            //                        // on the next frame. So the actual "current" for this frame is in
            //                        // "previous".
            //                        cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._ExposureTexture, GetPreviousExposureTexture(camera));
            //                        cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._InputTexture, source);
            //                        cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._OutputTexture, destination);
            //                        cmd.DispatchCompute(cs, kernel, (camera.actualWidth + 7) / 8, (camera.actualHeight + 7) / 8, camera.viewCount);

            //                        PoolSource(ref source, destination);
            //                    }
            //                }
            //            }

            if (m_PostProcessEnabled)
            {
                //                // Temporal anti-aliasing goes first
                //                bool taaEnabled = false;

                //                if (m_AntialiasingFS)
                //                {
                //                    taaEnabled = camera.antialiasing == AntialiasingMode.TemporalAntialiasing;

                //                    if (taaEnabled)
                //                    {
                //                        using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.TemporalAntialiasing)))
                //                        {
                //                            var destination = m_Pool.Get(Vector2.one, m_ColorFormat);
                //                            DoTemporalAntialiasing(cmd, camera, source, destination, depthBuffer, depthMipChain);
                //                            PoolSource(ref source, destination);
                //                        }
                //                    }
                //                    else if (camera.antialiasing == AntialiasingMode.SubpixelMorphologicalAntiAliasing)
                //                    {
                //                        using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.SMAA)))
                //                        {
                //                            var destination = m_Pool.Get(Vector2.one, m_ColorFormat);
                //                            DoSMAA(cmd, camera, source, destination, depthBuffer);
                //                            PoolSource(ref source, destination);
                //                        }
                //                    }
                //                }

                //                if (camera.frameSettings.IsEnabled(FrameSettingsField.CustomPostProcess))
                //                {
                //                    using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.CustomPostProcessBeforePP)))
                //                    {
                //                        foreach (var typeString in HDRenderPipeline.defaultAsset.beforePostProcessCustomPostProcesses)
                //                            RenderCustomPostProcess(cmd, camera, ref source, colorBuffer, Type.GetType(typeString));
                //                    }
                //                }

                //                // If Path tracing is enabled, then DoF is computed in the path tracer by sampling the lens aperure (when using the physical camera mode)
                //                bool isDoFPathTraced = (camera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) &&
                //                     camera.volumeStack.GetComponent<PathTracing>().enable.value &&
                //                     camera.camera.cameraType != CameraType.Preview &&
                //                     m_DepthOfField.focusMode == DepthOfFieldMode.UsePhysicalCamera);

                //                // 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 && !isDoFPathTraced)
                //                {
                //                    using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.DepthOfField)))
                //                    {
                //                        var destination = m_Pool.Get(Vector2.one, m_ColorFormat);
                //                        DoDepthOfField(cmd, camera, 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 && !camera.resetPostProcessingHistory && m_MotionBlurFS)
                //                {
                //                    using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.MotionBlur)))
                //                    {
                //                        var destination = m_Pool.Get(Vector2.one, m_ColorFormat);
                //                        DoMotionBlur(cmd, camera, 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 ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PaniniProjection)))
                //                    {
                //                        var destination = m_Pool.Get(Vector2.one, m_ColorFormat);
                //                        DoPaniniProjection(cmd, camera, source, destination);
                //                        PoolSource(ref source, destination);
                //                    }
                //                }

                // Uber post-process
                //// Generate the bloom texture
                //bool bloomActive = m_Bloom.IsActive() && m_BloomFS;

                //if (bloomActive)
                //{
                //    using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.Bloom)))
                //    {
                //        DoBloom(cmd, camera, source, uberPostParams.uberPostCS, uberPostParams.uberPostKernel);
                //    }
                //}
                //else
                //{
                //    cmd.SetComputeTextureParam(uberPostParams.uberPostCS, uberPostParams.uberPostKernel, HDShaderIDs._BloomTexture, TextureXR.GetBlackTexture());
                //    cmd.SetComputeTextureParam(uberPostParams.uberPostCS, uberPostParams.uberPostKernel, HDShaderIDs._BloomDirtTexture, Texture2D.blackTexture);
                //    cmd.SetComputeVectorParam(uberPostParams.uberPostCS, HDShaderIDs._BloomParams, Vector4.zero);
                //}

                TextureHandle logLutOutput;
                using (var builder = renderGraph.AddRenderPass <ColorGradingPassData>("Color Grading", out var passData, ProfilingSampler.Get(HDProfileId.ColorGradingLUTBuilder)))
                {
                    TextureHandle logLut = renderGraph.CreateTexture(new TextureDesc(m_LutSize, m_LutSize)
                    {
                        name              = "Color Grading Log Lut",
                        dimension         = TextureDimension.Tex3D,
                        slices            = m_LutSize,
                        depthBufferBits   = DepthBits.None,
                        colorFormat       = m_LutFormat,
                        filterMode        = FilterMode.Bilinear,
                        wrapMode          = TextureWrapMode.Clamp,
                        anisoLevel        = 0,
                        useMipMap         = false,
                        enableRandomWrite = true
                    });

                    passData.parameters = PrepareColorGradingParameters();
                    passData.logLut     = builder.WriteTexture(logLut);
                    logLutOutput        = passData.logLut;

                    builder.SetRenderFunc(
                        (ColorGradingPassData data, RenderGraphContext ctx) =>
                    {
                        DoColorGrading(data.parameters, ctx.resources.GetTexture(data.logLut), ctx.cmd);
                    });
                }

                using (var builder = renderGraph.AddRenderPass <UberPostPassData>("Uber Post", out var passData, ProfilingSampler.Get(HDProfileId.UberPost)))
                {
                    TextureHandle dest = renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                    {
                        name              = "Uber Post Destination",
                        colorFormat       = m_ColorFormat,
                        useMipMap         = false,
                        enableRandomWrite = true
                    });

                    passData.parameters  = PrepareUberPostParameters(hdCamera, isSceneView);
                    passData.source      = builder.ReadTexture(source);
                    passData.logLut      = builder.ReadTexture(logLutOutput);
                    passData.destination = builder.WriteTexture(dest);

                    builder.SetRenderFunc(
                        (UberPostPassData data, RenderGraphContext ctx) =>
                    {
                        // Temp until bloom is implemented.
                        ctx.cmd.SetComputeTextureParam(data.parameters.uberPostCS, data.parameters.uberPostKernel, HDShaderIDs._BloomTexture, TextureXR.GetBlackTexture());
                        ctx.cmd.SetComputeTextureParam(data.parameters.uberPostCS, data.parameters.uberPostKernel, HDShaderIDs._BloomDirtTexture, Texture2D.blackTexture);
                        ctx.cmd.SetComputeVectorParam(data.parameters.uberPostCS, HDShaderIDs._BloomParams, Vector4.zero);


                        DoUberPostProcess(data.parameters,
                                          ctx.resources.GetTexture(data.source),
                                          ctx.resources.GetTexture(data.destination),
                                          ctx.resources.GetTexture(data.logLut),
                                          ctx.resources.GetTexture(data.source),    // TODO: TMP VALUE, should be bloom texture and will be as soon as PP is ported to rendergraph.
                                          ctx.cmd);
                    });

                    source = passData.destination;
                }

                m_HDInstance.PushFullScreenDebugTexture(renderGraph, source, FullScreenDebugMode.ColorLog);

                //                if (camera.frameSettings.IsEnabled(FrameSettingsField.CustomPostProcess))
                //                {
                //                    using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.CustomPostProcessAfterPP)))
                //                    {
                //                        foreach (var typeString in HDRenderPipeline.defaultAsset.afterPostProcessCustomPostProcesses)
                //                            RenderCustomPostProcess(cmd, camera, ref source, colorBuffer, Type.GetType(typeString));
                //                    }
                //                }
            }

            //            if (dynResHandler.DynamicResolutionEnabled() &&     // Dynamic resolution is on.
            //                camera.antialiasing == AntialiasingMode.FastApproximateAntialiasing &&
            //                m_AntialiasingFS)
            //            {
            //                using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.FXAA)))
            //                {
            //                    var destination = m_Pool.Get(Vector2.one, m_ColorFormat);
            //                    DoFXAA(cmd, camera, source, destination);
            //                    PoolSource(ref source, destination);
            //                }
            //            }

            //            // Contrast Adaptive Sharpen Upscaling
            //            if (dynResHandler.DynamicResolutionEnabled() &&
            //                dynResHandler.filter == DynamicResUpscaleFilter.ContrastAdaptiveSharpen)
            //            {
            //                using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.ContrastAdaptiveSharpen)))
            //                {
            //                    var destination = m_Pool.Get(Vector2.one, m_ColorFormat);

            //                    var cs = m_Resources.shaders.contrastAdaptiveSharpenCS;
            //                    int kInit = cs.FindKernel("KInitialize");
            //                    int kMain = cs.FindKernel("KMain");
            //                    if (kInit >= 0 && kMain >= 0)
            //                    {
            //                        cmd.SetComputeFloatParam(cs, HDShaderIDs._Sharpness, 1);
            //                        cmd.SetComputeTextureParam(cs, kMain, HDShaderIDs._InputTexture, source);
            //                        cmd.SetComputeVectorParam(cs, HDShaderIDs._InputTextureDimensions, new Vector4(source.rt.width, source.rt.height));
            //                        cmd.SetComputeTextureParam(cs, kMain, HDShaderIDs._OutputTexture, destination);
            //                        cmd.SetComputeVectorParam(cs, HDShaderIDs._OutputTextureDimensions, new Vector4(destination.rt.width, destination.rt.height));

            //                        ValidateComputeBuffer(ref m_ContrastAdaptiveSharpen, 2, sizeof(uint) * 4);

            //                        cmd.SetComputeBufferParam(cs, kInit, "CasParameters", m_ContrastAdaptiveSharpen);
            //                        cmd.SetComputeBufferParam(cs, kMain, "CasParameters", m_ContrastAdaptiveSharpen);

            //                        cmd.DispatchCompute(cs, kInit, 1, 1, 1);

            //                        int dispatchX = (int)System.Math.Ceiling(destination.rt.width / 16.0f);
            //                        int dispatchY = (int)System.Math.Ceiling(destination.rt.height / 16.0f);

            //                        cmd.DispatchCompute(cs, kMain, dispatchX, dispatchY, camera.viewCount);
            //                    }

            //                    PoolSource(ref source, destination);
            //                }
            //            }

            using (var builder = renderGraph.AddRenderPass <FinalPassData>("Final Pass", out var passData, ProfilingSampler.Get(HDProfileId.FinalPost)))
            {
                passData.parameters = PrepareFinalPass(hdCamera, blueNoise, flipY);
                passData.source     = builder.ReadTexture(source);
                passData.afterPostProcessTexture = builder.ReadTexture(afterPostProcessTexture);
                passData.alphaTexture            = builder.ReadTexture(alphaTexture);
                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);
                });
            }
        }
コード例 #22
0
 public HizCullPassShadow(HizCullSetting hizCullSetting)
 {
     m_hizCullSetting = hizCullSetting;
     profilingSampler = new ProfilingSampler("HizCullShadow");
 }
コード例 #23
0
        public TextureHandle Denoise(RenderGraph renderGraph, HDCamera hdCamera, DiffuseDenoiserParameters tfParameters, TextureHandle noisyBuffer, TextureHandle depthPyramid, TextureHandle normalBuffer, TextureHandle outputBuffer)
        {
            using (var builder = renderGraph.AddRenderPass <DiffuseDenoiserPassData>("DiffuseDenoiser", out var passData, ProfilingSampler.Get(HDProfileId.DiffuseFilter)))
            {
                // Cannot run in async
                builder.EnableAsyncCompute(false);

                // Fetch all the resources
                passData.parameters         = tfParameters;
                passData.depthStencilBuffer = builder.ReadTexture(depthPyramid);
                passData.normalBuffer       = builder.ReadTexture(normalBuffer);
                passData.noisyBuffer        = builder.ReadTexture(noisyBuffer);
                passData.intermediateBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "DiffuseDenoiserIntermediate"
                });
                passData.outputBuffer = builder.WriteTexture(outputBuffer);

                builder.SetRenderFunc(
                    (DiffuseDenoiserPassData data, RenderGraphContext ctx) =>
                {
                    DiffuseDenoiserResources ddResources = new DiffuseDenoiserResources();
                    ddResources.depthStencilBuffer       = data.depthStencilBuffer;
                    ddResources.normalBuffer             = data.normalBuffer;
                    ddResources.noisyBuffer        = data.noisyBuffer;
                    ddResources.intermediateBuffer = data.intermediateBuffer;
                    ddResources.outputBuffer       = data.outputBuffer;
                    DenoiseBuffer(ctx.cmd, data.parameters, ddResources);
                });
                return(passData.outputBuffer);
            }
        }
コード例 #24
0
        public TemporalDenoiserArrayOutputData DenoiseBuffer(RenderGraph renderGraph, HDCamera hdCamera,
                                                             TextureHandle depthBuffer, TextureHandle normalBuffer, TextureHandle motionVectorBuffer, TextureHandle historyValidationBuffer,
                                                             TextureHandle noisyBuffer, RTHandle historyBuffer,
                                                             TextureHandle distanceBuffer, RTHandle distanceHistorySignal,
                                                             TextureHandle velocityBuffer,
                                                             RTHandle validationHistoryBuffer,
                                                             int sliceIndex, Vector4 channelMask, Vector4 distanceChannelMask,
                                                             bool distanceBased, bool singleChannel, float historyValidity)
        {
            TemporalDenoiserArrayOutputData resultData = new TemporalDenoiserArrayOutputData();

            using (var builder = renderGraph.AddRenderPass <TemporalFilterArrayPassData>("TemporalDenoiser", out var passData, ProfilingSampler.Get(HDProfileId.TemporalFilter)))
            {
                // Cannot run in async
                builder.EnableAsyncCompute(false);

                // Fetch all the resources
                passData.parameters = PrepareTemporalFilterArrayParameters(hdCamera, distanceBased, singleChannel, historyValidity, sliceIndex, channelMask, distanceChannelMask);

                // Input buffers
                passData.depthStencilBuffer = builder.ReadTexture(depthBuffer);
                passData.normalBuffer       = builder.ReadTexture(normalBuffer);
                passData.motionVectorBuffer = builder.ReadTexture(motionVectorBuffer);

                passData.velocityBuffer   = builder.ReadTexture(velocityBuffer);
                passData.noisyBuffer      = builder.ReadTexture(noisyBuffer);
                passData.distanceBuffer   = distanceBased ? builder.ReadTexture(distanceBuffer) : renderGraph.defaultResources.blackTextureXR;
                passData.validationBuffer = builder.ReadTexture(historyValidationBuffer);

                // History buffers
                passData.historyBuffer           = builder.ReadWriteTexture(renderGraph.ImportTexture(historyBuffer));
                passData.validationHistoryBuffer = builder.ReadWriteTexture(renderGraph.ImportTexture(validationHistoryBuffer));
                passData.distanceHistorySignal   = distanceBased ? builder.ReadWriteTexture(renderGraph.ImportTexture(distanceHistorySignal)) : renderGraph.defaultResources.blackTextureXR;

                // Output textures
                passData.outputBuffer = builder.ReadWriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Temporal Filter Output"
                }));
                passData.outputDistanceSignal = distanceBased ? builder.ReadWriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Temporal Filter Distance output"
                })) : new TextureHandle();

                builder.SetRenderFunc(
                    (TemporalFilterArrayPassData data, RenderGraphContext ctx) =>
                {
                    TemporalFilterArrayResources resources = new TemporalFilterArrayResources();
                    resources.depthStencilBuffer           = data.depthStencilBuffer;
                    resources.normalBuffer            = data.normalBuffer;
                    resources.motionVectorBuffer      = data.motionVectorBuffer;
                    resources.velocityBuffer          = data.velocityBuffer;
                    resources.noisyBuffer             = data.noisyBuffer;
                    resources.distanceBuffer          = data.distanceBuffer;
                    resources.validationBuffer        = data.validationBuffer;
                    resources.historyBuffer           = data.historyBuffer;
                    resources.validationHistoryBuffer = data.validationHistoryBuffer;
                    resources.distanceHistorySignal   = data.distanceHistorySignal;
                    resources.outputBuffer            = data.outputBuffer;
                    resources.outputDistanceSignal    = data.outputDistanceSignal;
                    ExecuteTemporalFilterArray(ctx.cmd, data.parameters, resources);
                });
                resultData.outputSignal         = passData.outputBuffer;
                resultData.outputSignalDistance = passData.outputDistanceSignal;
            }
            return(resultData);
        }
コード例 #25
0
        TextureHandle AdjustWeightRTR(RenderGraph renderGraph, HDCamera hdCamera, ScreenSpaceReflection settings,
                                      TextureHandle depthPyramid, TextureHandle normalBuffer, TextureHandle clearCoatTexture, TextureHandle lightingTexture, TextureHandle directionTexture)
        {
            using (var builder = renderGraph.AddRenderPass <AdjustWeightRTRPassData>("Adjust Weight RTR", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingReflectionAdjustWeight)))
            {
                builder.EnableAsyncCompute(false);

                passData.texWidth  = settings.fullResolution ? hdCamera.actualWidth : hdCamera.actualWidth / 2;
                passData.texHeight = settings.fullResolution ? hdCamera.actualHeight : hdCamera.actualHeight / 2;
                passData.viewCount = hdCamera.viewCount;

                // Requires parameters
                passData.minSmoothness       = settings.minSmoothness;
                passData.smoothnessFadeStart = settings.smoothnessFadeStart;

                // Other parameters
                passData.reflectionFilterCS          = m_Asset.renderPipelineRayTracingResources.reflectionBilateralFilterCS;
                passData.adjustWeightKernel          = settings.fullResolution ? m_ReflectionAdjustWeightKernel : m_ReflectionRescaleAndAdjustWeightKernel;
                passData.shaderVariablesRayTracingCB = m_ShaderVariablesRayTracingCB;

                passData.depthStencilBuffer   = builder.ReadTexture(depthPyramid);
                passData.normalBuffer         = builder.ReadTexture(normalBuffer);
                passData.clearCoatMaskTexture = builder.ReadTexture(clearCoatTexture);
                passData.lightingTexture      = builder.ReadTexture(lightingTexture);
                passData.directionTexture     = builder.ReadTexture(directionTexture);
                passData.outputTexture        = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Reflection Ray Reflections"
                }));

                builder.SetRenderFunc(
                    (AdjustWeightRTRPassData data, RenderGraphContext ctx) =>
                {
                    // Bind all the required scalars to the CB
                    data.shaderVariablesRayTracingCB._RaytracingReflectionMinSmoothness       = data.minSmoothness;
                    data.shaderVariablesRayTracingCB._RaytracingReflectionSmoothnessFadeStart = data.smoothnessFadeStart;
                    ConstantBuffer.PushGlobal(ctx.cmd, data.shaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing);

                    // Source input textures
                    ctx.cmd.SetComputeTextureParam(data.reflectionFilterCS, data.adjustWeightKernel, HDShaderIDs._DepthTexture, data.depthStencilBuffer);
                    ctx.cmd.SetComputeTextureParam(data.reflectionFilterCS, data.adjustWeightKernel, HDShaderIDs._SsrClearCoatMaskTexture, data.clearCoatMaskTexture);
                    ctx.cmd.SetComputeTextureParam(data.reflectionFilterCS, data.adjustWeightKernel, HDShaderIDs._NormalBufferTexture, data.normalBuffer);
                    ctx.cmd.SetComputeTextureParam(data.reflectionFilterCS, data.adjustWeightKernel, HDShaderIDs._DirectionPDFTexture, data.directionTexture);

                    // Lighting textures
                    ctx.cmd.SetComputeTextureParam(data.reflectionFilterCS, data.adjustWeightKernel, HDShaderIDs._SsrLightingTextureRW, data.lightingTexture);

                    // Output texture
                    ctx.cmd.SetComputeTextureParam(data.reflectionFilterCS, data.adjustWeightKernel, HDShaderIDs._RaytracingReflectionTexture, data.outputTexture);

                    // Compute the texture
                    int numTilesXHR = (data.texWidth + (rtReflectionsComputeTileSize - 1)) / rtReflectionsComputeTileSize;
                    int numTilesYHR = (data.texHeight + (rtReflectionsComputeTileSize - 1)) / rtReflectionsComputeTileSize;
                    ctx.cmd.DispatchCompute(data.reflectionFilterCS, data.adjustWeightKernel, numTilesXHR, numTilesYHR, data.viewCount);
                });

                return(passData.outputTexture);
            }
        }
コード例 #26
0
        public TextureHandle HistoryValidity(RenderGraph renderGraph, HDCamera hdCamera, HistoryValidityParameters parameters,
                                             TextureHandle depthBuffer, TextureHandle normalBuffer, TextureHandle motionVectorBuffer)
        {
            using (var builder = renderGraph.AddRenderPass <HistoryValidityPassData>("History Validity Evaluation", out var passData, ProfilingSampler.Get(HDProfileId.HistoryValidity)))
            {
                // Cannot run in async
                builder.EnableAsyncCompute(false);

                // Fetch all the resources
                passData.parameters = parameters;
                // Input Buffers
                passData.depthStencilBuffer = builder.ReadTexture(depthBuffer);
                passData.normalBuffer       = builder.ReadTexture(normalBuffer);
                passData.motionVectorBuffer = builder.ReadTexture(motionVectorBuffer);

                // History buffers
                passData.historyDepthTexture  = builder.ReadTexture(renderGraph.ImportTexture(hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Depth)));
                passData.historyNormalTexture = builder.ReadTexture(renderGraph.ImportTexture(hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Normal)));

                // Output buffers
                passData.validationBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R8_UNorm, enableRandomWrite = true, name = "ValidationTexture"
                }));

                builder.SetRenderFunc(
                    (HistoryValidityPassData data, RenderGraphContext ctx) =>
                {
                    HistoryValidityResources resources = new HistoryValidityResources();
                    resources.depthStencilBuffer       = data.depthStencilBuffer;
                    resources.normalBuffer             = data.normalBuffer;
                    resources.motionVectorBuffer       = data.motionVectorBuffer;
                    resources.historyDepthTexture      = data.historyDepthTexture;
                    resources.historyNormalTexture     = data.historyNormalTexture;
                    resources.validationBuffer         = data.validationBuffer;
                    ExecuteHistoryValidity(ctx.cmd, data.parameters, resources);
                });
                return(passData.validationBuffer);
            }
        }
コード例 #27
0
        TextureHandle QualityRTR(RenderGraph renderGraph, HDCamera hdCamera, ScreenSpaceReflection settings,
                                 TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle clearCoatTexture, TextureHandle rayCountTexture, bool transparent)
        {
            using (var builder = renderGraph.AddRenderPass <TraceQualityRTRPassData>("Quality RT Reflections", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingReflectionEvaluation)))
            {
                builder.EnableAsyncCompute(false);

                // Camera parameters
                passData.texWidth  = hdCamera.actualWidth;
                passData.texHeight = hdCamera.actualHeight;
                passData.viewCount = hdCamera.viewCount;

                // Reflection evaluation parameters
                passData.clampValue          = settings.clampValue;
                passData.reflectSky          = settings.reflectSky.value ? 1 : 0;
                passData.rayLength           = settings.rayLength;
                passData.sampleCount         = settings.sampleCount.value;
                passData.bounceCount         = settings.bounceCount.value;
                passData.transparent         = transparent;
                passData.minSmoothness       = settings.minSmoothness;
                passData.smoothnessFadeStart = settings.smoothnessFadeStart;

                // Other parameters
                passData.accelerationStructure       = RequestAccelerationStructure();
                passData.lightCluster                = RequestLightCluster();
                passData.ditheredTextureSet          = GetBlueNoiseManager().DitheredTextureSet8SPP();
                passData.shaderVariablesRayTracingCB = m_ShaderVariablesRayTracingCB;
                passData.skyTexture       = m_SkyManager.GetSkyReflection(hdCamera);
                passData.reflectionShader = m_Asset.renderPipelineRayTracingResources.reflectionRaytracingRT;

                passData.depthBuffer          = builder.ReadTexture(depthPyramid);
                passData.stencilBuffer        = builder.ReadTexture(stencilBuffer);
                passData.normalBuffer         = builder.ReadTexture(normalBuffer);
                passData.clearCoatMaskTexture = builder.ReadTexture(clearCoatTexture);
                passData.rayCountTexture      = builder.ReadWriteTexture(rayCountTexture);
                passData.outputTexture        = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Ray Traced Reflections"
                }));

                builder.SetRenderFunc(
                    (TraceQualityRTRPassData data, RenderGraphContext ctx) =>
                {
                    // Define the shader pass to use for the reflection pass
                    ctx.cmd.SetRayTracingShaderPass(data.reflectionShader, "IndirectDXR");

                    // Set the acceleration structure for the pass
                    ctx.cmd.SetRayTracingAccelerationStructure(data.reflectionShader, HDShaderIDs._RaytracingAccelerationStructureName, data.accelerationStructure);

                    // Global reflection parameters
                    data.shaderVariablesRayTracingCB._RaytracingIntensityClamp = data.clampValue;
                    data.shaderVariablesRayTracingCB._RaytracingIncludeSky     = data.reflectSky;
                    // Inject the ray generation data
                    data.shaderVariablesRayTracingCB._RaytracingRayMaxLength = data.rayLength;
                    data.shaderVariablesRayTracingCB._RaytracingNumSamples   = data.sampleCount;
                    // Set the number of bounces for reflections
                    data.shaderVariablesRayTracingCB._RaytracingMaxRecursion        = data.bounceCount;
                    data.shaderVariablesRayTracingCB._RayTracingDiffuseLightingOnly = 0;
                    // Bind all the required scalars to the CB
                    data.shaderVariablesRayTracingCB._RaytracingReflectionMinSmoothness       = data.minSmoothness;
                    data.shaderVariablesRayTracingCB._RaytracingReflectionSmoothnessFadeStart = data.smoothnessFadeStart;
                    ConstantBuffer.PushGlobal(ctx.cmd, data.shaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing);

                    // Inject the ray-tracing sampling data
                    BlueNoise.BindDitheredTextureSet(ctx.cmd, data.ditheredTextureSet);

                    // Set the data for the ray generation
                    ctx.cmd.SetRayTracingTextureParam(data.reflectionShader, HDShaderIDs._SsrLightingTextureRW, data.outputTexture);
                    ctx.cmd.SetRayTracingTextureParam(data.reflectionShader, HDShaderIDs._DepthTexture, data.depthBuffer);
                    ctx.cmd.SetRayTracingTextureParam(data.reflectionShader, HDShaderIDs._NormalBufferTexture, data.normalBuffer);
                    ctx.cmd.SetGlobalTexture(HDShaderIDs._StencilTexture, data.stencilBuffer, RenderTextureSubElement.Stencil);
                    ctx.cmd.SetRayTracingIntParams(data.reflectionShader, HDShaderIDs._SsrStencilBit, (int)StencilUsage.TraceReflectionRay);

                    // Set ray count texture
                    ctx.cmd.SetRayTracingTextureParam(data.reflectionShader, HDShaderIDs._RayCountTexture, data.rayCountTexture);

                    // Bind the lightLoop data
                    data.lightCluster.BindLightClusterData(ctx.cmd);

                    // Evaluate the clear coat mask texture based on the lit shader mode
                    ctx.cmd.SetRayTracingTextureParam(data.reflectionShader, HDShaderIDs._SsrClearCoatMaskTexture, data.clearCoatMaskTexture);

                    // Set the data for the ray miss
                    ctx.cmd.SetRayTracingTextureParam(data.reflectionShader, HDShaderIDs._SkyTexture, data.skyTexture);

                    // Only use the shader variant that has multi bounce if the bounce count > 1
                    CoreUtils.SetKeyword(ctx.cmd, "MULTI_BOUNCE_INDIRECT", data.bounceCount > 1);

                    // Run the computation
                    ctx.cmd.DispatchRays(data.reflectionShader, data.transparent ? m_RayGenIntegrationTransparentName : m_RayGenIntegrationName, (uint)data.texWidth, (uint)data.texHeight, (uint)data.viewCount);

                    // Disable multi-bounce
                    CoreUtils.SetKeyword(ctx.cmd, "MULTI_BOUNCE_INDIRECT", false);
                });

                return(passData.outputTexture);
            }
        }
コード例 #28
0
        public TextureHandle Denoise(RenderGraph renderGraph, HDCamera hdCamera, TemporalFilterParameters tfParameters,
                                     TextureHandle noisyBuffer, TextureHandle velocityBuffer,
                                     TextureHandle historyBuffer,
                                     TextureHandle depthBuffer, TextureHandle normalBuffer, TextureHandle motionVectorBuffer, TextureHandle historyValidationBuffer)
        {
            using (var builder = renderGraph.AddRenderPass <TemporalFilterPassData>("TemporalDenoiser", out var passData, ProfilingSampler.Get(HDProfileId.TemporalFilter)))
            {
                // Cannot run in async
                builder.EnableAsyncCompute(false);

                // Fetch all the resources
                passData.parameters = tfParameters;

                // Prepass Buffers
                passData.depthStencilBuffer = builder.ReadTexture(depthBuffer);
                passData.normalBuffer       = builder.ReadTexture(normalBuffer);
                passData.motionVectorBuffer = builder.ReadTexture(motionVectorBuffer);

                // Effect buffers
                passData.velocityBuffer   = builder.ReadTexture(velocityBuffer);
                passData.noisyBuffer      = builder.ReadTexture(noisyBuffer);
                passData.validationBuffer = builder.ReadTexture(historyValidationBuffer);

                // History buffer
                passData.historyBuffer = builder.ReadWriteTexture(historyBuffer);

                // Output buffers
                passData.outputBuffer = builder.ReadWriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
                {
                    colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Temporal Filter Output"
                }));

                builder.SetRenderFunc(
                    (TemporalFilterPassData data, RenderGraphContext ctx) =>
                {
                    TemporalFilterResources tfResources = new TemporalFilterResources();
                    tfResources.depthStencilBuffer      = data.depthStencilBuffer;
                    tfResources.normalBuffer            = data.normalBuffer;
                    tfResources.velocityBuffer          = data.velocityBuffer;
                    tfResources.motionVectorBuffer      = data.motionVectorBuffer;
                    tfResources.noisyBuffer             = data.noisyBuffer;
                    tfResources.validationBuffer        = data.validationBuffer;
                    tfResources.historyBuffer           = data.historyBuffer;
                    tfResources.outputBuffer            = data.outputBuffer;
                    DenoiseBuffer(ctx.cmd, data.parameters, tfResources);
                });
                return(passData.outputBuffer);
            }
        }
コード例 #29
0
        Texture FilterAreaLightTexture(CommandBuffer cmd, Texture source)
        {
            if (m_MaterialFilterAreaLights == null)
            {
                Debug.LogError("FilterAreaLightTexture has an invalid shader. Can't filter area light cookie.");
                return(null);
            }

            // TODO: we don't need to allocate two temp RT, we can use the atlas as temp render texture
            // it will avoid additional copy of the whole mip chain into the atlas.
            int sourceWidth    = m_CookieAtlas.AtlasTexture.rt.width;
            int sourceHeight   = m_CookieAtlas.AtlasTexture.rt.height;
            int viewportWidth  = source.width;
            int viewportHeight = source.height;
            int mipMapCount    = 1 + Mathf.FloorToInt(Mathf.Log(Mathf.Max(source.width, source.height), 2));

            if (m_TempRenderTexture0 == null)
            {
                string cacheName = m_CookieAtlas.AtlasTexture.name;
                m_TempRenderTexture0 = new RenderTexture(sourceWidth, sourceHeight, 1, cookieFormat)
                {
                    hideFlags        = HideFlags.HideAndDontSave,
                    useMipMap        = true,
                    autoGenerateMips = false,
                    name             = cacheName + "TempAreaLightRT0"
                };

                // We start by a horizontal gaussian into mip 1 that reduces the width by a factor 2 but keeps the same height
                m_TempRenderTexture1 = new RenderTexture(sourceWidth >> 1, sourceHeight, 1, cookieFormat)
                {
                    hideFlags        = HideFlags.HideAndDontSave,
                    useMipMap        = true,
                    autoGenerateMips = false,
                    name             = cacheName + "TempAreaLightRT1"
                };
            }

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.AreaLightCookieConvolution)))
            {
                int targetWidth  = sourceWidth;
                int targetHeight = sourceHeight;

                // Start by copying the source texture to the array slice's mip 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, m_MPBFilterAreaLights);
                }

                // Then operate on all the remaining mip levels
                Vector4 sourceSize = Vector4.zero;
                for (int mipIndex = 1; mipIndex < mipMapCount; mipIndex++)
                {
                    {   // Perform horizontal blur
                        sourceSize.Set(viewportWidth / (float)sourceWidth * 1.0f, viewportHeight / (float)sourceHeight, 1.0f / sourceWidth, 1.0f / sourceHeight);
                        Vector4 uvLimits = new Vector4(0, 0, viewportWidth / (float)sourceWidth, viewportHeight / (float)sourceHeight);

                        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.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 1, MeshTopology.Triangles, 3, 1, m_MPBFilterAreaLights);
                    }

                    sourceWidth = targetWidth;

                    {   // Perform vertical blur
                        sourceSize.Set(viewportWidth / (float)sourceWidth, viewportHeight / (float)sourceHeight * 1.0f, 1.0f / sourceWidth, 1.0f / sourceHeight);
                        Vector4 uvLimits = new Vector4(0, 0, viewportWidth / (float)sourceWidth, viewportHeight / (float)sourceHeight);

                        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.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 2, MeshTopology.Triangles, 3, 1, m_MPBFilterAreaLights);
                    }

                    sourceHeight = targetHeight;
                }
            }

            return(m_TempRenderTexture0);
        }
コード例 #30
0
        /// <inheritdoc/>
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            if (m_CopyDepthMaterial == null)
            {
                Debug.LogErrorFormat("Missing {0}. {1} render pass will not execute. Check for missing reference in the renderer resources.", m_CopyDepthMaterial, GetType().Name);
                return;
            }
            CommandBuffer cmd = CommandBufferPool.Get();

            using (new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.CopyDepth)))
            {
                int cameraSamples = 0;

                if (MssaSamples == -1)
                {
                    RenderTextureDescriptor descriptor = renderingData.cameraData.cameraTargetDescriptor;
                    cameraSamples = descriptor.msaaSamples;
                }
                else
                {
                    cameraSamples = MssaSamples;
                }

                CameraData cameraData = renderingData.cameraData;

                switch (cameraSamples)
                {
                case 8:
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4);
                    cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa8);
                    break;

                case 4:
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2);
                    cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa4);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa8);
                    break;

                case 2:
                    cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa2);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa8);
                    break;

                // MSAA disabled
                default:
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4);
                    cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa8);
                    break;
                }

                cmd.SetGlobalTexture("_CameraDepthAttachment", source.Identifier());


#if ENABLE_VR && ENABLE_XR_MODULE
                // XR uses procedural draw instead of cmd.blit or cmd.DrawFullScreenMesh
                if (renderingData.cameraData.xr.enabled)
                {
                    // XR flip logic is not the same as non-XR case because XR uses draw procedure
                    // and draw procedure does not need to take projection matrix yflip into account
                    // We y-flip if
                    // 1) we are bliting from render texture to back buffer and
                    // 2) renderTexture starts UV at top
                    // XRTODO: handle scalebias and scalebiasRt for src and dst separately
                    bool    isRenderToBackBufferTarget = destination.Identifier() == cameraData.xr.renderTarget && !cameraData.xr.renderTargetIsRenderTexture;
                    bool    yflip       = isRenderToBackBufferTarget && SystemInfo.graphicsUVStartsAtTop;
                    float   flipSign    = (yflip) ? -1.0f : 1.0f;
                    Vector4 scaleBiasRt = (flipSign < 0.0f)
                        ? new Vector4(flipSign, 1.0f, -1.0f, 1.0f)
                        : new Vector4(flipSign, 0.0f, 1.0f, 1.0f);
                    cmd.SetGlobalVector(ShaderPropertyId.scaleBiasRt, scaleBiasRt);

                    cmd.DrawProcedural(Matrix4x4.identity, m_CopyDepthMaterial, 0, MeshTopology.Quads, 4);
                }
                else
#endif
                {
                    // Blit has logic to flip projection matrix when rendering to render texture.
                    // Currently the y-flip is handled in CopyDepthPass.hlsl by checking _ProjectionParams.x
                    // If you replace this Blit with a Draw* that sets projection matrix double check
                    // to also update shader.
                    // scaleBias.x = flipSign
                    // scaleBias.y = scale
                    // scaleBias.z = bias
                    // scaleBias.w = unused
                    // In game view final target acts as back buffer were target is not flipped
                    bool    isGameViewFinalTarget = (cameraData.cameraType == CameraType.Game && destination == RenderTargetHandle.CameraTarget);
                    bool    yflip       = (cameraData.IsCameraProjectionMatrixFlipped()) && !isGameViewFinalTarget;
                    float   flipSign    = yflip ? -1.0f : 1.0f;
                    Vector4 scaleBiasRt = (flipSign < 0.0f)
                        ? new Vector4(flipSign, 1.0f, -1.0f, 1.0f)
                        : new Vector4(flipSign, 0.0f, 1.0f, 1.0f);
                    cmd.SetGlobalVector(ShaderPropertyId.scaleBiasRt, scaleBiasRt);

                    cmd.DrawMesh(RenderingUtils.fullscreenMesh, Matrix4x4.identity, m_CopyDepthMaterial);
                }
            }

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }