컴퓨트 셰이더를 실행하는 렌더 패스를 생성하는 방법은 다음과 같습니다.
플랫폼이 컴퓨트 셰이더를 지원하는지 확인하려면 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라는 예시를 참고하십시오.