Visualizing and interacting with a reconstructed scene
At a glance
| Item | Summary |
|---|---|
| Purpose | Estimate the shape of the physical environment using a polygonal mesh. |
| App architecture | A storyboard UIKit app with scene-based lifecycle. A single ViewController configures a RealityKit ARView for mesh reconstruction with classification, occlusion, and physics. It handles taps and debug toggles, and conforms to the AR-session and coaching-overlay delegates. Helper extensions decode mesh classification and add self-removing anchors. |
| Main patterns | Delegate or data-source callbacks (ARSessionDelegate, ARCoachingOverlayViewDelegate) |
| Project style | One iOS target. ViewController.swift holds the session setup, tap handling, mesh search, and entity factories. ViewController+CoachingOverlay.swift holds onboarding. Extensions.swift holds geometry and classification helpers on ARKit, simd, and RealityKit types. |
| Execution model | The face search runs on DispatchQueue.global(). Its result returns through a completion block and is applied on DispatchQueue.main. Temporary anchors are removed by run-loop Timers. No Swift concurrency. |
| State/event model | Target-action (gesture recognizer, @IBAction buttons), delegate callbacks, and a completion block from the mesh search. The session configuration is changed in place and re-run. |
| Key frameworks/packages | ARKit, RealityKit, UIKit, Metal buffer access through ARMeshGeometry. No package dependencies. |
Project structure
Source bundle/
├── VisualizingSceneSemantics/
│ ├── AppDelegate.swift ARKit support check, scene configuration
│ ├── SceneDelegate.swift window holder; storyboard comes from Info.plist
│ ├── ViewController.swift session setup, tap → classification, toggles
│ ├── ViewController+CoachingOverlay.swift coaching overlay setup and delegate
│ ├── Extensions.swift ARMeshGeometry face helpers, Scene.addAnchor(_:removeAfter:)
│ ├── RoundedButton.swift
│ ├── Base.lproj/Main.storyboard
│ └── Info.plist
├── Documentation/ images only
└── VisualizingSceneSemantics.xcodeproj/
Structure observations
- The window and root controller come from the Info.plist scene manifest (
VisualizingSceneSemantics/Info.plist:62).SceneDelegateonly checks for aUIWindowScene(VisualizingSceneSemantics/SceneDelegate.swift:15). - Device capability is checked twice.
AppDelegateends the process if world tracking is unsupported (VisualizingSceneSemantics/AppDelegate.swift:17).ViewControllerchecks for mesh-with-classification support and shows an in-app message instead of running the session (VisualizingSceneSemantics/ViewController.swift:27). Extensions.swiftturns rawARMeshGeometrybuffers into face-level queries (centerOf,classificationOf). This keeps buffer arithmetic out of the controller.
Overall architecture
flowchart LR
Plist["Info.plist scene manifest"] --> Scene["SceneDelegate"]
Scene --> VC["ViewController"]
VC --> ARView["ARView (RealityKit)"]
ARView --> Session["ARSession (mesh + classification)"]
Session -->|ARSessionDelegate| VC
VC --> Coaching["ARCoachingOverlayView"]
Coaching -->|ARCoachingOverlayViewDelegate| VC
VC --> Ext["ARMeshGeometry / Scene extensions"]
Reference code
VisualizingSceneSemantics/ViewController.swift:52 — the controller turns off automatic configuration and runs its own mesh-classification session
override func viewDidLoad() {
super.viewDidLoad()
guard ARWorldTrackingConfiguration.supportsSceneReconstruction(.meshWithClassification) else {
showUnsupportedDeviceMessage()
return
}
arView.session.delegate = self
setupCoachingOverlay()
arView.environment.sceneUnderstanding.options = []
// ...
arView.environment.sceneUnderstanding.options.insert(.occlusion)
// ...
arView.environment.sceneUnderstanding.options.insert(.physics)
// ...
arView.automaticallyConfigureSession = false
let configuration = ARWorldTrackingConfiguration()
configuration.sceneReconstruction = .meshWithClassification
configuration.environmentTexturing = .automatic
arView.session.run(configuration)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
arView.addGestureRecognizer(tapRecognizer)
}Interpretation
ViewController is the only composition point. It configures RealityKit’s scene understanding (occlusion and physics against the reconstructed mesh), owns the session configuration, and registers for both delegates. The source comment notes that ARView does not enable mesh classification on its own, which is why automaticallyConfigureSession is turned off. Inference: the extensions act as a small domain layer over ARKit’s mesh buffers, so the controller can ask “which classification is near this point” without handling byte offsets.
Ownership and state
classDiagram
ViewController o-- ARView : IBOutlet arView
ViewController *-- ARCoachingOverlayView : let coachingOverlay
ViewController *-- ModelEntity : modelsForClassification cache
ARView *-- ARSession : session
ARCoachingOverlayView o-- ARSession : session
ARCoachingOverlayView --> ViewController : delegate
Ownership evidence
VisualizingSceneSemantics/ViewController.swift:21 — outlets, a controller-created overlay, and a per-classification entity cache
class ViewController: UIViewController, ARSessionDelegate {
@IBOutlet var arView: ARView!
@IBOutlet weak var hideMeshButton: UIButton!
@IBOutlet weak var resetButton: UIButton!
@IBOutlet weak var planeDetectionButton: UIButton!
let coachingOverlay = ARCoachingOverlayView()
// Cache for 3D text geometries representing the classification values.
var modelsForClassification: [ARMeshClassification: ModelEntity] = [:]
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
Storyboard / ViewController |
ARView |
Strong outlet; the view owns its ARSession |
ViewController configures and re-runs the session |
ViewController |
ARCoachingOverlayView |
Created as a let property, added as a subview, and given arView.session (VisualizingSceneSemantics/ViewController+CoachingOverlay.swift:31) |
ViewController |
ViewController |
modelsForClassification |
Lazily filled cache of text entities. Callers receive clone(recursive: true) copies (VisualizingSceneSemantics/ViewController.swift:239) |
model(for:), called from main-queue work |
ARSession |
Current ARWorldTrackingConfiguration |
The plane-detection toggle and reset read session.configuration, mutate it, and run it again |
ViewController action methods |
Scene extension |
Temporary anchors | Added now and removed by a timer 3 seconds after the given delay (VisualizingSceneSemantics/Extensions.swift:119) |
The timer closure |
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 |
|---|---|---|---|
| Global-queue work | DispatchQueue.global().async |
The face-by-face search over nearby ARMeshAnchors runs on a global concurrent queue. The source comment says this is “in order not to stall rendering”. |
VisualizingSceneSemantics/ViewController.swift:187 |
| Captured input | Local meshAnchors array |
Anchors are read from session.currentFrame, filtered, and sorted before the hop. The background block only reads the captured array and its geometry. |
VisualizingSceneSemantics/ViewController.swift:178 |
| Callback queue | completionBlock |
The completion block is called on the global queue, or synchronously when no frame exists. The caller cannot assume the main queue. | VisualizingSceneSemantics/ViewController.swift:203 |
| Main-queue scheduling | DispatchQueue.main.async |
The tap handler applies the result on the main queue: it positions and scales the text, reads the entity cache, and adds anchors. | VisualizingSceneSemantics/ViewController.swift:107 |
| Main-queue scheduling | DispatchQueue.main.async |
Session failure presents the restart alert on the main queue. | VisualizingSceneSemantics/ViewController.swift:223 |
| Run-loop timers | Timer.scheduledTimer |
addAnchor(_:removeAfter:) switches the model to dynamic physics after seconds and removes the anchor 3 seconds later. |
VisualizingSceneSemantics/Extensions.swift:116 |
Shared-state safety: modelsForClassification has no lock. It is touched only inside model(for:), which this sample calls only from the main-queue block above. Mesh geometry is read on the global queue with no synchronization, from anchors captured from one frame.
Reference code
VisualizingSceneSemantics/ViewController.swift:187 — the expensive search moves off the caller’s queue and reports through a block
// Perform the search asynchronously in order not to stall rendering.
DispatchQueue.global().async {
for anchor in meshAnchors {
for index in 0..<anchor.geometry.faces.count {
// ...
if distanceToFace <= 0.05 {
// Get the semantic classification of the face and finish the search.
let classification: ARMeshClassification = anchor.geometry.classificationOf(faceWithIndex: index)
completionBlock(centerWorldPosition, classification)
return
}
}
}
// Let the completion block know that no result was found.
completionBlock(nil, .none)
}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 | Target-action | The tap gesture and three @IBAction buttons (reset, show or hide mesh, plane detection). |
VisualizingSceneSemantics/ViewController.swift:158 |
| State propagation | Configuration re-run | Plane detection is toggled by mutating session.configuration and calling run again. Reset re-runs with .resetSceneReconstruction. |
VisualizingSceneSemantics/ViewController.swift:169 |
| State propagation | ARCoachingOverlayViewDelegate |
Hides the buttons while coaching is active and resets the session on request. | VisualizingSceneSemantics/ViewController+CoachingOverlay.swift:11 |
| State propagation | Completion block | The mesh search result returns to the tap handler. | VisualizingSceneSemantics/ViewController.swift:172 |
| Framework import | RealityKit |
ARView, AnchorEntity, ModelEntity, MeshResource.generateText, physics. |
VisualizingSceneSemantics/ViewController.swift:8 |
| Framework import | ARKit |
Scene reconstruction, ARMeshAnchor, ARMeshClassification, coaching overlay. |
VisualizingSceneSemantics/ViewController.swift:9 |
| Framework import | UIKit |
App and scene delegates, coaching-overlay layout, buttons. | VisualizingSceneSemantics/ViewController+CoachingOverlay.swift:8 |
Class and protocol design
Reference code
VisualizingSceneSemantics/Extensions.swift:63 — a typed query over a raw Metal-backed classification buffer
extension ARMeshGeometry {
// ...
func classificationOf(faceWithIndex index: Int) -> ARMeshClassification {
guard let classification = classification else { return .none }
assert(classification.format == MTLVertexFormat.uchar, "Expected one unsigned char (one byte) per classification")
let classificationPointer = classification.buffer.contents().advanced(by: classification.offset + (classification.stride * index))
let classificationValue = Int(classificationPointer.assumingMemoryBound(to: CUnsignedChar.self).pointee)
return ARMeshClassification(rawValue: classificationValue) ?? .none
}
// ...
}| Type | Responsibility | Depends on |
|---|---|---|
AppDelegate |
World-tracking support check; returns the scene configuration | UIApplicationDelegate |
SceneDelegate |
Holds the scene’s window |
UIWindowSceneDelegate |
ViewController |
Session and view configuration, tap-to-classification, toggles, error alert, entity factories | ARView, extensions |
ViewController (coaching extension) |
Overlay layout and delegate callbacks | ARCoachingOverlayView |
ARMeshGeometry extension |
Vertex, face, center, and classification lookup | Metal buffer layout |
ARMeshClassification extension |
Display description and color |
UIKit |
Scene extension |
addAnchor(_:removeAfter:) with a kinematic-then-dynamic physics handoff |
RealityKit physics |
RoundedButton |
Styled UIButton |
UIKit |
No local protocol is declared. All extension points are framework delegate protocols and extensions on framework types.
Access control
No declaration in the app sources uses an explicit access modifier. Every type and member is implicit internal.
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
ViewController.coachingOverlay, hideMeshButton, resetButton, planeDetectionButton (VisualizingSceneSemantics/ViewController.swift:14) |
implicit internal |
ViewController+CoachingOverlay.swift, a separate file, reads and changes them. |
Inference: private would block the cross-file extension. |
resetButtonPressed(_:) (VisualizingSceneSemantics/ViewController.swift:140) |
implicit internal @IBAction |
Called by the button, the error alert, and the coaching extension. | Inference: one reset path shared by three triggers. |
ARMeshGeometry.classificationOf(faceWithIndex:) (VisualizingSceneSemantics/Extensions.swift:63) |
implicit internal |
Usable anywhere in the app module. | Inference: the helpers are module-wide utilities. |
Reference code
VisualizingSceneSemantics/ViewController+CoachingOverlay.swift:13 — a different file mutates the controller’s outlets
extension ViewController: ARCoachingOverlayViewDelegate {
func coachingOverlayViewWillActivate(_ coachingOverlayView: ARCoachingOverlayView) {
hideMeshButton.isHidden = true
resetButton.isHidden = true
planeDetectionButton.isHidden = true
}
// ...
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Session and scene-understanding configuration | ViewController.viewDidLoad |
One place enables occlusion, physics, the debug mesh, and render-option trimming. |
| Unsupported-device UI | ViewController.showUnsupportedDeviceMessage (VisualizingSceneSemantics/ViewController.swift:63) |
Hides subviews and shows a label instead of running the session. |
| Tap → ray cast → classification → text | ViewController.handleTap and nearbyFaceWithClassification |
Immediate sphere feedback first, then the asynchronous classification result. |
| Face geometry and classification decoding | ARMeshGeometry extension |
Keeps buffer-offset arithmetic next to the type it reads. |
| Temporary content lifetime and physics handoff | Scene.addAnchor(_:removeAfter:) |
Every transient anchor gets the same collision setup and timed removal. |
| Onboarding | ViewController+CoachingOverlay.swift |
Coaching state controls button visibility. |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Delegate or data-source callbacks | VisualizingSceneSemantics/ViewController.swift:32 (ARSessionDelegate), VisualizingSceneSemantics/ViewController+CoachingOverlay.swift:32 (ARCoachingOverlayViewDelegate) |
Session failures and coaching state reach the controller as framework callbacks, each conformance in its own file. |
Main application flow
The flow below covers one tap on the reconstructed mesh, through the classification label.
sequenceDiagram
actor Person
participant VC as ViewController
participant ARView
participant Global as GlobalQueue
participant Main as MainQueue
Person->>VC: handleTap
VC->>ARView: raycast estimatedPlane
VC->>ARView: addAnchor sphere removeAfter 3
VC->>Global: nearbyFaceWithClassification async search
Global-->>VC: completionBlock(center, classification)
VC->>Main: DispatchQueue.main.async
Main->>ARView: addAnchor text and face markers
Reference code
VisualizingSceneSemantics/ViewController.swift:96 — the tap handler gives instant feedback, then hops to main for the asynchronous result
func handleTap(_ sender: UITapGestureRecognizer) {
// ...
let tapLocation = sender.location(in: arView)
if let result = arView.raycast(from: tapLocation, allowing: .estimatedPlane, alignment: .any).first {
// ...
let resultAnchor = AnchorEntity(world: result.worldTransform)
resultAnchor.addChild(sphere(radius: 0.01, color: .lightGray))
arView.scene.addAnchor(resultAnchor, removeAfter: 3)
// ...
nearbyFaceWithClassification(to: result.worldTransform.position) { (centerOfFace, classification) in
// ...
DispatchQueue.main.async {
// ...
let textEntity = self.model(for: classification)
// ...
self.arView.scene.addAnchor(textAnchor, removeAfter: 3)
// ...
}
}
}
}VisualizingSceneSemantics/ViewController.swift:203 — the search runs on a global queue and calls back from there
func nearbyFaceWithClassification(to location: SIMD3<Float>, completionBlock: @escaping (SIMD3<Float>?, ARMeshClassification) -> Void) {
guard let frame = arView.session.currentFrame else {
completionBlock(nil, .none)
return
}
// ...
DispatchQueue.global().async {
for anchor in meshAnchors {
for index in 0..<anchor.geometry.faces.count {
// ...
if distanceToFace <= 0.05 {
// ...
let classification: ARMeshClassification = anchor.geometry.classificationOf(faceWithIndex: index)
completionBlock(centerWorldPosition, classification)
return
}
}
}
// ...
completionBlock(nil, .none)
}
}Naming conventions
- Types: UIKit role suffixes (
ViewController,SceneDelegate). Extensions are named for the framework type they extend. - Methods:
…Pressedfor@IBActions (resetButtonPressed,toggleMeshButtonPressed). Noun-style factories return entities (model(for:),sphere(radius:color:)). Queries read as phrases (nearbyFaceWithClassification(to:completionBlock:),classificationOf(faceWithIndex:),centerOf(faceWithIndex:)). - Callbacks: the completion parameter is named
completionBlock. - Files:
Type+Feature.swiftfor a conformance extension (ViewController+CoachingOverlay.swift). Helpers for several framework types share oneExtensions.swift.
Architecture takeaways
- When a framework view auto-configures its session (
ARView), turn that off explicitly and own the configuration if you need features it will not enable. - Snapshot the input on the calling queue, search on a global queue, and apply the result on the main queue. The callback queue is not the main queue, so the caller must hop.
- Small typed extensions over raw framework buffers (
classificationOf(faceWithIndex:)) keep unsafe pointer code out of controller logic. - Caching one template entity per classification and returning clones avoids regenerating text meshes on every tap.
- A shared
addAnchor(_:removeAfter:)helper gives transient content one consistent lifetime and physics policy.
Source map
| Source file | Relevant symbols |
|---|---|
VisualizingSceneSemantics/AppDelegate.swift |
AppDelegate, scene configuration |
VisualizingSceneSemantics/SceneDelegate.swift |
SceneDelegate |
VisualizingSceneSemantics/ViewController.swift |
ViewController, viewDidLoad, handleTap, nearbyFaceWithClassification, model(for:), togglePlaneDetectionButtonPressed |
VisualizingSceneSemantics/ViewController+CoachingOverlay.swift |
setupCoachingOverlay, ARCoachingOverlayViewDelegate methods |
VisualizingSceneSemantics/Extensions.swift |
ARMeshGeometry.classificationOf, centerOf, Scene.addAnchor(_:removeAfter:) |
VisualizingSceneSemantics/Info.plist |
Scene manifest |