模型I / O导入资产

时间:2018-03-30 03:35:40

标签: swift3 gpu .obj

我尝试使用模型I / O作为为我的iOS应用渲染导入的3D模型的更快捷方式。我编写了一些代码导入并显示了我用.obj文件格式制作的3D模型。出于某种原因,当我运行我的应用程序时,只出现黑屏。这是我的代码:

import UIKit
import ModelIO
import SceneKit
import SceneKit.ModelIO

class ViewController: UIViewController {


var sceneView: SCNView {
    return self.view as! SCNView
}

override func viewDidLoad() {
     // Do any additional setup after loading the view, typically from                a nib.
    guard let url = Bundle.main.url(forResource: "Digestive_System",      withExtension: "obj") else {
        fatalError("Failed to find model")

    }

    //Load Object
    let asset = MDLAsset(url:url)
    guard let object = asset.object(at: 0) as? MDLMesh else {
        fatalError("failed to get mesh from asset")
    }

    // Wrap Model I/O object in SceneKit object
    let scene = SCNScene()
    let node = SCNNode(mdlObject: object)
    scene.rootNode.addChildNode(node)


    //Display Scene

    sceneView.autoenablesDefaultLighting = true
    sceneView.allowsCameraControl = true
    sceneView.scene = scene
    sceneView.backgroundColor = UIColor.black








     super.viewDidLoad()
     }

旁注:我的模型位于应用程序的主文件夹中。

感谢您的帮助! NOA

1 个答案:

答案 0 :(得分:0)

我已经使用Model I / O渲染了.Obj模型:

  1. 从捆绑包加载模型

    NSURL *url = [[NSBundle mainBundle] URLForResource:@"modelName" withExtension:@"obj"];
    MDLAsset *asset = [[MDLAsset alloc] initWithURL:url];
    MDLMesh *meshObject = (MDLMesh *)[asset objectAtIndex:0];
    
  2. 将材料应用于模型

    MDLScatteringFunction *scattering = [MDLScatteringFunction new];
    MDLMaterial *mdMaterial = [[MDLMaterial alloc] initWithName:@"material" 
    scatteringFunction:scattering];
    
    NSURL *baseMaterialURL = [[NSBundle mainBundle] 
    URLForResource:@"Image_Base_Color" withExtension:@"png"];
    MDLMaterialProperty *baseColor = [MDLMaterialProperty new];
    [baseColor setType:MDLMaterialPropertyTypeTexture];
    [baseColor setSemantic:MDLMaterialSemanticBaseColor];
    [baseColour setURLValue:baseMaterialURL];
    [material setProperty:baseColor];
    
     for(MDLSubmesh *subMesh in meshObject.submeshes)
     {
        sub.material = material;
     }
    
  3. 将模型添加到场景

     SCNNode *baseModelNode = [SCNNode nodeWithMDLObject:object];
     [self.sceneView.scene rootNode] addChildNode:self.baseModelNode];
    

您可以根据需要设置比例和位置。