FRMSKI開発ブログ

AWS、iOS、AR/VRなど開発メモ

【ARKit】lightEstimateでカメラ画像の明るさを環境光に反映

f:id:frmski:20181004160717j:plain:w300
上画像のようにARKitでカメラ画像の明るさをライティングに反映する方法をご紹介します。

①SceneKitのライティングを作成

まずはライティング用ノードを作成してrootNodeに追加します。

var sceneLight: SCNLight!//シーンのライト

override func viewDidLoad()
{
 ...
 sceneLight = SCNLight()
    sceneLight.type = .omni //豆電球のように球状に光が広がるライト
    let lightNode = SCNNode()
    lightNode.light = sceneLight
    lightNode.position = SCNVector3(0,0,2)
    self.sceneView.scene.rootNode.addChildNode(lightNode) //ライティング用のノードをARSCNViewに追加

②ARWorldTrackingConfigurationでisLightEstimationEnabledをtrueに

isLightEstimationEnabledをtrueにすることで環境光に合わせてレンダリングすることができます。

let configuration = ARWorldTrackingConfiguration()
configuration.isLightEstimationEnabled = true
sceneView.session.run(configuration)

③rendererでライティング情報を反映

①で作成したSceneLightにlightEstimateの光量と色を反映させます。

func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
        guard let lightEstimate = self.sceneView.session.currentFrame?.lightEstimate else { return }
        
        let ambientLightEstimate = lightEstimate.ambientIntensity
        let ambientColorTemperature = lightEstimate.ambientColorTemperature
        
        sceneLight!.intensity = ambientLightEstimate //光量を反映
        sceneLight!.temperature = ambientColorTemperature //環境光の色
        
        if ambientLightEstimate < 100 { print("Lighting Is Too Dark") }
}

このように手軽に反映できます。素晴らしいですね。