在下一个计算着色器中使用一个计算着色器的结果的正确方法是什么

What is the proper method to use the results of one compute shader in the next compute shader

假设我在金属中分配了两个计算着色器 A 和 B。在 A 完成之前,我不希望 B 运行。目前我正在将每个着色器编码到它们自己的命令缓冲区中并像这样提交:

commandBufferA.commit()
commandBufferA.waitUntilCompleted()
commandBufferB.commit()

这是正确的技巧吗?

如果您需要在 CPU 上使用内核的结果,则在命令缓冲区上调用 waitUntilCompleted() 很有用,但如果您的意图只是使用结果,则没有必要且效率低下后续计算命令中的计算命令(调度)。如果计算命令之间存在数据依赖性,则前者写入的结果保证对后者可见,即使在单个命令缓冲区中也是如此。所以,你可以这样构造它:

let commandBuffer = commandQueue.makeCommandBuffer()
let commandEncoder = commandBuffer.makeComputeCommandEncoder()

commandEncoder.setComputePipelineState(pipelineStateA)
commandEncoder.setTexture(inputTexture, at: 0)
commandEncoder.setTexture(intermediateTexture, at: 1)
commandEncoder.dispatchThreadgroups(threadgroupCount, 
                                    threadsPerThreadgroup: threadgroupSize)

commandEncoder.setComputePipelineState(pipelineStateB)
commandEncoder.setTexture(intermediateTexture, at: 0)
commandEncoder.setTexture(outputTexture, at: 1)
commandEncoder.dispatchThreadgroups(threadgroupCount, 
                                    threadsPerThreadgroup: threadgroupSize)

commandEncoder.endEncoding()
commandBuffer.commit()

commandBuffer.waitUntilCompleted() // optional; only if you need to read the result on the CPU