问题
I am passing a uniform buffer to both vertex and fragment shaders.
let uniformBuffer = device.makeBuffer(length: 4096, options: [])
renderEncoder.setVertexBuffer(uniformBuffer, offset: 0, at: 1)
renderEncoder.setFragmentBuffer(uniformBuffer,offset:0, at: 1)
Does this copy the uniformBuffer from CPU to GPU twice? Then I will instead pass the buffer from vertex shader to fragment shader which happens just inside the GPU.
回答1:
There are no copies involved specifically with setVertexBuffer()
or setFragmentBuffer()
. Those only put a reference to the buffer into the render encoder's buffer tables.
Your code and Metal need only ensure that the contents of the buffer are up-to-date on the GPU and from there it will be referenced. As Matthjis mentioned, how you do this depends on the storageMode
. If you're using managed mode, if you modify the buffer contents on the CPU, you need to tell Metal about that using didModifyRange()
. Once you do that, Metal knows to copy the modified range to the GPU the next time it's needed there. That single copy is sufficient, regardless of how many times the buffer is referenced by encoder buffer tables.
Note that setVertexBytes()
and setFragmentBytes()
work differently. Those have to (and do) make immediate copies of the passed-in byte array, each time they are called.
回答2:
I think this depends on the platform. On iOS the memory is shared between the CPU and GPU and so no copy is performed at all. On macOS, it depends on the storageMode
of the buffer or texture whether copying is involved (but I don't know if it copies the buffer twice in your case or just once).
来源:https://stackoverflow.com/questions/43797198/in-metal-does-setting-vertex-and-fragment-buffer-to-same-mtlbuffer-copies-it-to