swift - 在scenekit中使用.obj从文档目录加载.mtl文件以获得纹理
问题描述
我正在尝试从文档目录加载下载的 3d 对象。我已经成功地在 scenekit 中加载了 3d 对象文件和 .mtl 文件,但是在 .mtl 文件中命名的图像不会被渲染以在 3d 模型上应用纹理,这些纹理也放置在与 .mtl 文件中同名的文档目录中。
下面是使用的代码
func loadObjToScene() {
let scene = SCNScene()
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
cameraNode.position = SCNVector3.init(0, 0, 15)
// create and add a light to the scene
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light?.type = .omni
lightNode.position = SCNVector3.init(0, 0, 10)
scene.rootNode.addChildNode(lightNode)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light?.type = .ambient
ambientLightNode.light?.color = UIColor.darkGray
scene.rootNode.addChildNode(ambientLightNode)
scnView.scene = scene
scnView.allowsCameraControl = true
scnView.showsStatistics = false
scnView.backgroundColor = UIColor.white
let mdlAsset = MDLAsset(url: URL(fileURLWithPath: "\(MZUtility.baseFilePath)/\(/obj?.objectUrl?.fileName)"))
let scatteringFunction = MDLScatteringFunction.init()
let material = MDLMaterial.init(name: "baseMaterial", scatteringFunction: scatteringFunction)
let textureFileName = "Ford_Explorer_(Mk5f)_(U502)_Police_Interceptor_Utility_HQinterior_2016.mtl"
material.setTextureProperties(textures: [MDLMaterialSemantic.baseColor : textureFileName])
for mesh in ((mdlAsset.object(at: 0) as? MDLMesh)?.submeshes as? [MDLSubmesh]) ?? [] {
print("Mesh Name: \(mesh.name)")
mesh.material = material
}
mdlAsset.loadTextures()
let objectNode = SCNNode(mdlObject: mdlAsset.object(at: 0))
objectNode.scale = SCNVector3(2, 2, 2)
objectNode.position = SCNVector3(0, 0, 0)
scene.rootNode.addChildNode(objectNode)
}
}
extension MDLMaterial {
func setTextureProperties(textures: [MDLMaterialSemantic:String]) -> Void {
for (key,value) in textures {
let url = URL(fileURLWithPath: "\(MZUtility.baseFilePath)/\(value)")
let property = MDLMaterialProperty(name:value, semantic: key, url: url)
self.setProperty(property)
}
}
}
解决方案
推荐阅读
- bokehjs - 测量散景中直方图之间的距离
- c - 如何在 centos8 中使用“dnf install”安装文件 libc.a
- javascript - 如何在 Next.JS 中使用 URL 查询创建条件逻辑?
- python - 如何在 Python 3 中执行 input() 方法时输入换行符?
- rust - 由于对 `.into_iter()` 的隐式调用,移动了对向量的可变引用,但显式调用 `.into_iter()` 有效
- python - 使用 Telebot ValueError 编写电报机器人时出错:check_hostname 需要 server_hostname
- javascript - 在javascript中每2秒更改一次url
- java - NIO2 CompletionHandler 的线程安全
- azure - 验证从 azure 静态 Web 应用程序发送到 byo 函数的令牌
- javascript - 从 jest 设置文件中检测测试文件路径