BlueRoseNote/07-Other/Unity/ComputeShader笔记.md
2023-06-29 11:55:02 +08:00

44 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## Shader
- RWStructuredBuffer:可读写可用类型float1234、uint1234
- StructuredBuffer:对应的只读BUffer
## C#脚本
### 声明变量
CS与Buffer
```c#
[SerializeField]
ComputeShader computeShader = default;
ComputeBuffer positionBuffer;
```
### 绑定CS中的变量并且执行
声明Shader中变量id以用于绑定
```c#
static readonly int intpositionsId = Shader.PropertyToID("_Positions"),
resolutionId= Shader.PropertyToID("_Resolution"),
stepId= Shader.PropertyToID("_Step"),
timeId= Shader.PropertyToID("_Time");
```
给变量绑定数值
```c#
computeShader.SetInt(resolutionId, resolution);
computeShader.SetFloat(stepId, step);
computeShader.SetFloat(timeId, Time.time);
computeShader.SetBuffer(0, positionsId, positionBuffer);
```
执行
```c#
int groups = Mathf.CeilToInt(resolution / 8f);
computeShader.Dispatch(0, groups, groups, 1);
```
### 绘制GPU Instance命令
```c#
//需要传入边界盒以及绘制数量
var bounds=new Bounds(Vector3.zero,Vector3.one*(2f+2f/resolution));
Graphics.DrawMeshInstancedProcedural(mesh, 0, material,bounds,positionBuffer.count);
```
### 多kernel
CS可能拥有多个内核函数此时computeShader的SetBuffer()与Dispatch()可以通过第一个形参来设置kernel index。