コンピュートシェーダーを実行するレンダーパスを作成するには、以下の手順を実行します。
プラットフォームがコンピュートシェーダーをサポートしているか確認するには、SystemInfo.supportsComputeShaders API を使用します。
ScriptableRenderPass を作成 するときに、以下の手順を実行します。
AddRasterRenderPass の代わりに AddComputePass を使用します。RasterGraphContext の代わりに ComputeGraphContext を使用します。例:
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));
}
ImportBuffer レンダーグラフ API を使用してバッファをレンダーグラフシステムが使用できるハンドルに変換し、パスデータの BufferHandle フィールドを設定します。例:
BufferHandle outputHandleRG = renderGraph.ImportBuffer(outputBuffer);
passData.output = outputHandleRG;
UseBuffer メソッドを使用して、バッファをレンダーグラフシステムで書き込み可能なバッファとして設定します。
builder.UseBuffer(passData.output, AccessFlags.Write);
以下の手順に従ってください。
コンピュートシェーダーをレンダーパスに渡します。例えば、ScriptableRendererFeature クラスでは、ComputeShader プロパティを公開してから、コンピュートシェーダーをレンダーパスクラスに渡します。
パスデータに 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 メソッドで、SetComputeBufferParam API を使用してバッファをコンピュートシェーダーにアタッチします。例:
// 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 API を使用します。
データは、レンダーパスが実行され、コンピュートシェーダーの実行が終了した後にのみ取得できます。
例:
// 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 という例を参照してください。