Search code examples
iosswift3dscenekitapple-model-io

SceneKit: export mesh that has been imported from STL results in garbage


I am using this gist to import a binary STL 3d mesh into a SCNNode, which works fine (I can view the mesh in a SCNView and it looks good).

However, if I try to export the (unchanged) mesh using either MDLAsset.export(to: url) or SCNScene.write(to: url) to an STL or OBJ file, the resulting mesh is broken.

If I load the example ship.scn scene and then export to STL, everything looks good. This makes me think that there must be something wrong about how the above mentioned gist creates the SCNNode, but I can't figure out what it is.

Actual model: enter image description here Result of STL/OBJ export: enter image description here


Solution

  • I figured it out myself. The SCNGeometryElement's constructor allows to pass nil for the indices data. While this is fine for showing the mesh in a scene, at least the export functionality and probably other parts of the framework rely on the data being populated - which, contrary to what one would expect - isn't done by the constructor automatically. So you need to do that yourself. Luckily there is another constructor which makes this easier:

    let indices = [UInt32](0..<UInt32(trianglesCounted * 3))
    let countedTriangles = SCNGeometryElement(indices: indices, primitiveType: .triangles)