Tracking and visualizing faces
At a glance
| Item | Summary |
|---|---|
| Purpose | Run ARFaceTrackingConfiguration (with as many tracked faces as the device supports) and render one of five SceneKit visualizations per face: transform axes, a textured mesh, an occluding 3D overlay, a video-textured mesh, or a blend-shape-driven character. |
| App architecture | A single-scene UIKit app. ViewController owns the ARSCNView, runs the session, and keeps one VirtualContentController per ARFaceAnchor. A tab bar selects a VirtualContentType, whose makeController() builds the matching controller. The view controller forwards SceneKit renderer callbacks to that controller. |
| Main patterns | Delegate or data-source callbacks (ARKit, SceneKit, and tab-bar delegates), Protocol-oriented abstraction (VirtualContentController), Factory (VirtualContentType.makeController()) |
| Project style | One app target. Root files hold the lifecycle delegates, the view controller, and utilities; Face Overlay Content/ holds the protocol, the factory enum, and the five content controllers; Resources/ holds Info.plist, models, and a shader modifier. |
| Execution model | UIKit lifecycle and delegate callbacks. renderer(_:didAdd:for:) defers content creation with DispatchQueue.main.async; the session-failure alert also hops to the main queue. No Swift concurrency appears. |
| State/event model | A dictionary [ARFaceAnchor: VirtualContentController] in the view controller, updated by renderer callbacks and by the selectedVirtualContent property observer. |
| Key frameworks/packages | Swift modules ARKit, SceneKit, UIKit, Foundation; no packages. |
Project structure
ARKitFaceExample.xcodeproj # 1 iOS app target
ARKitFaceExample/
├── AppDelegate.swift # @UIApplicationMain, support check, scene configuration
├── SceneDelegate.swift # UIWindowSceneDelegate (storyboard window)
├── ViewController.swift # session, per-anchor controllers, delegate forwarding
├── Utilities.swift # SCNMatrix4(affine), SCNReferenceNode(named:), colors
├── Face Overlay Content/
│ ├── VirtualContent.swift # VirtualContentType + VirtualContentController
│ ├── TransformVisualization.swift
│ ├── TexturedFace.swift
│ ├── VideoTexturedFace.swift # subclass of TexturedFace
│ ├── FaceOcclusionOverlay.swift
│ └── BlendShapeCharacter.swift
├── Base.lproj/Main.storyboard # ARSCNView, tab bar, unsupported-device scene
└── Resources/ # Info.plist, Models.scnassets, VideoTexturedFace.shader
Structure observations
- The project has one application target (
ARKitFaceExample.xcodeproj/project.pbxproj:155) for device families1,2(ARKitFaceExample.xcodeproj/project.pbxproj:380) with an iOS 15 deployment target (ARKitFaceExample.xcodeproj/project.pbxproj:371). ItsInfo.plistlives underResources/(ARKitFaceExample.xcodeproj/project.pbxproj:370). - The folder split matches the type split: everything that varies per visualization is in
Face Overlay Content/, and the view controller depends only on the protocol and the enum. - The storyboard’s tab items carry tags
0through4(ARKitFaceExample/Base.lproj/Main.storyboard:29,ARKitFaceExample/Base.lproj/Main.storyboard:32) that map toVirtualContentTyperaw values, and the tab bar’sdelegateoutlet targets the view controller (ARKitFaceExample/Base.lproj/Main.storyboard:35). - The shader modifier and SceneKit models are bundle resources (
ARKitFaceExample.xcodeproj/project.pbxproj:197,ARKitFaceExample.xcodeproj/project.pbxproj:198).Info.plistnamesSceneDelegateand theMainstoryboard for the default scene (ARKitFaceExample/Resources/Info.plist:38).
Overall architecture
flowchart LR
Tab["UITabBar"] -->|"UITabBarDelegate"| VC["ViewController"]
VC -->|"run ARFaceTrackingConfiguration"| Session["ARSession"]
View["ARSCNView"] -->|"ARSCNViewDelegate"| VC
VC -->|"makeController()"| Type["VirtualContentType"]
Type --> Ctrl["VirtualContentController"]
VC -->|"nodeFor / didUpdate"| Ctrl
Ctrl --> Impl["Transform / Textured / VideoTextured / Occlusion / BlendShape"]
Reference code
ARKitFaceExample/Face Overlay Content/VirtualContent.swift:11 — the enum is the factory, the protocol is the seam
enum VirtualContentType: Int {
case transforms, texture, geometry, videoTexture, blendShape
func makeController() -> VirtualContentController {
switch self {
case .transforms:
return TransformVisualization()
case .texture:
return TexturedFace()
case .geometry:
return FaceOcclusionOverlay()
case .videoTexture:
return VideoTexturedFace()
case .blendShape:
return BlendShapeCharacter()
}
}
}
/// For forwarding `ARSCNViewDelegate` messages to the object controlling the currently visible virtual content.
protocol VirtualContentController: ARSCNViewDelegate {
/// The root node for the virtual content.
var contentNode: SCNNode? { get set }
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode?
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor)
}Interpretation
Observed: ViewController is the only ARSCNViewDelegate set on the view (ARKitFaceExample/ViewController.swift:51). It never inspects which visualization is active. It asks the selected type for a new controller, asks that controller for a node, and forwards per-frame updates (ARKitFaceExample/ViewController.swift:149, ARKitFaceExample/ViewController.swift:164).
Inference: the protocol inherits from ARSCNViewDelegate and mirrors two of its methods, so each content controller looks like a small renderer delegate for one face. Adding a sixth visualization needs one new conformer, one enum case, and one tab item; ViewController would not change.
Ownership and state
classDiagram
ViewController o-- ARSCNView : IBOutlet sceneView
ViewController o-- UITabBar : weak IBOutlet tabBar
ViewController *-- VirtualContentController : one per ARFaceAnchor (dictionary)
ViewController --> VirtualContentType : selectedVirtualContent
VirtualContentController *-- SCNNode : contentNode
VideoTexturedFace --|> TexturedFace
Ownership evidence
ARKitFaceExample/ViewController.swift:21 — per-anchor controllers, rebuilt when the selection changes
var faceAnchorsAndContentControllers: [ARFaceAnchor: VirtualContentController] = [:]
var selectedVirtualContent: VirtualContentType! {
didSet {
guard oldValue != nil, oldValue != selectedVirtualContent
else { return }
// Remove existing content when switching types.
for contentController in faceAnchorsAndContentControllers.values {
contentController.contentNode?.removeFromParentNode()
}
// If there are anchors already (switching content), create new controllers and generate updated content.
// Otherwise, the content controller will place it in `renderer(_:didAdd:for:)`.
for anchor in faceAnchorsAndContentControllers.keys {
let contentController = selectedVirtualContent.makeController()
if let node = sceneView.node(for: anchor),
let contentNode = contentController.renderer(sceneView, nodeFor: anchor) {
node.addChildNode(contentNode)
faceAnchorsAndContentControllers[anchor] = contentController
}
}
}
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
| Storyboard | ARSCNView, UITabBar, unsupported-device scene |
Instantiated by Interface Builder (ARKitFaceExample/Base.lproj/Main.storyboard:52, ARKitFaceExample/Base.lproj/Main.storyboard:53, ARKitFaceExample/Base.lproj/Main.storyboard:63) |
— |
ViewController |
faceAnchorsAndContentControllers |
Stored dictionary; the only strong reference to each content controller (ARKitFaceExample/ViewController.swift:21) |
renderer(_:didAdd:for:) inserts; didRemove deletes; selectedVirtualContent replaces; resetTracking() clears |
ViewController |
selectedVirtualContent |
Stored implicitly unwrapped enum with a didSet observer (ARKitFaceExample/ViewController.swift:23) |
viewDidLoad() (initial tab) and tabBar(_:didSelect:) |
| Each content controller | contentNode |
Stored var required by the protocol; created in renderer(_:nodeFor:) |
The controller; ViewController removes it from its parent when switching |
FaceOcclusionOverlay |
occlusionNode |
Stored SCNNode! child of contentNode (ARKitFaceExample/Face Overlay Content/FaceOcclusionOverlay.swift:15) |
The controller |
BlendShapeCharacter |
originalJawY, lazy child-node references |
private (ARKitFaceExample/Face Overlay Content/BlendShapeCharacter.swift:17, ARKitFaceExample/Face Overlay Content/BlendShapeCharacter.swift:19) |
The controller |
ARSession |
Face anchors | ARKit; the configuration requests supportedNumberOfTrackedFaces (ARKitFaceExample/ViewController.swift:93) |
ARKit |
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution. A Sendable conformance alone does not prove thread-safe mutation.
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Delegate callbacks | ARSCNViewDelegate renderer methods |
didAdd, didUpdate, didRemove read and write faceAnchorsAndContentControllers. The source does not state which thread SceneKit uses for these callbacks. |
ARKitFaceExample/ViewController.swift:143, ARKitFaceExample/ViewController.swift:157, ARKitFaceExample/ViewController.swift:167 |
| Main-queue scheduling | DispatchQueue.main.async in didAdd |
Controller creation, node attachment, and the dictionary insert are submitted to the main queue. | ARKitFaceExample/ViewController.swift:148 |
| Main-queue scheduling | DispatchQueue.main.async in session(_:didFailWithError:) |
Presents the restart alert. | ARKitFaceExample/ViewController.swift:84 |
| Shared-state safety | None explicit | didUpdate and didRemove access the dictionary directly in the callback, while didAdd inserts on the main queue and the tab-bar observer mutates it from UI code. No lock or serial queue protects it. |
ARKitFaceExample/ViewController.swift:159, ARKitFaceExample/ViewController.swift:170 |
No Swift concurrency, task, actor, or Combine appears. The project sets no default actor isolation.
Reference code
ARKitFaceExample/ViewController.swift:143 — creation is deferred to the main queue; the empty-node check prevents duplicate content
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
guard let faceAnchor = anchor as? ARFaceAnchor else { return }
// If this is the first time with this anchor, get the controller to create content.
// Otherwise (switching content), will change content when setting `selectedVirtualContent`.
DispatchQueue.main.async {
let contentController = self.selectedVirtualContent.makeController()
if node.childNodes.isEmpty, let contentNode = contentController.renderer(renderer, nodeFor: faceAnchor) {
node.addChildNode(contentNode)
self.faceAnchorsAndContentControllers[faceAnchor] = contentController
}
}
}Inference: hopping to the main queue serializes didAdd with the tab-bar observer, which also runs on the main thread, so a selection change cannot interleave with first-time content creation. The didUpdate/didRemove paths do not hop, so the dictionary is still touched from the callback context there.
State propagation, frameworks, and dependencies
Evidence limit: an import proves a source-level compilation dependency at the cited line. It does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.
| Category | Mechanism or module | Verified role | Evidence |
|---|---|---|---|
| Event delivery | UITabBarDelegate |
Tab selection sets selectedVirtualContent from the item’s tag |
ARKitFaceExample/ViewController.swift:134 |
| Event delivery | ARSCNViewDelegate, ARSessionDelegate |
Anchor lifecycle and session failure | ARKitFaceExample/ViewController.swift:141, ARKitFaceExample/ViewController.swift:73 |
| State propagation | Property observer | selectedVirtualContent.didSet swaps every face’s content |
ARKitFaceExample/ViewController.swift:24 |
| State propagation | Forwarding | ViewController passes didUpdate to the anchor’s controller with that controller’s contentNode |
ARKitFaceExample/ViewController.swift:164 |
| Rendering input | Blend shapes, face geometry, eye transforms | Controllers read ARFaceAnchor data each update |
ARKitFaceExample/Face Overlay Content/BlendShapeCharacter.swift:46, ARKitFaceExample/Face Overlay Content/TexturedFace.swift:38 |
| Rendering input | ARFrame.displayTransform + shader modifier |
VideoTexturedFace updates a displayTransform value each frame; on iOS 27 it uses viewRotationAngle, otherwise portrait |
ARKitFaceExample/Face Overlay Content/VideoTexturedFace.swift:49, ARKitFaceExample/Face Overlay Content/VideoTexturedFace.swift:57 |
| Swift module import | ARKit, SceneKit, UIKit |
Controller dependencies | ARKitFaceExample/ViewController.swift:8, ARKitFaceExample/ViewController.swift:9, ARKitFaceExample/ViewController.swift:10 |
| Swift module import | Foundation |
Imported by BlendShapeCharacter |
ARKitFaceExample/Face Overlay Content/BlendShapeCharacter.swift:8 |
| Privacy declaration | NSCameraUsageDescription |
Camera access string | ARKitFaceExample/Resources/Info.plist:25 |
Platform boundary
The view controller allows all orientations only when #available(iOS 27.0, *), and otherwise portrait, because the video texture’s rotation-aware transform is only used on iOS 27 (ARKitFaceExample/ViewController.swift:125). The project’s deployment target is iOS 15 (ARKitFaceExample.xcodeproj/project.pbxproj:371), so both branches ship.
Class and protocol design
classDiagram
class ARSCNViewDelegate {
<<ARKit protocol>>
}
class VirtualContentController {
<<protocol>>
contentNode
renderer(_:nodeFor:)
renderer(_:didUpdate:for:)
}
VirtualContentController --|> ARSCNViewDelegate
TransformVisualization ..|> VirtualContentController
TexturedFace ..|> VirtualContentController
FaceOcclusionOverlay ..|> VirtualContentController
BlendShapeCharacter ..|> VirtualContentController
VideoTexturedFace --|> TexturedFace
ViewController --> VirtualContentController
Reference code
ARKitFaceExample/Face Overlay Content/VideoTexturedFace.swift:38 — the subclass reuses mesh updates and adds the per-frame display transform
override func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
super.renderer(renderer, didUpdate: node, for: anchor)
guard let sceneView = renderer as? ARSCNView,
let frame = sceneView.session.currentFrame,
let faceGeometry = node.geometry as? ARSCNFaceGeometry
else { return }
// Pass view-appropriate image transform to the shader modifier so
// that the mapped video lines up correctly with the background video.
let affineTransform: CGAffineTransform
if #available(iOS 27.0, *) {
// The view rotation angle keeps the video level with the horizon as the device rotates.
affineTransform = frame.displayTransform(viewRotationAngle: sceneView.session.viewRotationAngle ?? 90,
viewportSize: sceneView.bounds.size)
} else {
affineTransform = frame.displayTransform(for: .portrait, viewportSize: sceneView.bounds.size)
}
let transform = SCNMatrix4(affineTransform)
faceGeometry.setValue(SCNMatrix4Invert(transform), forKey: "displayTransform")
}| Type | Responsibility | Depends on |
|---|---|---|
AppDelegate |
@UIApplicationMain; face-tracking support check; scene configuration |
ARFaceTrackingConfiguration, UIStoryboard |
SceneDelegate |
Holds the scene window; callbacks are empty apart from a type check | UIKit |
ViewController |
Session lifecycle, per-anchor controller map, delegate forwarding, error alert, orientation policy | ARSCNView, VirtualContentType, VirtualContentController |
VirtualContentType |
Closed list of visualizations; builds a controller per case | The five conformers |
VirtualContentController |
Per-face content seam: create a node, update it | ARSCNViewDelegate |
TransformVisualization |
Axis models at the face origin and eye transforms | SCNReferenceNode(named:) |
TexturedFace / VideoTexturedFace |
ARSCNFaceGeometry with a texture, or with the camera image through a shader modifier |
ARSCNFaceGeometry, VideoTexturedFace.shader |
FaceOcclusionOverlay |
Depth-only face mesh rendered first, plus a “glasses” model | colorBufferWriteMask = [], renderingOrder = -1 |
BlendShapeCharacter |
Robot head driven by eyeBlinkLeft/Right and jawOpen |
ARFaceAnchor.blendShapes |
VideoTexturedFace is the only class inheritance between content controllers; the other four conform to the protocol directly as NSObject subclasses (ARKitFaceExample/Face Overlay Content/TexturedFace.swift:11).
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
BlendShapeCharacter.originalJawY, jawNode, eyeLeftNode, eyeRightNode, jawHeight |
private / private lazy |
Only the character controller can read or set them (ARKitFaceExample/Face Overlay Content/BlendShapeCharacter.swift:17, ARKitFaceExample/Face Overlay Content/BlendShapeCharacter.swift:19, ARKitFaceExample/Face Overlay Content/BlendShapeCharacter.swift:23). |
Inference: rig details stay inside the controller that understands the model. |
VirtualContentController.contentNode |
protocol requirement { get set } |
Every conformer exposes a settable root node; ViewController reads it to remove content (ARKitFaceExample/Face Overlay Content/VirtualContent.swift:33). |
Inference: the owner needs a handle for teardown without knowing the concrete type. |
faceAnchorsAndContentControllers, selectedVirtualContent |
implicitly internal |
Reachable from other module code; only ViewController uses them (ARKitFaceExample/ViewController.swift:21, ARKitFaceExample/ViewController.swift:23). |
— |
sceneView, tabBar outlets |
implicitly internal (tabBar is weak) |
Connected by Interface Builder (ARKitFaceExample/ViewController.swift:16, ARKitFaceExample/ViewController.swift:17). |
— |
TransformVisualization.rightEyeNode, leftEyeNode; FaceOcclusionOverlay.occlusionNode |
implicitly internal |
Not restricted, although only their owners use them (ARKitFaceExample/Face Overlay Content/TransformVisualization.swift:16, ARKitFaceExample/Face Overlay Content/FaceOcclusionOverlay.swift:15). |
— |
Nothing is public or open.
Reference code
ARKitFaceExample/Face Overlay Content/BlendShapeCharacter.swift:13 — private lazy references into the loaded model
class BlendShapeCharacter: NSObject, VirtualContentController {
var contentNode: SCNNode?
private var originalJawY: Float = 0
private lazy var jawNode = contentNode!.childNode(withName: "jaw", recursively: true)!
private lazy var eyeLeftNode = contentNode!.childNode(withName: "eyeLeft", recursively: true)!
private lazy var eyeRightNode = contentNode!.childNode(withName: "eyeRight", recursively: true)!
// ...
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Device support gate | AppDelegate.application(_:willFinishLaunchingWithOptions:) and ViewController.resetTracking() |
Observed: the app delegate tries to swap in the unsupportedDeviceMessage scene through window?.rootViewController (ARKitFaceExample/AppDelegate.swift:26); resetTracking() returns without running when unsupported (ARKitFaceExample/ViewController.swift:90). |
| Session configuration | ViewController.resetTracking() |
Observed: maximum supported faces and light estimation; clears the controller map (ARKitFaceExample/ViewController.swift:93, ARKitFaceExample/ViewController.swift:98). |
| Content switching | selectedVirtualContent.didSet |
Observed: removes old nodes and builds new controllers for existing anchors. |
| Visualization-specific rendering | Each VirtualContentController conformer |
Observed: geometry, materials, shader modifiers, and blend-shape mapping live in the conformer files. |
| Face-mesh updates | TexturedFace.renderer(_:didUpdate:for:) and FaceOcclusionOverlay |
Observed: faceGeometry.update(from: faceAnchor.geometry) (ARKitFaceExample/Face Overlay Content/TexturedFace.swift:38, ARKitFaceExample/Face Overlay Content/FaceOcclusionOverlay.swift:54). |
| Model loading helper | SCNReferenceNode(named:loadImmediately:) in Utilities.swift |
Observed: one place resolves Models.scnassets paths (ARKitFaceExample/Utilities.swift:38). |
Observed: no source assigns AppDelegate.window; with the scene manifest, the window belongs to the scene (ARKitFaceExample/SceneDelegate.swift:12). Inference: the app-delegate fallback’s optional chain therefore has no window to update, and on an unsupported device the visible effect comes from resetTracking() declining to run the session.
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Delegate or data-source callbacks | ARKitFaceExample/ViewController.swift:51, ARKitFaceExample/ViewController.swift:52, ARKitFaceExample/ViewController.swift:133, ARKitFaceExample/ViewController.swift:141 |
ARKit, SceneKit, and UIKit push anchor, session, and selection events to the view controller, which forwards renderer events onward. |
| Protocol-oriented abstraction | ARKitFaceExample/Face Overlay Content/VirtualContent.swift:31, consumed as [ARFaceAnchor: VirtualContentController] (ARKitFaceExample/ViewController.swift:21) |
Five interchangeable visualizations behind one interface; the view controller never names a concrete type. |
| Factory | ARKitFaceExample/Face Overlay Content/VirtualContent.swift:14 (makeController()) |
Maps a UI selection to a new controller instance; a fresh controller per face keeps per-face state (for example, random colors, jaw position) separate. |
Naming conventions
- Types: noun phrases for what is drawn (
TexturedFace,VideoTexturedFace,FaceOcclusionOverlay,BlendShapeCharacter,TransformVisualization);…Controllerfor the protocol role;…Typefor the selection enum. - Factory method uses the
make…prefix (makeController()). - The dictionary name states both key and value (
faceAnchorsAndContentControllers). - Enum cases are short lower camel case (
transforms,texture,geometry,videoTexture,blendShape); their raw values are the tab tags. - Files: one primary type per file in
Face Overlay Content/;VirtualContent.swiftpairs the enum and the protocol it returns.
Architecture takeaways
- When one screen can show several interchangeable renderings, put a small protocol between the owner and the renderings, and let an enum build the concrete type. The owner then stays unchanged as variants are added.
- Keep per-entity state in per-entity objects: one controller per
ARFaceAnchor, stored in a dictionary keyed by the anchor, removed when ARKit removes the anchor. - Let an
ARSCNViewDelegateowner forward callbacks to sub-delegates instead of setting multiple delegates; a protocol that inherits fromARSCNViewDelegatemakes the forwarding read naturally. - Gate a rendering capability on OS availability in both places it matters: the transform calculation and the supported orientations.
- When adopting the scene lifecycle, move window-dependent launch logic to the scene delegate; app-delegate
windowcode no longer has a window to act on.
Source map
| Source file | Relevant symbols |
|---|---|
ARKitFaceExample/AppDelegate.swift |
AppDelegate, application(_:willFinishLaunchingWithOptions:), application(_:configurationForConnecting:options:) |
ARKitFaceExample/SceneDelegate.swift |
SceneDelegate, window |
ARKitFaceExample/ViewController.swift |
ViewController, faceAnchorsAndContentControllers, selectedVirtualContent, resetTracking(), delegate extensions, supportedInterfaceOrientations |
ARKitFaceExample/Face Overlay Content/VirtualContent.swift |
VirtualContentType, makeController(), VirtualContentController |
ARKitFaceExample/Face Overlay Content/TexturedFace.swift |
TexturedFace |
ARKitFaceExample/Face Overlay Content/VideoTexturedFace.swift |
VideoTexturedFace |
ARKitFaceExample/Face Overlay Content/FaceOcclusionOverlay.swift |
FaceOcclusionOverlay, occlusionNode |
ARKitFaceExample/Face Overlay Content/BlendShapeCharacter.swift |
BlendShapeCharacter |
ARKitFaceExample/Face Overlay Content/TransformVisualization.swift |
TransformVisualization |
ARKitFaceExample/Utilities.swift |
SCNReferenceNode(named:loadImmediately:) |
ARKitFaceExample/Base.lproj/Main.storyboard |
Tab items and tags, outlets, unsupported-device scene |
ARKitFaceExample/Resources/Info.plist |
Scene manifest, NSCameraUsageDescription |
ARKitFaceExample.xcodeproj/project.pbxproj |
Target, deployment target, resources |