Using a MTLTexture as the environment map of a SCNScene

Lighting SCN Environment with an MTK texture

Using Xcode 13.3.1 on macOS 12.3.1 for iOS 15.4 app.

The trick is, the environment lighting requires a cube texture, not a flat image.

  • Create 6 square images for MetalKit cube texture

enter image description here

  • in Xcode Assets folder create Cube Texture Set

enter image description here

  • place textures to their corresponding slots

enter image description here

  • mirror images horizontally and vertically, if needed

enter image description here

Paste the code:

import ARKit
import MetalKit

class ViewController: UIViewController {

    @IBOutlet var sceneView: ARSCNView!
    
    override func viewDidLoad() {
        super.viewDidLoad()    
        let scene = SCNScene()
        
        let imageName = "CubeTextureSet"
        let textureLoader = MTKTextureLoader(device: sceneView.device!)

        let environmentMap = try! textureLoader.newTexture(name: imageName, 
                                                    scaleFactor: 2, 
                                                         bundle: .main, 
                                                        options: nil)
        
        let daeScene = SCNScene(named: "art.scnassets/testCube.dae")!

        let model = daeScene.rootNode.childNode(withName: "polyCube", 
                                             recursively: true)!
        
        scene.lightingEnvironment.contents = environmentMap
        scene.lightingEnvironment.intensity = 2.5
        scene.background.contents = environmentMap

        sceneView.scene = scene
        sceneView.allowsCameraControl = true
        scene.rootNode.addChildNode(model)
    }
}

Apply metallic materials to models. Now MTL environment lighting is On.

enter image description here

If you need a procedural skybox texture – use MDLSkyCubeTexture class.

Also, this post may be useful for you.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)