打印MDLMesh的顶点位置

时间:2019-01-24 19:29:32

标签: swift cocoa scenekit-modelio

我正在尝试打印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)
}

但是我不必复制所有顶点数据即可访问顶点。

0 个答案:

没有答案