Combining user face-tracking and world tracking
At a glance
| Item | Summary |
|---|---|
| Purpose | Track the user’s face in an app that displays an AR experience with the rear camera. |
| App architecture | A storyboard UIKit app with scene-based lifecycle. One ViewController runs a RealityKit ARView with a world-tracking configuration that also tracks the user’s face. A RobotHead entity attached to a camera anchor mirrors the face’s blend shapes. A tap re-anchors the head in the world and freezes it. |
| Main patterns | Delegate or data-source callbacks (ARSessionDelegate, ARCoachingOverlayViewDelegate) |
| Project style | One iOS target. The controller (ViewController.swift), its coaching extension, a custom RobotHead entity, a MessageLabel view, and Utilities.swift extensions. The model ships as robotHead.reality, with authoring sources in Assets/. |
| Execution model | Per-frame logic runs in ARSessionDelegate callbacks with no queue hop. MessageLabel posts its text changes to DispatchQueue.main and hides itself with asyncAfter. The error alert is presented through DispatchQueue.main.async. No Swift concurrency. |
| State/event model | Session delegate callbacks drive a headPreview slot: nil means a new head is needed, and non-nil means a live head is following the face. A didSet on RobotHead.appearance turns state into colors. |
| Key frameworks/packages | ARKit, RealityKit, UIKit. No package dependencies. |
Project structure
Source bundle/
├── FaceAndWorldTrackingExample/
│ ├── AppDelegate.swift face-tracking support check, scene configuration
│ ├── SceneDelegate.swift window holder; storyboard comes from Info.plist
│ ├── ViewController.swift session config, per-frame head logic, tap to anchor
│ ├── ViewController+CoachingOverlay.swift
│ ├── RobotHead.swift Entity subclass: load, appearance, blend-shape update
│ ├── MessageLabel.swift self-hiding instruction label
│ ├── Utilities.swift Entity.color, simd_float4x4.eulerAngles
│ ├── robotHead.reality bundled model
│ └── Base.lproj/Main.storyboard AR scene plus "unsupportedDeviceMessage" scene
├── Assets/ RobotHead.rcproject, .scn, .usdz sources
└── FaceAndWorldTrackingExample.xcodeproj/
Structure observations
- The window and root controller come from the Info.plist scene manifest (
FaceAndWorldTrackingExample/Info.plist:37).SceneDelegateholds the scene’swindowand only checks for aUIWindowScene(FaceAndWorldTrackingExample/SceneDelegate.swift:15). RobotHeadis a domain entity. It loads its own model, finds its named parts, and exposesappearance,update(with:), and a proximity query. The controller never touches the head’s sub-entities.
Device-support boundary
AppDelegate tries to swap in the storyboard’s unsupportedDeviceMessage controller through its own window property (FaceAndWorldTrackingExample/AppDelegate.swift:24). Nothing in the source assigns AppDelegate.window; the scene manifest gives the window to SceneDelegate. Inference: under scene-based lifecycle that assignment has no effect, and an unsupported device reaches the fatalError guard in ViewController.viewDidLoad (FaceAndWorldTrackingExample/ViewController.swift:36).
Overall architecture
flowchart LR
Plist["Info.plist scene manifest"] --> Scene["SceneDelegate"]
Scene --> VC["ViewController"]
VC --> ARView["ARView"]
ARView --> Session["ARSession (world + user face)"]
Session -->|ARSessionDelegate| VC
VC --> Head["RobotHead (camera anchor)"]
VC --> Label["MessageLabel"]
VC --> Coaching["ARCoachingOverlayView"]
Reference code
FaceAndWorldTrackingExample/ViewController.swift:54 — a custom world-tracking configuration with user face tracking turned on
override func viewDidLoad() {
super.viewDidLoad()
guard ARWorldTrackingConfiguration.supportsUserFaceTracking else {
fatalError("This sample code requires iOS 13 / iPad OS 13, and an iOS device with a front TrueDepth camera. Note: 2020 iPads do not support user face-tracking while world tracking.")
}
arView.session.delegate = self
// We want to run a custom configuration.
arView.automaticallyConfigureSession = false
setupCoachingOverlay()
// ...
configuration.environmentTexturing = .automatic
// Enable tracking the user's face during the world tracking session.
configuration.userFaceTrackingEnabled = true
// ...
arView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:))))
}Interpretation
ViewController owns the configuration as a stored let and runs it in viewWillAppear (FaceAndWorldTrackingExample/ViewController.swift:64). Session callbacks are its only input besides the tap and the restart button. Rear-camera world tracking places content. The front camera supplies ARFaceAnchors, which only drive the head’s expression and mirrored pose. Head rendering decisions sit in RobotHead. Inference: the controller acts as a per-frame state machine over one optional slot.
Ownership and state
classDiagram
ViewController o-- ARView : IBOutlet arView
ViewController o-- MessageLabel : weak IBOutlet
ViewController *-- ARCoachingOverlayView : let coachingOverlay
ViewController *-- ARWorldTrackingConfiguration : let configuration
ViewController o-- RobotHead : var headPreview
AnchorEntity *-- RobotHead : child
ARView *-- AnchorEntity : scene.anchors
Ownership evidence
FaceAndWorldTrackingExample/ViewController.swift:23 — the controller stores its configuration, its overlay, and a non-owning slot for the live head
class ViewController: UIViewController, ARSessionDelegate {
// MARK: - Properties
@IBOutlet var arView: ARView!
@IBOutlet weak var messageLabel: MessageLabel!
@IBOutlet weak var restartButton: UIButton!
let coachingOverlay = ARCoachingOverlayView()
let configuration = ARWorldTrackingConfiguration()
var headPreview: RobotHead?
// ...
}FaceAndWorldTrackingExample/ViewController.swift:157 — each new head gets a fresh camera anchor, and the scene keeps both
private func addHeadPreview() {
// ...
let camera = AnchorEntity(.camera)
arView.scene.addAnchor(camera)
// Attach a robot head to the camera anchor.
let robotHead = RobotHead()
camera.addChild(robotHead)
// Move the head behind the camera to keep it hidden until the user's face is first tracked.
robotHead.position.z = 1.0
headPreview = robotHead
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
ViewController |
ARWorldTrackingConfiguration |
Created as a let; run on appear and on reset |
ViewController |
ViewController |
headPreview |
A reference to the head that currently follows the face. It is cleared on tap and on reset, but the scene keeps the entity | ViewController (handleTap, resetTracking, addHeadPreview) |
ARView.scene |
Camera and world AnchorEntitys with their RobotHead children |
Keeps every frozen head until resetTracking() removes all anchors (FaceAndWorldTrackingExample/ViewController.swift:88) |
ViewController |
RobotHead |
Loaded model, cached part entities, original part positions | Loads robotHead in init and looks up parts lazily by name (FaceAndWorldTrackingExample/RobotHead.swift:51) |
RobotHead only (private) |
MessageLabel |
tag, ignoreMessages |
Uses tag as a generation counter for auto-hide; the coaching extension toggles ignoreMessages |
MessageLabel, coaching extension |
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Delegate queue | No delegateQueue assignment |
session(_:didUpdate:) for frames and for anchors mutates entities, headPreview, and view state directly. The source never sets a delegate queue. Inference: it relies on ARKit’s default main-queue delivery. |
FaceAndWorldTrackingExample/ViewController.swift:164 |
| Main-queue scheduling | DispatchQueue.main.async |
MessageLabel.displayMessage posts its show and hide text changes to the main queue. |
FaceAndWorldTrackingExample/MessageLabel.swift:30 |
| Delayed scheduling | DispatchQueue.main.asyncAfter + tag generation |
Hides the label after duration unless a newer message has incremented tag. |
FaceAndWorldTrackingExample/MessageLabel.swift:39 |
| Shared state | tag read and written on the caller’s queue |
tag is incremented synchronously in the caller’s context and compared in the delayed main-queue block. No lock is present. Inference: this is consistent only if callers are on the main queue. |
FaceAndWorldTrackingExample/MessageLabel.swift:37 |
| Main-queue scheduling | DispatchQueue.main.async |
Session failure presents the restart alert on the main queue. | FaceAndWorldTrackingExample/ViewController.swift:106 |
Reference code
FaceAndWorldTrackingExample/MessageLabel.swift:39 — a generation counter cancels stale delayed hides without storing work items
func displayMessage(_ text: String, duration: TimeInterval = 3.0) {
guard !ignoreMessages else { return }
guard !text.isEmpty else {
DispatchQueue.main.async {
self.isHidden = true
self.text = ""
}
return
}
DispatchQueue.main.async {
self.isHidden = false
self.text = text
}
// Use tag to tell if the label has been updated.
let tag = self.tag + 1
self.tag = tag
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
// Do not hide if showMessage is called again before this block kicks in.
if self.tag == tag {
self.isHidden = true
}
}
}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 |
|---|---|---|---|
| State propagation | ARSessionDelegate (frame) |
Creates a head when none exists and tracking is normal, enables it only while coaching is inactive, and updates its appearance. | FaceAndWorldTrackingExample/ViewController.swift:164 |
| State propagation | ARSessionDelegate (anchors) |
Forwards every ARFaceAnchor to headPreview?.update(with:). |
FaceAndWorldTrackingExample/ViewController.swift:179 |
| State propagation | Property observer | RobotHead.appearance didSet recolors the parts for tracked, notTracked, intersecting, and anchored. |
FaceAndWorldTrackingExample/RobotHead.swift:71 |
| State propagation | ARCoachingOverlayViewDelegate |
Mutes the label and hides the restart button during coaching, and resets on request. | FaceAndWorldTrackingExample/ViewController+CoachingOverlay.swift:11 |
| Framework import | RealityKit |
ARView, Entity/HasModel, AnchorEntity, re-anchoring. |
FaceAndWorldTrackingExample/RobotHead.swift:8 |
| Framework import | ARKit |
ARWorldTrackingConfiguration.userFaceTrackingEnabled, ARFaceAnchor blend shapes. |
FaceAndWorldTrackingExample/ViewController.swift:10 |
| Framework import | UIKit |
Controller, label, coaching-overlay layout. | FaceAndWorldTrackingExample/ViewController.swift:8 |
Class and protocol design
classDiagram
class Entity
class HasModel {
<<protocol>>
}
RobotHead --|> Entity
RobotHead ..|> HasModel
ViewController --> RobotHead : appearance, update(with:)
ViewController --> MessageLabel : displayMessage
Reference code
FaceAndWorldTrackingExample/RobotHead.swift:107 — the entity turns a face anchor into its own part transforms
class RobotHead: Entity, HasModel {
// ...
func update(with faceAnchor: ARFaceAnchor) {
// Update eyes and jaw transforms based on blend shapes.
let blendShapes = faceAnchor.blendShapes
guard let eyeBlinkLeft = blendShapes[.eyeBlinkLeft] as? Float,
let eyeBlinkRight = blendShapes[.eyeBlinkRight] as? Float,
let eyeBrowLeft = blendShapes[.browOuterUpLeft] as? Float,
let eyeBrowRight = blendShapes[.browOuterUpRight] as? Float,
let jawOpen = blendShapes[.jawOpen] as? Float,
let upperLip = blendShapes[.mouthUpperUpLeft] as? Float,
let tongueOut = blendShapes[.tongueOut] as? Float
else { return }
// ...
}
// ...
}| Type | Responsibility | Depends on |
|---|---|---|
ViewController |
Configuration, session callbacks, head lifecycle, tap to anchor, reset, error alert | ARView, RobotHead, MessageLabel |
RobotHead |
Model loading, appearance coloring, blend-shape animation, mirrored pose, proximity to anchored heads | RealityKit, ARFaceAnchor |
RobotHead.Appearance |
Closed set of visual states | — |
ViewController.Instruction |
Instruction strings as String raw values |
— |
MessageLabel |
Inset label that hides itself after a timeout | UIKit |
Entity.color / simd_float4x4.eulerAngles |
Material tint access and rotation decomposition | RealityKit, simd |
No local protocol is declared. RobotHead subclasses Entity and adopts RealityKit’s HasModel.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
RobotHead colors, original positions, part entities (FaceAndWorldTrackingExample/RobotHead.swift:14) |
private / private lazy |
Callers cannot reach the model’s sub-entities or palette. | Inference: the head’s internal structure stays an implementation detail behind appearance and update(with:). |
RobotHead.appearance, update(with:), isTooCloseToAnchoredHeads(in:) |
implicit internal |
The controller’s only handles on the head. | Inference: a narrow surface for a domain entity. |
ViewController.displayErrorMessage, showInstruction, updateHeadPreviewAppearance, addHeadPreview (FaceAndWorldTrackingExample/ViewController.swift:93) |
private |
Callable only within the controller’s own declaration. | Inference: per-frame steps are not part of the controller’s API. |
ViewController.coachingOverlay, messageLabel, restartButton, resetTracking() |
implicit internal |
Used by ViewController+CoachingOverlay.swift, a separate file. |
Inference: private would block the cross-file extension. |
Reference code
FaceAndWorldTrackingExample/RobotHead.swift:28 — parts are resolved lazily by name and kept private
class RobotHead: Entity, HasModel {
// ...
private lazy var eyeLeftEntity = findEntity(named: "eyeLeft")!
private lazy var eyeRightEntity = findEntity(named: "eyeRight")!
private lazy var eyebrowLeftEntity = findEntity(named: "eyebrowLeft")!
private lazy var eyebrowRightEntity = findEntity(named: "eyebrowRight")!
private lazy var jawEntity = findEntity(named: "jaw")!
private lazy var upperLipEntity = findEntity(named: "upperLip")!
private lazy var headEntity = findEntity(named: "head")!
private lazy var tongueEntity = findEntity(named: "tongue")!
private lazy var mouthEntity = findEntity(named: "mouth")!
// ...
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Session configuration and reset | ViewController |
One stored configuration is reused for both the first run and resets. |
| Head lifecycle (create, follow, freeze) | ViewController.session(_:didUpdate:), handleTap |
The optional headPreview slot encodes which phase the head is in. |
| Freeze-in-place | handleTap (FaceAndWorldTrackingExample/ViewController.swift:74) |
Re-anchors the camera anchor to .world(transform:) at the head’s current world transform. |
| Expression mirroring and pose | RobotHead.update(with:) |
Blend shapes and the camera-relative face transform map to part offsets and a mirrored rotation. |
| Overlap warning | RobotHead.isTooCloseToAnchoredHeads(in:) (FaceAndWorldTrackingExample/RobotHead.swift:153) |
Compares the head’s world position with non-camera anchors in the scene. |
| Instruction display policy | MessageLabel |
Timing, auto-hide, and muting live in the view. |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Delegate or data-source callbacks | FaceAndWorldTrackingExample/ViewController.swift:40 (ARSessionDelegate), FaceAndWorldTrackingExample/ViewController+CoachingOverlay.swift:31 (ARCoachingOverlayViewDelegate) |
ARKit pushes frames, anchors, and coaching state into the controller. All per-frame behavior hangs off these callbacks. |
RobotHead.Appearance with a didSet is a finite set of visual states, not a polymorphic State pattern.
Main application flow
The flow below covers per-frame updates while a head follows the face, then a tap that freezes it.
sequenceDiagram
actor Person
participant Session as ARSession
participant VC as ViewController
participant Head as RobotHead
Session->>VC: didUpdate frame
VC->>Head: addHeadPreview when slot is nil
VC->>Head: appearance tracked or notTracked
Session->>VC: didUpdate anchors
VC->>Head: update(with faceAnchor)
Person->>VC: handleTap
VC->>Head: reanchor world, appearance anchored
Reference code
FaceAndWorldTrackingExample/ViewController.swift:166 — each frame refills the slot, gates visibility, and updates appearance
func session(_ session: ARSession, didUpdate frame: ARFrame) {
if headPreview == nil, case .normal = frame.camera.trackingState {
addHeadPreview()
}
// Only show floating head if the coaching overlay isn't shown.
headPreview?.isEnabled = !coachingOverlay.isActive
// Update the head's appearance to reflect whether the user's face is tracked
// or the floating head intersects with already anchored heads.
updateHeadPreviewAppearance(for: frame)
}FaceAndWorldTrackingExample/ViewController.swift:179 — face anchors drive only the live head
func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) {
anchors.compactMap { $0 as? ARFaceAnchor }.forEach { headPreview?.update(with: $0) }
}FaceAndWorldTrackingExample/ViewController.swift:74 — a tap re-anchors the head in world space and empties the slot
func handleTap(recognizer: UITapGestureRecognizer) {
guard let robotHeadPreview = headPreview, robotHeadPreview.isEnabled, robotHeadPreview.appearance == .tracked else {
return
}
let headWorldTransform = robotHeadPreview.transformMatrix(relativeTo: nil)
robotHeadPreview.anchor?.reanchor(.world(transform: headWorldTransform))
robotHeadPreview.appearance = .anchored
// By setting the `headPreview` to nil, it prevents the app from updating
// its facial expression in `session(didUpdate anchors:)`.
self.headPreview = nil
}Naming conventions
- Types: UIKit role suffixes (
ViewController,SceneDelegate) and a domain noun for the entity (RobotHead). Nested enums name states and messages (Appearance,Instruction). - Properties:
headPreviewnames the role (the live, not-yet-frozen head) rather than the type. Booleans includeignoreMessages. - Methods:
…ButtonPressedfor actions, imperative helpers (resetTracking,addHeadPreview,showInstruction), and a Boolean query phrased as a question (isTooCloseToAnchoredHeads(in:)). - Files:
Type+Feature.swiftfor the coaching conformance. Cross-type helpers are inUtilities.swift.
Architecture takeaways
- One optional slot (
headPreview) is enough to drive a create → follow → freeze lifecycle from per-frame callbacks. Clearing the slot stops updates while the scene keeps the content. - Re-anchoring an existing camera-anchored entity to a world transform turns follow-the-camera content into placed content without rebuilding it.
- A domain
Entitysubclass with private part lookups and a small API (appearance,update(with:)) keeps the controller free of model-graph details. - A generation counter (
tag) is a lightweight way to cancel stale delayed UI work without keeping work items. - In scene-based lifecycle, window-level fallbacks belong in the scene delegate. An
AppDelegate.windowthat nothing assigns cannot swap the root controller.
Source map
| Source file | Relevant symbols |
|---|---|
FaceAndWorldTrackingExample/AppDelegate.swift |
AppDelegate, unsupported-device fallback, scene configuration |
FaceAndWorldTrackingExample/SceneDelegate.swift |
SceneDelegate |
FaceAndWorldTrackingExample/ViewController.swift |
ViewController, handleTap, addHeadPreview, updateHeadPreviewAppearance, session(_:didUpdate:), resetTracking |
FaceAndWorldTrackingExample/ViewController+CoachingOverlay.swift |
setupCoachingOverlay, ARCoachingOverlayViewDelegate methods |
FaceAndWorldTrackingExample/RobotHead.swift |
RobotHead, Appearance, update(with:), isTooCloseToAnchoredHeads(in:) |
FaceAndWorldTrackingExample/MessageLabel.swift |
MessageLabel, displayMessage |
FaceAndWorldTrackingExample/Utilities.swift |
Entity.color, simd_float4x4.eulerAngles |
FaceAndWorldTrackingExample/Info.plist |
Scene manifest |