﻿using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using System;

[Serializable, VolumeComponentMenu("Post-processing/Snapshot Pro (HDRP)/Pixelate")]
public sealed class Pixelate : CustomPostProcessVolumeComponent, IPostProcessComponent
{
    [Tooltip("Controls the intensity of the effect.")]
    public ClampedIntParameter pixelSize = new ClampedIntParameter(1, 1, 128);

    Material m_Material;

    public bool IsActive() => m_Material != null && pixelSize.value > 1;

    // Remember to add this post process in the Custom Post Process Orders list 
    // (Project Settings > HDRP Default Settings).
    public override CustomPostProcessInjectionPoint injectionPoint => 
        CustomPostProcessInjectionPoint.AfterPostProcess;

    const string kShaderName = "SnapshotProHDRP/Base";

    public override void Setup()
    {
        if (Shader.Find(kShaderName) != null)
        {
            m_Material = new Material(Shader.Find(kShaderName));
        }
        else
        {
            Debug.LogError($"Unable to find shader '{kShaderName}' for the Pixelate effect.");
        }  
    }

    public override void Render(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination)
    {
        if (m_Material == null)
        {
            return;
        }

        var tmpID = Shader.PropertyToID("Temp");
        cmd.GetTemporaryRT(tmpID, source.rt.width / pixelSize.value, 
            source.rt.height / pixelSize.value, 0, FilterMode.Point, 
            RenderTextureFormat.ARGB32);
        var tmpRT = new RenderTargetIdentifier(tmpID);

        source.rt.filterMode = FilterMode.Point;
        
        cmd.SetGlobalTexture("_InputTexture", source);

        cmd.Blit(source, tmpRT, m_Material);
        cmd.Blit(tmpRT, destination);

        cmd.ReleaseTemporaryRT(tmpID);
    }

    public override void Cleanup()
    {
        CoreUtils.Destroy(m_Material);
    }
}
