包含此页的版本:
不含此页的版本:
创建运行计算的渲染通道着色器在 GPU 上运行的程序。更多信息
请参阅术语表,请执行以下作:
要检查平台是否支持计算着色器,请使用SystemInfo.supportsComputeShaders应用程序接口
当您创建一个ScriptableRenderPass,请执行以下作:
AddComputePass而不是AddRasterRenderPass.ComputeGraphContext而不是RasterGraphContext.例如:
class ComputePass : ScriptableRenderPass
{
...
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer contextData)
{
...
// Use AddComputePass instead of AddRasterRenderPass.
using (var builder = renderGraph.AddComputePass("MyComputePass", out PassData data))
{
...
// Use ComputeGraphContext instead of RasterGraphContext.
builder.SetRenderFunc((PassData data, ComputeGraphContext context) => ExecutePass(data, context));
...
}
}
}
若要创建计算着色器输出到的缓冲区,请执行以下步骤:
创建一个图形缓冲区,然后在通道数据中为其添加句柄。
// Declare an output buffer
public GraphicsBuffer outputBuffer;
// Add a handle to the output buffer in your pass data
class PassData
{
public BufferHandle output;
}
// Create the buffer in the render pass constructor
public ComputePass(ComputeShader computeShader)
{
// Create the output buffer as a structured buffer
// Create the buffer with a length of 5 integers, so the compute shader can output 5 values.
outputBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, 5, sizeof(int));
}
使用ImportBufferrender graph API 将缓冲区转换为渲染图系统可以使用的句柄,然后将BufferHandle字段。例如:
BufferHandle outputHandleRG = renderGraph.ImportBuffer(outputBuffer);
passData.output = outputHandleRG;
使用UseBuffer方法将缓冲区设置为渲染图系统中的可写缓冲区。
builder.UseBuffer(passData.output, AccessFlags.Write);
按着这些次序:
将计算着色器传递给渲染通道。例如,在ScriptableRendererFeature类,公开一个ComputeShader属性,然后将计算着色器传递到 Render Pass 类中。
添加一个ComputeShader字段设置为传递数据,并将其设置为计算着色器。例如:
// Add a `ComputeShader` field to your pass data
class PassData
{
...
public ComputeShader computeShader;
}
// Set the `ComputeShader` field to the compute shader
passData.computeShader = yourComputeShader;
在您的SetRenderFunc方法,使用SetComputeBufferParamAPI 将缓冲区附加到计算着色器。例如:
// The first parameter is the compute shader
// The second parameter is the function that uses the buffer
// The third parameter is the StructuredBuffer output variable to attach the buffer to
// The fourth parameter is the handle to the output buffer
context.cmd.SetComputeBufferParam(passData.computeShader, passData.computeShader.FindKernel("Main"), "outputData", passData.output);
使用DispatchCompute用于执行计算着色器的 API。
context.cmd.DispatchCompute(passData.computeShader, passData.computeShader.FindKernel("CSMain"), 1, 1, 1);
要从输出缓冲区获取数据,请使用GraphicsBuffer.GetData应用程序接口。
只有在渲染传递执行且计算着色器完成运行后,才能提取数据。
例如:
// Create an array to store the output data
outputData = new int[5];
// Copy the output data from the output buffer to the array
outputBuffer.GetData(outputData);
有关完整示例,请参阅渲染图系统URP包示例中名为 计算(Compute) 的示例。