Tracking and visualizing planes
At a glance
| Item | Summary |
|---|---|
| Purpose | Run world tracking with horizontal and vertical plane detection and draw each detected plane’s estimated mesh, bounding extent, and classification label in SceneKit. |
| App architecture | UIKit scene-based shell (AppDelegate + SceneDelegate + Main.storyboard) hosting one ViewController; a Plane SCNNode subclass encapsulates per-anchor visualization. |
| Main patterns | ARSCNViewDelegate and ARSessionDelegate callbacks into the controller. |
| Project style | Five Swift files plus a SceneKit shader modifier (wireframe_shader.metal) loaded as text at run time. |
| Execution model | Framework callbacks; one explicit DispatchQueue.main.async hop for presenting the failure alert. |
| State/event model | Direct mutation of SceneKit nodes and UIKit labels inside delegate callbacks. |
| Key frameworks/packages | UIKit, SceneKit, ARKit; no package manifest. |
Project structure
ARKitBasics/
├── AppDelegate.swift ARKit capability check, scene configuration
├── SceneDelegate.swift window scene delegate (empty lifecycle hooks)
├── ViewController.swift session lifecycle, ARSCNView/ARSession delegates
├── Plane.swift SCNNode subclass: mesh, extent, classification text
├── Utilities.swift Classification.description, SCNNode.centerAlign
├── Assets.scnassets/wireframe_shader.metal surface shader modifier
├── Base.lproj/Main.storyboard ViewController, ARSCNView, info overlay
└── Info.plist UIApplicationSceneManifest
Structure observations
- Visualization logic for one anchor lives in
Plane, so the controller only creates and updates it (ARKitBasics/Plane.swift:15). - The storyboard wires both the outlets and the
ARSCNView.delegateto the controller (ARKitBasics/Base.lproj/Main.storyboard:23). Info.plistdeclares a single-scene manifest that namesSceneDelegateand theMainstoryboard (ARKitBasics/Info.plist:31).
Overall architecture
flowchart LR
App["AppDelegate"] -->|UISceneConfiguration| Scene["SceneDelegate"]
Scene -->|Main storyboard| VC["ViewController"]
VC --> View["ARSCNView"]
View --> Session["ARSession"]
View -->|"renderer(_:didAdd/didUpdate:)"| VC
Session -->|"session callbacks"| VC
VC --> Plane["Plane (SCNNode)"]
VC --> Overlay["sessionInfoLabel / View"]
Reference code
ARKitBasics/AppDelegate.swift:36 — AppDelegate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// ...
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
guard ARWorldTrackingConfiguration.isSupported else {
// ...
}
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication,
configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
// ...
}Interpretation
The app delegate fails fast when world tracking is unsupported, then returns a named scene configuration; the storyboard listed in the scene manifest builds the controller and its ARSCNView. SceneDelegate only verifies the scene type (ARKitBasics/SceneDelegate.swift:15). All feature behavior is in ViewController and Plane.
Ownership and state
classDiagram
ViewController o-- ARSCNView : weak IBOutlet sceneView
ViewController o-- UILabel : weak IBOutlet sessionInfoLabel
ARSCNView *-- ARSession : session
ARSCNView --> ViewController : delegate (storyboard)
ARSession --> ViewController : delegate
AnchorNode *-- Plane : addChildNode
Plane *-- SCNNode : meshNode, extentNode, classificationNode
Ownership evidence
ARKitBasics/Plane.swift:17 — Plane
class Plane: SCNNode {
let meshNode: SCNNode
let extentNode: SCNNode
var classificationNode: SCNNode?
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
| Storyboard view hierarchy | sceneView, sessionInfoLabel, sessionInfoView |
Created by the storyboard; the controller holds weak outlets (ARKitBasics/ViewController.swift:15) |
Controller updates text and visibility |
ARKit-managed SCNNode |
Plane |
renderer(_:didAdd:for:) adds Plane as a child of the anchor’s node |
ARKit moves the parent node with the anchor |
Plane |
meshNode, extentNode, classificationNode |
Creates in init and adds as children |
ViewController.renderer(_:didUpdate:for:) updates their geometry |
ViewController |
session configuration | Builds ARWorldTrackingConfiguration in viewDidAppear and resetTracking |
run, pause, and reset options |
Inference: the controller keeps no dictionary of planes; it recovers each Plane from node.childNodes.first, so ARKit’s anchor-to-node mapping is the only index.
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 |
|---|---|---|---|
| Framework callback | ARSCNViewDelegate.renderer(_:didAdd:for:) / didUpdate |
Creates and updates Plane geometry; the source does not state which queue invokes these callbacks |
ARKitBasics/ViewController.swift:51 |
| Framework callback | ARSessionDelegate / ARSessionObserver |
Updates the info label on anchor, tracking, interruption, and failure events | ARKitBasics/ViewController.swift:96 |
| Main-queue scheduling | DispatchQueue.main.async |
Builds and presents the failure alert; the restart action calls resetTracking() |
ARKitBasics/ViewController.swift:137 |
| Shared-state safety | None declared | No lock, actor, or queue protects node or label mutation | ARKitBasics/ViewController.swift:124 |
Reference code
ARKitBasics/ViewController.swift:137 — session(_:didFailWithError:)
func session(_ session: ARSession, didFailWithError error: Error) {
sessionInfoLabel.text = "Session failed: \(error.localizedDescription)"
guard error is ARError else { return }
// ...
DispatchQueue.main.async {
// Present an alert informing about the error that has occurred.
let alertController = UIAlertController(title: "The AR session failed.", message: errorMessage, preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Restart Session", style: .default) { _ in
alertController.dismiss(animated: true, completion: nil)
self.resetTracking()
}
alertController.addAction(restartAction)
self.present(alertController, animated: true, completion: nil)
}
}Only the alert is submitted to the main queue; the label assignment before it runs on whatever queue delivers the callback.
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 | Delegate callbacks | Anchor geometry flows from ARPlaneAnchor into ARSCNPlaneGeometry, SCNPlane, and SCNText |
ARKitBasics/ViewController.swift:71 |
| State propagation | UI feedback | updateSessionInfoLabel maps tracking state to a message and hides the overlay when empty |
ARKitBasics/ViewController.swift:179 |
| Resource loading | Shader modifier string | wireframe_shader.metal is read from the bundle and set as a .surface modifier |
ARKitBasics/Plane.swift:92 |
| Framework import | SceneKit, ARKit |
Compilation dependencies of the controller | ARKitBasics/ViewController.swift:9 |
| Scene lifecycle | UIApplicationSceneManifest |
Single scene, SceneDelegate, Main storyboard |
ARKitBasics/Info.plist:43 |
No Combine usage appears in the source.
Class and protocol design
classDiagram
class ARSCNViewDelegate {
<<protocol>>
}
class ARSessionDelegate {
<<protocol>>
}
ViewController ..|> ARSCNViewDelegate
ViewController ..|> ARSessionDelegate
Plane --|> SCNNode
ViewController --> Plane : creates and updates
Reference code
ARKitBasics/ViewController.swift:12 — ViewController
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
// MARK: - IBOutlets
@IBOutlet weak var sessionInfoView: UIView!
@IBOutlet weak var sessionInfoLabel: UILabel!
@IBOutlet weak var sceneView: ARSCNView!
// ...
}| Type | Responsibility | Depends on |
|---|---|---|
AppDelegate |
Capability check and scene configuration | ARWorldTrackingConfiguration |
SceneDelegate |
Holds the scene window | UIWindowSceneDelegate |
ViewController |
Session lifecycle, delegate callbacks, user feedback | ARSCNView, Plane |
Plane |
Builds and styles the mesh, extent, and classification nodes for one anchor | ARPlaneAnchor, ARSCNView.device |
Utilities.swift extensions |
Classification text and node pivot centering | ARPlaneAnchor.Classification, SCNNode |
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
Plane.setupMeshVisualStyle(), setupExtentVisualStyle(), makeTextNode(_:) |
private |
Only Plane can restyle its children |
Inference: keep construction details inside the node type |
ViewController.updateSessionInfoLabel(for:trackingState:), resetTracking() |
private |
Only the controller’s callbacks drive feedback and resets | Inference: one entry point per behavior |
Plane.meshNode, extentNode |
implicit internal let |
The controller reads them to update geometry; the bindings cannot be replaced | Inference: expose children for updates without allowing reassignment |
Plane.classificationNode |
implicit internal var |
Optional; set only when classification is supported | — |
Reference code
ARKitBasics/Plane.swift:68 — setupMeshVisualStyle()
private func setupMeshVisualStyle() {
// Make the plane visualization semitransparent to clearly show real-world placement.
meshNode.opacity = 0.25
// Use color and blend mode to make planes stand out.
guard let material = meshNode.geometry?.firstMaterial
else { fatalError("ARSCNPlaneGeometry always has one material") }
material.diffuse.contents = UIColor.planeColor
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Device support check | AppDelegate |
Fails at launch rather than in the controller (ARKitBasics/AppDelegate.swift:16) |
| Session start, pause, and reset | ViewController |
Tied to viewDidAppear / viewWillDisappear (ARKitBasics/ViewController.swift:46) |
| Per-plane visualization construction | Plane.init |
Encapsulates geometry, styling, and child layout |
| Per-frame plane updates | ViewController.renderer(_:didUpdate:for:) |
Reads the anchor and mutates Plane children |
| Simulator guard | Plane.init #if targetEnvironment(simulator) #error |
Compile-time failure for unsupported destinations (ARKitBasics/Plane.swift:24) |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Delegate or data-source callbacks | ARKitBasics/ViewController.swift:32 sets sceneView.session.delegate = self; the storyboard connects ARSCNView.delegate (ARKitBasics/Base.lproj/Main.storyboard:23) |
ARKit and SceneKit push anchor and tracking events into the controller |
Main application flow
Scope: ARKit detects a plane and keeps refining it.
sequenceDiagram
participant View as ARSCNView
participant VC as ViewController
participant Plane as Plane
participant Geometry as ARSCNPlaneGeometry
View->>VC: renderer didAdd node for ARPlaneAnchor
VC->>Plane: Plane(anchor, in sceneView)
VC->>View: node.addChildNode(plane)
View->>VC: renderer didUpdate node for anchor
VC->>Geometry: update(from: planeAnchor.geometry)
VC->>Plane: extent size and center from anchor
Reference code
ARKitBasics/ViewController.swift:56 — renderer(_:didAdd:for:)
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
// Place content only for anchors found by plane detection.
guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
// Create a custom object to visualize the plane geometry and extent.
let plane = Plane(anchor: planeAnchor, in: sceneView)
// Add the visualization to the ARKit-managed node so that it tracks
// changes in the plane anchor as plane estimation continues.
node.addChildNode(plane)
}ARKitBasics/ViewController.swift:71 — renderer(_:didUpdate:for:)
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
// Update only anchors and nodes set up by `renderer(_:didAdd:for:)`.
guard let planeAnchor = anchor as? ARPlaneAnchor,
let plane = node.childNodes.first as? Plane
else { return }
// Update ARSCNPlaneGeometry to the anchor's new estimated shape.
if let planeGeometry = plane.meshNode.geometry as? ARSCNPlaneGeometry {
planeGeometry.update(from: planeAnchor.geometry)
}
// Update extent visualization to the anchor's new bounding rectangle.
if let extentGeometry = plane.extentNode.geometry as? SCNPlane {
extentGeometry.width = CGFloat(planeAnchor.extent.x)
extentGeometry.height = CGFloat(planeAnchor.extent.z)
plane.extentNode.simdPosition = planeAnchor.center
}
// ...
}Naming conventions
- Types: UIKit template names plus a domain noun for the visualization node (
Plane). - Protocols: none declared locally.
- Methods:
setup…VisualStyleandmake…Nodefor construction helpers,update…/reset…for controller actions, framework callback signatures elsewhere. - Properties:
…Nodesuffix for SceneKit children,sessionInfo…prefix for the overlay outlets. - Files and extensions:
Utilities.swiftcollects extensions on system types.
Architecture takeaways
- Attach per-anchor content as a child of the ARKit-managed node so the framework handles world transforms; the app only updates local geometry.
- Encapsulate a visualization in an
SCNNodesubclass withprivatesetup helpers, exposing just the child nodes that need per-frame updates. - Recover per-anchor content from the scene graph instead of a parallel dictionary when one child per anchor is guaranteed.
- Pause the session when the view disappears and reset with
.resetTrackingand.removeExistingAnchorsafter interruption.
Source map
| Source file | Relevant symbols |
|---|---|
ARKitBasics/AppDelegate.swift |
AppDelegate, scene configuration |
ARKitBasics/SceneDelegate.swift |
SceneDelegate |
ARKitBasics/ViewController.swift |
ViewController, renderer(_:didAdd:for:), renderer(_:didUpdate:for:), session(_:didFailWithError:) |
ARKitBasics/Plane.swift |
Plane, setupMeshVisualStyle, setupExtentVisualStyle |
ARKitBasics/Base.lproj/Main.storyboard |
outlets, ARSCNView.delegate |
ARKitBasics/Info.plist |
UIApplicationSceneManifest |