ComputeShader/Assets/Scripts/ComputeController.cs

93 lines
2.4 KiB
C#

using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UIElements;
public class ComputeController : MonoBehaviour
{
[Header("Conections")]
[SerializeField] private ComputeShader _computeShader;
[SerializeField] private Texture2D _inputTexture;
[SerializeField] private RenderTexture _resultTexture;
[Header("Config")]
[SerializeField] private int _width;
[SerializeField] private int _height;
[SerializeField] private float _scale = 1;
[SerializeField] private bool _resize;
[Header("state")]
[SerializeField] private float sin;
private int _kernelHandle;
private const int NumThreadX = 8;
private const int NumThreadY = 8;
#region ShaderVariables
private static readonly int Result = Shader.PropertyToID("result");
private static readonly int SourceTexture = Shader.PropertyToID("source_texture");
private static readonly int SinScaled = Shader.PropertyToID("sin_scaled");
#endregion
private void Start()
{
SetWidthHeight();
_kernelHandle = _computeShader.FindKernel("cs_main");
RunComputeShader();
}
private void RunComputeShader()
{
_resultTexture = new(_width, _height, 24);
_resultTexture.name = "ResultTexture";
_resultTexture.enableRandomWrite = true;
_resultTexture.Create();
_computeShader.SetTexture(_kernelHandle, SourceTexture, _inputTexture);
_computeShader.SetTexture(_kernelHandle, Result, _resultTexture);
DispatchShader();
}
private void DispatchShader()
{
_computeShader.Dispatch(_kernelHandle, _width / NumThreadX, _height / NumThreadY, 1);
}
private void OnGUI()
{
CheckScale();
ShaderUpdate();
GUI.DrawTexture(new Rect(0, 0, _width, _height), _inputTexture);
GUI.DrawTexture(new Rect(0, _height, _width, _height), _resultTexture);
}
private void ShaderUpdate()
{
sin = (Mathf.Sin(Time.unscaledTime) + 1) / 2;
_computeShader.SetFloat(SinScaled, sin);
DispatchShader();
}
private void CheckScale()
{
if (_resize)
{
_resize = false;
SetWidthHeight();
RunComputeShader();
}
}
private void SetWidthHeight()
{
_width = Mathf.RoundToInt(_inputTexture.width * _scale);
_height = Mathf.RoundToInt(_inputTexture.height * _scale);
}
}