Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

Trouble with MDLMesh.newBox()

I'm trying to build an MDLMesh then add normals

let mdlMesh = MDLMesh.newBox(withDimensions: SIMD3<Float>(1, 1, 1),
                                 segments: SIMD3<UInt32>(2, 2, 2),
                                 geometryType: MDLGeometryType.triangles,
                                 inwardNormals:false,
                                 allocator: allocator)

mdlMesh.addNormals(withAttributeNamed: MDLVertexAttributeNormal, creaseThreshold: 0)

When I render the mesh, some normals are (0,0,0). I don't know if the problem is in the mesh, or in the conversion to MTKMesh. Is there a way to examine an MDLMesh with the geometry viewer? When I look at the variable values for my mdlMesh I get this:

Not too useful. I don't know how to track down the normals. What's the best way to find out where the normals getting broken?

To check the normals you could export to a .obj and then open the result in an editing tool to inspect them.

For example, the following:

let device = MTLCreateSystemDefaultDevice()
let allocator = MTKMeshBufferAllocator(device: device!)
let mdlMesh = MDLMesh.newBox(withDimensions: SIMD3<Float>(1, 1, 1),
                                 segments: SIMD3<UInt32>(2, 2, 2),
                                 geometryType: MDLGeometryType.triangles,
                                 inwardNormals:false,
                                 allocator: allocator)
mdlMesh.addNormals(withAttributeNamed: MDLVertexAttributeNormal, creaseThreshold: 0)

let asset = MDLAsset()
asset.add(mdlMesh)
/* substitute your username in the path below */
let url = URL(fileURLWithPath: "/Users/dtsengineer42/Desktop/exported_mesh.obj") // Choose your desired path and format
do {
    try asset.export(to: url)
    print("MDLMesh saved successfully to \(url)")
} catch {
    print("Error exporting MDLMesh: \(error)")
}

exports the mesh as a file named exported_mesh.obj on the desktop. Importing that file into a Blender scene and displaying the normals produces the following result:

Trouble with MDLMesh.newBox()
 
 
Q