Get SCNGeometry from Model I/O

217 Views Asked by At

I am trying to import a Mesh into a SCNGeometry. I do want to manipulate the vertices individually from the CPU. Therefore, I want to do it according to the following post: https://developer.apple.com/forums/thread/91618 . So far I have imported it into the Model I/O Framework and created a MTLBuffer.

    let MDLPositionData = mesh?.vertexAttributeData(forAttributeNamed: "position", as: .float3)
    
    let vertexBuffer1 = device.makeBuffer(bytes: MDLPositionData!.dataStart,
                                          length: MDLPositionData!.bufferSize,
                                          options: [.cpuCacheModeWriteCombined])
    let vertexSource = SCNGeometrySource(
           buffer: vertexBuffer1!,
           vertexFormat: vertexFormat,
           semantic: SCNGeometrySource.Semantic.vertex,
           vertexCount: mesh!.vertexCount,
           dataOffset: 0,
           dataStride: MemoryLayout<vector_float3>.size)

The SCNGeometry needs index elements to properly show the mesh. Where do I get those? I have tried to use the submeshes from Model I/O:

    let submesh = mesh?.submeshes?[0]
    let indexBuffer = (submesh as? MDLSubmesh)?.indexBuffer(asIndexType: .uInt32)
    let indexBufferData = Data(bytes: indexBuffer!.map().bytes, count: indexBuffer!.length)
    let indexElement = SCNGeometryElement(
        data: indexBufferData,
        primitiveType: SCNGeometryPrimitiveType.triangles,
        primitiveCount: indexBuffer!.length,
        bytesPerIndex: 32)
    let geo = SCNGeometry(sources: [vertexSource, normalSource], elements: [indexElement])

But this trows the error [SceneKit] Error: C3DMeshElementSetPrimitives invalid index buffer size and shows the following geometry: The Teapot. It seems like the vertices aren't connected properly.

How do I get the correct Index data? Thank you!

0

There are 0 best solutions below