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

[Serializable, VolumeComponentMenu("Post-processing/Snapshot Pro (HDRP)/Vortex")]
public sealed class Vortex : CustomPostProcessVolumeComponent, IPostProcessComponent
{
    [Tooltip("The vortex will swirl around this normalized position.")]
    public Vector2Parameter center = new Vector2Parameter(new Vector2(0.5f, 0.5f));

    [Tooltip("How strongly the effect will twirl pixels around the center.")]
    public ClampedFloatParameter strength = new ClampedFloatParameter(0.0f, 0.0f, 100.0f);

    [Tooltip("How far the image is offset before twirling.")]
    public Vector2Parameter offset = new Vector2Parameter(Vector2.zero);

    Material m_Material;

    public bool IsActive() => m_Material != null && strength.value > 0.0f;

    // 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/Vortex";

    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 Vortex effect.");
        }  
    }

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

        m_Material.SetVector("_Center", center.value);
        m_Material.SetFloat("_Strength", strength.value);
        m_Material.SetVector("_Offset", offset.value);
        
        m_Material.SetTexture("_InputTexture", source);
        HDUtils.DrawFullScreen(cmd, m_Material, destination);
    }

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