2016-11-17 70 views
1

我需要從MDLMeshBufferData實例創建一個MTKMeshBuffer實例。這裏是一個代碼片段:如何從MDLMeshBufferData中提取數據以填充MTKMeshBuffer?

let mdlm = MDLMesh(scnGeometry:sceneGeometry, bufferAllocator:nil) 

let mdlSubmesh:MDLSubmesh = mdlm.submeshes?[ 0 ] as! MDLSubmesh 

let mdlIndexBufferData:MDLMeshBufferData = mdlSubmesh.indexBuffer as! MDLMeshBufferData 

let d:Data = mdlIndexBufferData.data 

let mtlIndexBuffer:MTKMeshBuffer = device.makeBuffer(bytes: ???, length: ???, options:MTLResourceOptions.storageModeShared) as! MTKMeshBuffer 

The ???是我需要填寫的位。有人可以告訴我適當的API來從MDL緩衝區中提取位來填充MTK緩衝區嗎?

回答

1

實際上,通過嘗試將數據從網格中拉出並「手動」將其填充到金屬緩衝區中,可以爲自己做更多的工作。此外,MTKMeshBuffer不是MTLBuffer - 它包含金屬緩衝區,以及使用該緩衝區渲染時可能需要的信息。

實際上你要做什麼是模型I/O爲你自己分配Metalkit緩衝區而不是自己做,這意味着MetalKit爲數據分配金屬緩衝區,所以你不必複製它。然後使用MetalKit來訪問網格和緩衝區。像這樣的(未經測試)的東西:

let allocator = MTKMeshBufferAllocator(device: myMetalDevice) 
let mdlMesh = MDLMesh(scnGeometry: sceneGeometry, bufferAllocator: allocator) 
let mtkMesh = try! MTKMesh(mesh: mdlMesh, device: myMetalDevice) 
//   ~~~~ <- in real code, please handle errors 

// then, at render time... 
for (index, vertexBuffer) in mtkMesh.vertexBuffers.enumerated() { 
    // vertexBuffer is a MTKMeshBuffer, containing an MTLBuffer 
    renderEncoder.setVertexBuffer(vertexBuffer.buffer, 
            offset: vertexBuffer.offset, 
            at: index) 
} 
for submesh in mtkMesh.submeshes { 
    // submesh is a MTKSubmesh, containing an MTKMeshBuffer 
    renderEncoder.drawIndexedPrimitives(type: submesh.primitiveType, 
             indexCount: submesh.indexCount, 
             indexType: submesh.indexType, 
             indexBuffer: submesh.indexBuffer.buffer, 
             indexBufferOffset: submesh.indexBuffer.offset) 
} 
+0

是的,我通過MDLMesh工廠方法 - 平面/立方體/球體/ ...成功創建網格。效果很好。我從頭創建緩衝區的動機 - indexBuffer和vertexBuffer與讀取SCNScene文件 - .scn - 並從中提取網格有關。關鍵的API - MDLMesh(scnGeometry:sceneGeometry,bufferAllocator:MTKMeshBufferAllocator(device:device)) - 被破壞了,我將提交一個針對它的雷達bug。親自嘗試一下。 – dugla

相關問題