
namespace UnityEngine.Rendering.Universal
{
    internal class GammaLinearConvertorPass : ScriptableRenderPass
    {
        const string profilerTag = "Gamma To Linear Pass";
        Material blitMaterial;
        TextureDimension targetDimension;
        RenderTargetIdentifier source;
        RenderTextureDescriptor desc;

        static readonly int tempCopyString = Shader.PropertyToID("_TempCopy");
        RenderTargetIdentifier tempCopy = new RenderTargetIdentifier(tempCopyString);

        public GammaLinearConvertorPass(RenderPassEvent evt, GammaLinearConvertor.ConvertorType convertorType)
        {
            var shader = convertorType == GammaLinearConvertor.ConvertorType.GammaToLinear ? Shader.Find("URP/Gamma2Linear") : Shader.Find("URP/Linear2Gamma");
            blitMaterial = CoreUtils.CreateEngineMaterial(shader);
            renderPassEvent = evt;
        }

        public void Setup(RenderTextureDescriptor baseDescriptor, RenderTargetIdentifier source)
        {
            this.source = source;
            targetDimension = baseDescriptor.dimension;
            desc = baseDescriptor;
        }

        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer cmd = CommandBufferPool.Get(profilerTag);
            cmd.GetTemporaryRT(tempCopyString, desc, FilterMode.Bilinear);
            cmd.CopyTexture(source, tempCopy);
            cmd.Blit(tempCopy, source, blitMaterial);

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

        public override void FrameCleanup(CommandBuffer cmd)
        {
            cmd.ReleaseTemporaryRT(tempCopyString);
        }
    }
}
