//
//  FaceTrackingViewController.swift
//  HeiseARKit3
//
//  Created by Gero Gerber on 13.03.20.
//  Copyright © 2020 Gero Gerber. All rights reserved.
//

import ARKit
import SceneKit
import UIKit

class FaceTrackingViewController: UIViewController {

	@IBOutlet var arView: ARSCNView!
	
	var availableColors = [UIColor.red, UIColor.green, UIColor.blue]
	
	override func viewDidAppear(_ animated: Bool) {
		super.viewDidAppear(animated)
		
		guard ARFaceTrackingConfiguration.isSupported else {
            fatalError("ARFaceTrackingConfiguration is not supported on this device!")
        }
		
		let config = ARFaceTrackingConfiguration()
		config.maximumNumberOfTrackedFaces = ARFaceTrackingConfiguration.supportedNumberOfTrackedFaces
		arView.session.run(config, options: .resetTracking)
		arView.delegate = self
	}
}

extension FaceTrackingViewController: ARSCNViewDelegate {
	func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
		guard anchor is ARFaceAnchor else { return nil }
		guard let device = arView.device else { return nil }
		let faceGeometry = ARSCNFaceGeometry(device: device)
		let node = SCNNode(geometry: faceGeometry)
		node.geometry?.firstMaterial?.fillMode = .lines
		node.geometry?.firstMaterial?.diffuse.contents = availableColors.remove(at: 0)
		return node
	}
	
	func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
		guard let fa = anchor as? ARFaceAnchor else { return }
		guard let faceGeometry = node.geometry as? ARSCNFaceGeometry else { return }
		faceGeometry.update(from: fa.geometry)
	}
}
