gpt4 book ai didi

ios - 从通用MTLBuffer读取内容?

转载 作者:行者123 更新时间:2023-12-01 21:23:46 24 4
gpt4 key购买 nike

在我的应用程序中,我有一个MTLBuffer,正在使用泛型类型进行实例化。在一种特定情况下,缓冲区将保存与点云中的粒子相关的值,并以此定义;

struct ParticleUniforms {
simd_float3 position;
simd_float3 color;
float confidence;
};
我像这样实例化 MTLBuffer;
guard let buffer = device.makeBuffer(length: MemoryLayout<Element>.stride * count, options: options) else {
fatalError("Failed to create MTLBuffer.")
}
但是,我要努力的地方是了解如何读取缓冲区的内容。而且,我希望将缓冲区中每个项目的一个元素复制到CPU上的一个数组中,稍后我将使用它。
实际上,缓冲区包含 ParticleUniforms的集合,我想访问每个项目的 position值,将该位置保存到单独的数组中。
我在Stack Overflow上看到的所有示例似乎都显示 MTLBuffer持有Float的集合,尽管我没有看到任何使用泛型类型的例子。

最佳答案

看来您要实现的目标只能通过将每个成员保持在连续块中的C结构来完成(C结构的数组是not必定是连续的,但是MemoryLayout<Type>.stride将解决所有潜在的填充问题)。 Swift结构属性may not be contiguous,因此以下用于访问成员值的方法将无法实际使用。不幸的是,在使用void*时,您需要知道数据描述的内容,这并不特别适合Swift泛型类型。但是,我将提供潜在的解决方案。
C文件:

#ifndef Test_h
#define Test_h

#include <simd/simd.h>

typedef struct {
vector_float3 testA;
vector_float3 testB;
} CustomC;

#endif /* Test_h */
Swift文件(假定为桥接头)
import Metal

// MARK: Convenience
typealias MTLCStructMemberFormat = MTLVertexFormat

@_functionBuilder
struct ArrayLayout { static func buildBlock<T>(_ arr: T...) -> [T] { arr } }

extension MTLCStructMemberFormat {
var stride: Int {
switch self {
case .float2: return MemoryLayout<simd_float2>.stride
case .float3: return MemoryLayout<simd_float3>.stride
default: fatalError("Case unaccounted for")
}
}
}

// MARK: Custom Protocol
protocol CMetalStruct {
/// Returns the type of the `ith` member
static var memoryLayouts: [MTLCStructMemberFormat] { get }
}

// Custom Allocator
class CustomBufferAllocator<Element> where Element: CMetalStruct {

var buffer: MTLBuffer!
var count: Int

init(bytes: UnsafeMutableRawPointer, count: Int, options: MTLResourceOptions = []) {
guard let buffer = device.makeBuffer(bytes: bytes, length: count * MemoryLayout<Element>.stride, options: options) else {
fatalError("Failed to create MTLBuffer.")
}
self.buffer = buffer
self.count = count
}

func readBufferContents<T>(element_position_in_array n: Int, memberID: Int, expectedType type: T.Type = T.self)
-> T {
let pointerAddition = n * MemoryLayout<Element>.stride
let valueToIncrement = Element.memoryLayouts[0..<memberID].reduce(0) { $0 + $1.stride }
return buffer.contents().advanced(by: pointerAddition + valueToIncrement).bindMemory(to: T.self, capacity: 1).pointee
}

func extractMembers<T>(memberID: Int, expectedType type: T.Type = T.self) -> [T] {
var array: [T] = []

for n in 0..<count {
let pointerAddition = n * MemoryLayout<Element>.stride
let valueToIncrement = Element.memoryLayouts[0..<memberID].reduce(0) { $0 + $1.stride }
let contents = buffer.contents().advanced(by: pointerAddition + valueToIncrement).bindMemory(to: T.self, capacity: 1).pointee
array.append(contents)
}

return array
}
}

// Example

// First extend the custom struct to conform to out type
extension CustomC: CMetalStruct {
@ArrayLayout static var memoryLayouts: [MTLCStructMemberFormat] {
MTLCStructMemberFormat.float3
MTLCStructMemberFormat.float3
}
}

let device = MTLCreateSystemDefaultDevice()!
var CTypes = [CustomC(testA: .init(59, 99, 0), testB: .init(102, 111, 52)), CustomC(testA: .init(10, 11, 5), testB: .one), CustomC(testA: .zero, testB: .init(5, 5, 5))]

let allocator = CustomBufferAllocator<CustomC>(bytes: &CTypes, count: 3)
let value = allocator.readBufferContents(element_position_in_array: 1, memberID: 0, expectedType: simd_float3.self)
print(value)

// Prints SIMD3<Float>(10.0, 11.0, 5.0)

let group = allocator.extractMembers(memberID: 1, expectedType: simd_float3.self)
print(group)

// Prints [SIMD3<Float>(102.0, 111.0, 52.0), SIMD3<Float>(1.0, 1.0, 1.0), SIMD3<Float>(5.0, 5.0, 5.0)]
这类似于 MTLVertexDescriptor,除了手动访问内存,而不是通过 [[stage_in]]属性和传递到片段着色器顶点的每个实例的参数表访问。您甚至可以扩展分配器以接受带有属性名称的字符串参数,并保留一些映射到成员ID的字典。

关于ios - 从通用MTLBuffer读取内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63606753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com