2

我正在尝试打印MDLMesh. 我在操场上有以下代码:

import Cocoa
import ModelIO

let boxURL = Bundle.main.url(forResource: "box", withExtension: "obj")!

let asset = MDLAsset(url: boxURL)

let mesh = asset.object(at: 0) as! MDLMesh

let vbuf = mesh.vertexBuffers[0]
let vbufmap = vbuf.map()
let layout = mesh.vertexDescriptor.layouts.firstObject as! MDLVertexBufferLayout
let stride = layout.stride

assert(vbuf.length == mesh.vertexCount*stride)

for i in 0..<mesh.vertexCount {
    let v = (vbufmap.bytes+i*stride).bindMemory(to: float3.self, capacity: 1).pointee
    print(v)
}

它正确打印第一个顶点,然后在第二个顶点上出现段错误。我怀疑我做错了什么bindMemory

更新:

将顶点复制到Data作品中:

let data = Data(bytes: vbufmap.bytes, count: vbuf.length)

for i in 0..<mesh.vertexCount {
    var v = float3(0)
    let buffer = UnsafeMutableBufferPointer(start: &v, count: 1)
    let start = i*stride
    data.copyBytes(to: buffer, from: start..<start+MemoryLayout<float3>.size)
    print(v)
}

但我不应该复制所有顶点数据来访问顶点。

4

0 回答 0