I'm working with ModelI/O to show 3D model. This is my code:
// Load the .OBJ file
guard let url = Bundle.main.url(forResource: "agera r", withExtension: "obj") else {
fatalError("Failed to find model file.")
}
let asset = MDLAsset(url:url)
guard let object = asset.object(at: 0) as? MDLMesh else {
fatalError("Failed to get mesh from asset.")
}
// Create a material from the various textures
let scatteringFunction = MDLScatteringFunction()
let material = MDLMaterial(name: "baseMaterial", scatteringFunction: scatteringFunction)
let textureFileName = "agera_r.mtl"
material.setTextureProperties([.baseColor: textureFileName])
// Apply the texture to every submesh of the asset
for submesh in object.submeshes! {
if let submesh = submesh as? MDLSubmesh {
submesh.material = material
}
}
// Wrap the ModelIO object in a SceneKit object
let node = SCNNode(mdlObject: object)
let scene = SCNScene()
scene.rootNode.addChildNode(node)
// Set up the SceneView
sceneView.autoenablesDefaultLighting = true
sceneView.allowsCameraControl = true
sceneView.scene = scene
sceneView.backgroundColor = UIColor.black
}
extension MDLMaterial {
func setTextureProperties(_ textures: [MDLMaterialSemantic:String]) -> Void {
for (key,value) in textures {
guard let url = Bundle.main.url(forResource: value, withExtension: "") else {
fatalError("Failed to find URL for resource \(value).")
}
let property = MDLMaterialProperty(name:value, semantic: key, url: url)
self.setProperty(property)
}
}
The problem is when the app run, the 3D model is shown but the .mtl texture file not apply to it. How to fix this issue? Thanks all.