Search code examples
swifttexturesmetal

append data to existing contents of MTLBuffer in Metal


How to append data to MTLBuffer?

I have following data set:

var verticesArray:Array<Vertex>  = [
                A,B,C ,D,E,F
            ]

and I create a vertexBuffer(MTLBuffer) which can store multiple vertices arrays

var vertexData = Array<Float>()
    for vertex in vertices{
        vertexData += vertex.floatBuffer()
    }

    let dataSize = 1000*vertexData.count * MemoryLayout.size(ofValue: vertexData[0])
    vertexBuffer = device.makeBuffer(bytes: vertexData, length: dataSize, options: [])

I need to append to vertexBuffer another set of vertices as follow.

var verticesArray2:Array<Vertex>  = [
                    G,H,I ,J,K,L
                ]

How may I append? Need help.


Solution

  • A Metal buffer is not a like a Swift Array, Obj C NSMutableArray, or C++ STL vector. There is fixed memory backing for the buffer, so you can't resize it to add/append more data.

    Instead you'll need to create new buffer big enough to fit the existing array's data and the new elements you want to append, then copy them into the new expanded buffer. Since creating buffer and copying is expensive it's best to create add extra room each time you create a new buffer so that you can "append" many times without needing to create a new buffer and copy each time. Also, if the data is on the GPU in another buffer, you should use a MTLBlitCommandEncoder to perform the copy operations to the expanded buffer.

    I am wondering what you're ultimately trying to accomplish with this buffer, as it may not be a really great use of Metal.