繁体   English   中英

金属着色器输出数据(GPGPU)

[英]Metal shader output data (GPGPU)

我正在尝试在ios上实现一些图像检测算法,并且我需要一些应作为着色器(金属)使用的数据准备,因此它应将结果数据传递给输出数组。

小例子:SWIFT

...
// Create buffer
var resultBuffer = device.makeBuffer(length: SIZE * MemoryLayout<Int32>.size, options: .storageModeShared)!

// Set buffer to encoder
computeCommandEncoder?.setBuffer(resultBuffer, offset: 0, index: 0)
...
// Call shader
commandBuffer.commit()
commandBuffer.waitUntilCompleted()

// Print first element for test
var p = resultBuffer.contents()
let first = p.load(as: UInt32.self)
print("first = \(first)")

MSL(金属着色器)

...
kernel void preparation(
  texture2d<float, access::read> inTexture [[texture(0)]], // Input texture

  texture2d<float, access::write> outTexture [[texture(1)]], // Output texture
  device uint* result [[ buffer(0) ]], // Output buffer
                uint2 gid [[thread_position_in_grid]])
{
    result[0] = 5; // Just for test set first element to 5
    float4 colorAtPixel = inTexture.read(gid);
    outTexture.write(colorAtPixel, gid); // Copy color from input texture to output texture
}

所以我希望它可以打印

first = 5

但它打印

first = 0

这样看来着色器不会更改缓冲区内容吗? 有什么想法使它起作用吗?

PS我使用iOs 11.2,iPhone 5S,XCode 9.2

您试图从线程组中的每个像素写入相同的输出存储位置。 如果要写入一个存储位置,则必须格外小心,仅对每个gid元素标识的每个像素写入1个存储位置。 更好的方法是只读取输入纹理并为每个像素写入输出纹理,只需删除uint * result缓冲区并直接使用纹理,您的头痛就会消失。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM