Unity Compute Shader - 1 第一个Compute Shader

创建第一个Compute Shader时,需要先做一些准备工作:

  1. 创建一个Unity Built-in项目
  2. 在场景中创建一个Quad,设置其位置和旋转均为0
  3. 选中场景中的Main Camera,设置其位置为Vector3(0,0,-1)
  4. 设置Main Camera的Projection属性为Orthographic
  5. 调整Main Camera的Size属性值为0.5
  6. 创建一个材质球,材质球的shader使用Unlit/Texture
  7. 创建一个C#脚本,名称为AssignTexture
  8. C#脚本内容如下
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    using UnityEngine;

    public class AssignTexture : MonoBehaviour
    {
    //引用已经完成的ComputeShader,用于计算图片
    public ComputeShader shader;
    //生成图片的分辨率
    public int texResolution = 256;

    //Quad上的MeshRenderer组件
    public MeshRenderer meshRend;
    //经过ComputeShader计算生成的图片
    private RenderTexture outputTexture;
    //保存获取到的ComputeShader内核索引
    private int KernelHandle;

    private void Start()
    {
    //获取Quad上的MeshRenderer组件
    meshRend = gameObject.GetComponent<MeshRenderer>();

    //设置生成图片的大小
    outputTexture = new RenderTexture(texResolution, texResolution, 0);
    //创建的图片打开可读写
    outputTexture.enableRandomWrite = true;
    outputTexture.Create();
    }
    }
  9. 创建一个Compute Shader,名称为FirstComputeShader
  10. 将AssignTexture脚本挂载到Quad物体上,并将FirstComputeShader拖动到AssignTexture脚本的Shader变量栏中

准备工作完成后,继续在AssignTexture脚本中添加代码,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using UnityEngine;

public class AssignTexture : MonoBehaviour
{
...

private void Start()
{
...

InitShader();

DispatchShader(texResolution / 16, texResolution / 16);
}

private void InitShader()
{
//获取内核名称为CSMain的索引值
KernelHandle = shader.FindKernel("CSMain");
//将outputTexture发送给内核索引值为KernelHandle的cpmpute shader中的变量Result
//这句代码是在cpmpute shader中的Result变量来计算outputTexture
shader.SetTexture(KernelHandle, "Result", outputTexture);
//为Quad的材质赋值贴图,也就是计算后的outputTexture
meshRend.material.SetTexture("_MainTex", outputTexture);
}

private void DispatchShader(int _x, int _y)
{
//运行指定的cpmpute shader,在x,y,z上启动指定数量的计算着色器线程组
shader.Dispatch(KernelHandle, _x, _y, 1);
}

private void Update()
{
if (Input.GetKeyUp(KeyCode.A))
{
DispatchShader(texResolution / 8, texResolution /8 );
}
}
}

至此,我们就完成了第一个Compute Shader,在Unity中运行当前场景,可以看到Quad显示出了一个奇怪的图形:

这时按下键盘A键后,图片会发生变化,如下:

为什么会发生这样的情况?Compute Shader脚本中发生了什么?下一章中继续探索


相关链接

RenderTexture.Depth

ComputeShader.Dispatch

ComputeShader.FindKernel

ComputeShader.Dispatch