金属网格 IOS

Mesh in Metal IOS

我是 MTKMesh/MDLMesh 任何在线资源 material 的新手,无法在 2D 中创建自定义网格。我有顶点数据。

init(vertexBuffer: MDLMeshBuffer, vertexCount: Int,  descriptor: MDLVertexDescriptor, submeshes: [MDLSubmesh])

我希望使用这个功能。关于创建 MDLMeshBuffer、MDLVertexDescriptor、Submeshes

的任何建议

假设您有一个 Vertex 结构,其中有一个 float2 成员表示位置。您可以从这样的顶点数组 ([Vertex]) 和 16 位无符号整数索引数组 ([UInt16]).

开始

那么你可能会这样做:

let device = MTLCreateSystemDefaultDevice()!
let allocator = MTKMeshBufferAllocator(device: device)

let vertexBuffer = allocator.newBuffer(MemoryLayout<Vertex>.stride * vertices.count, type: .vertex)
let vertexMap = vertexBuffer.map()
vertexMap.bytes.assumingMemoryBound(to: Vertex.self).assign(from: vertices, count: vertices.count)

let indexBuffer = allocator.newBuffer(MemoryLayout<UInt16>.stride * indices.count, type: .index)
let indexMap = indexBuffer.map()
indexMap.bytes.assumingMemoryBound(to: UInt16.self).assign(from: indices, count: indices.count)

let submesh = MDLSubmesh(indexBuffer: indexBuffer,
                         indexCount: indices.count,
                         indexType: .uInt16,
                         geometryType: .triangles,
                         material: nil)

let vertexDescriptor = MDLVertexDescriptor()
vertexDescriptor.attributes[0] = MDLVertexAttribute(name: MDLVertexAttributePosition,
                                                    format: .float2,
                                                    offset: 0,
                                                    bufferIndex: 0)
let mdlMesh = MDLMesh(vertexBuffer: vertexBuffer,
                      vertexCount: vertices.count,
                      descriptor: vertexDescriptor, 
                      submeshes: [submesh])

let mesh = try? MTKMesh(mesh: mdlMesh, device: device)

如果您的顶点类型更复杂,您需要相应地调整顶点描述符。