ComputeShader/Assets/Scripts/ComputeController.cs

70 lines
2.0 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;
private int _kernelHandle;
private static readonly int Result = Shader.PropertyToID("result");
private static readonly int SourceTexture = Shader.PropertyToID("source_texture");
private static readonly int _threadgroupX = 8;
private static readonly int _threadgroupY = 8;
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);
_computeShader.Dispatch(_kernelHandle, _width / _threadgroupX, _height / _threadgroupY, 1);
}
private void OnGUI()
{
CheckScale();
GUI.DrawTexture(new Rect(0, 0, _width, _height), _inputTexture);
GUI.DrawTexture(new Rect(0, _height, _width, _height), _resultTexture);
}
private void CheckScale()
{
if (_resize)
{
_resize = false;
SetWidthHeight();
RunComputeShader();
}
}
private void SetWidthHeight()
{
_width = Mathf.RoundToInt(_inputTexture.width * _scale);
_height = Mathf.RoundToInt(_inputTexture.height * _scale);
}
}