How do you convert Wavefront OBJ file to an SCNNode with Model I/O
Asked Answered
E

1

5

I've imported a Wavefront OBJ file from a URL and now I'd like to insert it into my scene (SceneKit) on my iOS 9 app (in Swift). What I've done so far is:

let asset = MDLAsset(URL: localFileUrl)
print("count = \(asset.count)")  // 1

Any help converting this to a SCNNode would be appreciated. According to to Apple's docs:

Model I/O can share data buffers with the MetalKit, GLKit, and SceneKit frameworks to help you load, process, and render 3D assets efficiently.

But I'm not sure how to get buffer from an MDLAsset into a SCNNode.

Eucharis answered 8/1, 2016 at 1:10 Comment(0)
E
11

Turns out this quite easy as many of the ModelIO classes already bridge. I was doing import ModelIO which gave me access to all the ModelIO classes and likewise import SceneKit which gave me the SceneKit classes, but, I was missing import SceneKit.ModelIO to bring in the SceneKit support for ModelIO.

let url = NSURL(string: "url-to-your-obj-here")
let asset = MDLAsset(URL: url!)
let object = asset.objectAtIndex(0)
let node = SCNNode(MDLObject: object)

Easy as that...

Eucharis answered 11/1, 2016 at 3:47 Comment(5)
note that +[SCNScene sceneWithURL:options:error:] will also work.Needlepoint
Also note that there's some cost to parsing/importing OBJ. If this is an asset that you're shipping in/with your app, consider converting it to .scn in Xcode (or with your own tools that run on the Mac, using Model I/O) first.Betsey
I see the SCNNode initializer in the documentation, with its signature changed to SCNNode(mdlObject:). But.. Xcode 9.4.1 claims this initializer does not exist, and right-command-clicking on SCNNode shows a class definition that does not have that initializer. Where is it?Linalinacre
Similarly, Xcode denies that SCNScene(mdlObject:) exists.Linalinacre
Thanks for the solution my problem is i am working with server url to download it on local memory and then load it on camera with your solution and its working fine but problem is i am getting .obj 3d object with grey colour no colour my question is how could i load assets as well?Euphrates

© 2022 - 2024 — McMap. All rights reserved.