为什么我没有得到这个金属内核的结果

时间:2016-01-01 09:20:36

标签: swift2 xcode7 metal

我试图理解Metal计算着色器的工作原理,所以我写了这段代码:

class AppDelegate: NSObject, NSApplicationDelegate {


    var number:Float!
    var buffer:MTLBuffer!


    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
        let metalDevice = MTLCreateSystemDefaultDevice()!
        let library = metalDevice.newDefaultLibrary()!
        let commandQueue = metalDevice.newCommandQueue()
        let commandBuffer = commandQueue.commandBuffer()
        let commandEncoder = commandBuffer.computeCommandEncoder()


        let pointlessFunction = library.newFunctionWithName("pointless")!
        let pipelineState = try! metalDevice.newComputePipelineStateWithFunction(pointlessFunction)
        commandEncoder.setComputePipelineState(pipelineState)
        number = 12

        buffer = metalDevice.newBufferWithBytes(&number, length: sizeof(Float), options: MTLResourceOptions.StorageModeShared)
        commandEncoder.setBuffer(buffer, offset: 0, atIndex: 0)


        commandEncoder.endEncoding()

        commandBuffer.commit()
        commandBuffer.waitUntilCompleted()

        let data = NSData(bytesNoCopy: buffer.contents(), length: sizeof(Float), freeWhenDone: false)
        var newResult:Float = 0
        data.getBytes(&newResult, length: sizeof(Float))
        print(newResult)




    }

通过使用StorageModeShared创建缓冲区,我希望对我的Swift代码中反映的Metal缓冲区进行更改,但是当我填充newResult变量时,看起来缓冲区的值仍然与开头时的值相同(12)虽然它应该是125:

#include <metal_stdlib>
using namespace metal;



kernel void pointless (device float* outData [[ buffer(0) ]]) {

    *outData = 125.0;
}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

除非您发送内核函数,否则它不会运行。我认为你假设你有一个功能,那么Metal应该运行一次,直到你说不然,但那不会发生。它根本不会运行。在endEncoding之前添加此内容,您就可以开始了!

let size = MTLSize(width: 1, height: 1, depth: 1)
commandEncoder.dispatchThreadgroups(size, threadsPerThreadgroup: size)