Search code examples
iosshaderswift5metal

iOS Metal Invalid device store executing vertex function "myFunction" encoder: draw: offset:


I have a project using Metal rendering, it is working fine when I pass one metal buffer to the shader function. However, when I pass a different buffer, I get the following errors:

(IOAF code 11)
with "Shader validation enabled" scheme diagnostic flag:

Invalid device store executing vertex function "myFunction" encoder: draw: offset:

Both buffers are initialized using the same function. The lifecycle of the first object holding the buffer is much longer than the second one.

Is the error caused by the object holding the buffer being deallocated?

/// Initializes the buffer with zeros, the buffer is given an appropriate length based on the provided element count.
    init(device: MTLDevice, count: Int, index: UInt32, label: String? = nil, options: MTLResourceOptions = []) {
        
        guard let buffer = device.makeBuffer(length: MemoryLayout<Element>.stride * count, options: options) else {
            fatalError("Failed to create MTLBuffer.")
        }
        self.buffer = buffer
        self.buffer.label = label
        self.count = count
        self.index = Int(index)
    }

 //usage:
 renderEncoder.setVertexBuffer(/*one of two buffers*/)

Solution

  • The issue was caused by the shader function trying to write the output of it's calculation at a wrong index. As long as the shader references the buffer from 0 to count, everything works with either buffer. The error was caused by the shader trying to reference the buffer using a wrong index, and stepping out of range of the buffer.