[Swift] Converting between Data, Buffers, variable types efficiently.

Ahoy Developrs,

I was wondering if someone might be able to help me, regarding working with Data, Buffers and Pointers, as I am working with Metal, ModelIO and large arrays of vertex data.

Are there ways of converting/accessing Data instances as their original variable type without having to map/duplicate the data into a new variable? and visa-vera. I have to convert arrays into MDLMeshBuffer to pass them into ModelIO, from custom geometry that I have made at runtime.

This can be quite convoluted as I have my own array of structs for geometric topology. This gets converted into MetalBuffer for GPU drawing, but I want to leverage ModelIO for importing/exporting. To leverage ModelIO I need to convert to and from the ModelIO Mesh Buffers, which can be converted into Data objects, and then convert those into data specific

All this conversion to and from create quite a bit of memory bloat.

The following are 3 examples of how I have been interacting with the different types, are there better /more efficient ways of doing this?

// Converts Data to variable
var positions = Array<simd_float3>(repeating: simd_float3.zero, count: data2.count/MemoryLayout<simd_float3>.stride)
  _ = arr2.withUnsafeMutableBytes { data.copyBytes(to: $0) }

// Example ModelIO vert conversion
for i in 0..<mdlMesh.vertexBuffers.count {
      let vBuff = mdlMesh.vertexBuffers[i]
      let buffLyt = mdlMesh.vertexDescriptor.layouts[i] as! MDLVertexBufferLayout
      let vertCount = vBuff.length / buffLyt.stride
      let buffermap:MDLMeshBufferMap = vBuff.map()
      let rawBasePtr:UnsafeMutableRawPointer = buffermap.bytes
       
      for vertIndex in 0..<vertCount {
        let b = rawBasePtr.load(fromByteOffset: buffLyt.stride * vertIndex, as: (simd_float3).self)
        vertices.append(b)
      }
    }

// Example ModelIO submesh conversion
/// The layout of the face indicies
var topologyVertCount:Array<UInt8> = []
if subMesh.topology != nil {
   let topology = subMesh.topology!
   let faceBuffer = topology.faceTopology!
   print("Topology Buffer : \(topology)")
   print(" face count: \(topology.faceCount)")
   print(" hole count: \(topology.holeCount)")
   for faceIndex in 0..<topology.faceCount {
          let b = faceBuffer.map().bytes.load(fromByteOffset: MemoryLayout<UInt8>.stride * faceIndex, as: UInt8.self)
          topologyVertCount.append(b)
   }
}

Thank you for the help, Simon

[Swift] Converting between Data, Buffers, variable types efficiently.
 
 
Q