使用范围:像素处理、粒子效果、大规模同步无依赖运算。
1\检测是否支持:
SystemInfo.supportsComputeShaders
2\创建Computer Shader
click>Create>Shader>Compute Shader
直接上代码
using UnityEngine;
public class CBW : MonoBehaviour
{
public ComputeShader shader;
public Camera cam;
public RenderTexture rt;
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if(rt == null)
{
RenderTexture camTex = cam.activeTexture;
if (camTex == null) return;
rt = new RenderTexture(camTex.descriptor);
rt.enableRandomWrite = true;
rt.Create();
}
if (shader == null|| rt == null) return;
Graphics.Blit(source, rt);
int kernel = shader.FindKernel("CSMain");
uint shaderThreadX, shaderThreadY, shaderThreadZ;
shader.GetKernelThreadGroupSizes(kernel,out shaderThreadX,out shaderThreadY,out shaderThreadZ);
int dispathXF = Mathf.CeilToInt(source.width / shaderThreadX)+1;
int dispathYF = Mathf.CeilToInt(source.height / shaderThreadY)+1;
shader.SetTexture(kernel, "InOutputTexture", rt);
shader.Dispatch(kernel,dispathXF,dispathYF,1);
Graphics.Blit(rt,destination);
}
}
Computer Shader
// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel CSMain
// Create a RenderTexture with enableRandomWrite flag and set it
// with cs.SetTexture
RWTexture2D<float4> InOutputTexture;
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
// TODO: insert actual code here!
float4 color = InOutputTexture[id.xy];
//Result[id.xy] = float4(id.x & id.y, (id.x & 15)/15.0, (id.y & 15)/15.0, 0.0);
float c = color.r * 0.30 + color.g * 0.59 + color.b * 0.11;
InOutputTexture[id.xy] = float4(c, c, c,color.a);
}
说明:
使用默认管线,如果是URP管线,需要使用Feature进行操作
使用Computer shader 前后