ios – 金属着色语言 – (控制台)输出?

我可以使用控制台输出调试我的金属着色语言代码(比如在 Swift中打印)吗?

如果有,怎么样?

如果不是,有没有其他方法从我的.metal文件输出变量? (也许通过使用commandEncoder-buffer将数据从.metal文件传递到我的.swift文件?)

我没有成功尝试通过commandEncoder传递对Int变量(在我的.swift文件中)的引用到我的.metal文件.在.metal文件中,我为int变量赋值,但是如果我在swift文件中打印Int,则指定的值不存在.

.swift文件:

...
var myMetalOutput: Int = 0
...
let printBuffer = device.newBufferWithBytes(&myMetalOutput,length: sizeof(Int),options: MTLResourceOptions.CPUCacheModeDefaultCache)
commandEncoder.setBuffer(printBuffer,offset: 0,atIndex: 8)
...
commandBuffer.commit()
drawable.present()
print("myMetalOutput: \(myMetalOutput)")
...

.metal文件:

...
kernel void shader(...,device int &printBuffer [[8]],...) {
...
printBuffer = 123;
...
}

控制台输出始终为myMetalOutput:0

解决方法

如果有人需要,这是一个有效的解决方案:
let device = MTLCreateSystemDefaultDevice()!
let commandQueue = device.newCommandQueue()
let defaultLibrary = device.newDefaultLibrary()!
let commandBuffer = commandQueue.commandBuffer()
let computeCommandEncoder = commandBuffer.computeCommandEncoder()

let program = defaultLibrary.newFunctionWithName("shader")

do
{
    let computePipelineFilter = try device.newComputePipelineStateWithFunction(program!)
    computeCommandEncoder.setComputePipelineState(computePipelineFilter)
    var resultdata = [Int](count: 1,repeatedValue: 0)
    let outVectorBuffer = device.newBufferWithBytes(&resultdata,length: sizeofValue(1),options: MTLResourceOptions.CPUCacheModeDefaultCache)
    computeCommandEncoder.setBuffer(outVectorBuffer,atIndex: 0)


    let threadsPerGroup = MTLSize(width:1,height:1,depth:1)
    let numThreadgroups = MTLSize(width:1,depth:1)
    computeCommandEncoder.dispatchThreadgroups(numThreadgroups,threadsPerThreadgroup: threadsPerGroup)


    computeCommandEncoder.endEncoding()

    commandBuffer.addCompletedHandler {commandBuffer in
        let data = NSData(bytes: outVectorBuffer.contents(),length: sizeof(NSInteger))
        var out: NSInteger = 0
        data.getBytes(&out,length: sizeof(NSInteger))
        print("data: \(out)")
    }

    commandBuffer.commit()

}
catch
{
    fatalError("newComputePipelineStateWithFunction failed ")
}

着色器:

kernel void shader(device int &printBuffer [[buffer(0)]],uint id [[ thread_position_in_grid ]]) {

    printBuffer = 123;

}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...