MetalKit - Drawable.texture断言错误

soo*_*oon 7 macos swift metal

我是新手,MetalKit并尝试将本教程playgroundback 转换为OSXapp:

    import MetalKit

public class MetalView: MTKView {

    var queue: MTLCommandQueue! = nil
    var cps: MTLComputePipelineState! = nil

    required public init(coder: NSCoder) {
        super.init(coder: coder)
        device = MTLCreateSystemDefaultDevice()
        registerShaders()
    }


    override public func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)
        if let drawable = currentDrawable {
            let command_buffer = queue.commandBuffer()
            let command_encoder = command_buffer.computeCommandEncoder()
            command_encoder.setComputePipelineState(cps)
            command_encoder.setTexture(drawable.texture, atIndex: 0)
            let threadGroupCount = MTLSizeMake(8, 8, 1)
            let threadGroups = MTLSizeMake(drawable.texture.width / threadGroupCount.width, drawable.texture.height / threadGroupCount.height, 1)
            command_encoder.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadGroupCount)
            command_encoder.endEncoding()
            command_buffer.presentDrawable(drawable)
            command_buffer.commit()
        }
    }

    func registerShaders() {
        queue = device!.newCommandQueue()
        do {
            let library = device!.newDefaultLibrary()!
            let kernel = library.newFunctionWithName("compute")!
            cps = try device!.newComputePipelineStateWithFunction(kernel)
        } catch let e {
            Swift.print("\(e)")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这一行得到了一个错误:

command_encoder.setTexture(drawable.texture, atIndex: 0)
Run Code Online (Sandbox Code Playgroud)

失败的断言`frameBufferOnly纹理不支持计算.

我该如何解决这个问题?

war*_*enm 17

如果你想从一个计算函数写入一个drawable的纹理,你需要告诉MTKView它应该将它的图层配置为不仅仅是framebuffer:

metalView.framebufferOnly = false
Run Code Online (Sandbox Code Playgroud)

将此值设置为false时,drawable将为您提供一个纹理shaderWrite,其中设置了使用标志,这是从着色器函数编写纹理时所必需的.