Scanning and Detecting 3D Objects
At a glance
| Item | Summary |
|---|---|
| Purpose | Scan a real object into an ARReferenceObject (define a bounding box, capture features from all sides, adjust the origin), test detection with ARWorldTrackingConfiguration.detectionObjects, merge scans, and share the .arobject file. |
| App architecture | A UIKit storyboard app. One ViewController, split across extensions by concern, owns the ARSCNView and an app-level State machine. In the scanning state it creates a Scan (its own State machine plus the SceneKit nodes ScannedObject and ScannedPointCloud); in testing it creates a TestRun (owns a DetectedObject). SceneKit nodes and models talk back through NotificationCenter, and several types reach the controller through a global ViewController.instance. |
| Main patterns | View-controller organization (one controller plus concern-named extensions), ARKit/SceneKit delegate callbacks, NotificationCenter observers between nodes and the controller, and a PointCloud protocol whose extension supplies shared geometry code. |
| Project style | 31 Swift files in role folders: Controllers/, 3D UI and Visualizations / (SceneKit node subclasses), Gesture Recognizers/ (threshold recognizers), Views/ (UIKit controls), Utility Extensions/, plus art.scnassets/wireframe_shader.metal. |
| Execution model | No Swift concurrency. UI updates are submitted with DispatchQueue.main.async; .arobject export runs on DispatchQueue.global(); scan merging runs on DispatchQueue.global(qos: .background) and returns on the main queue. Per-frame work runs from renderer(_:updateAtTime:). Several one-shot Timers handle warnings and message expiry. |
| State/event model | Two nested finite state machines implemented as computed state properties whose setters check preconditions, apply side effects, and post a notification. Named notifications carry bounding-box, origin, scan-percentage, and state changes. |
| Key frameworks/packages | ARKit, SceneKit, UIKit, AVFoundation (flashlight). The project declares no Swift package. |
Project structure
ScanningApp.xcodeproj/ one app target, Swift 5, iOS 15.0 deployment target
ScanningApp/
├── Controllers/
│ ├── AppDelegate.swift ARKit support check; scene configuration
│ ├── SceneDelegate.swift forwards activation, foreground, and opened URLs to ViewController
│ ├── ViewController.swift outlets, session delegates, file import/export, timers
│ ├── ViewController+ApplicationState.swift app State machine and Scan.State UI mapping
│ ├── ViewController+Gestures.swift forwards gestures to Scan while scanning
│ ├── ViewController+NavigationBar.swift, ViewController+SessionInfo.swift
│ ├── Scan.swift Scan.State machine; preliminary and final reference objects
│ ├── TestRun.swift detection configuration, statistics, re-detection
│ └── ShareScanViewController.swift UIActivityViewController subclass
├── 3D UI and Visualizations / ScannedObject, BoundingBox(+Side, Tile, Wireframe, Snapping),
│ ObjectOrigin(+Axis), ScannedPointCloud, Detected*, PointCloud protocol
├── Gesture Recognizers/ ThresholdPan/Pinch/RotationGestureRecognizer
├── Views/ MessageLabel + Message, RoundedButton, FlashlightButton
├── Utility Extensions/ Utilities.swift (math, Ray, PlaneDrag, mergeInBackground), ARCameraTrackingState.swift
└── Info.plist scene manifest, arkit capability, .arobject document type
Structure observations
- The folder named
3D UI and Visualizationsends with a trailing space in the source tree; citations below keep it. ViewControlleris one class spread over five files; each extension file is named for its concern (+ApplicationState,+Gestures,+NavigationBar,+SessionInfo).Info.plistdeclares thecom.apple.arobjectdocument type and the scene manifest (ScanningApp/Info.plist:9,ScanningApp/Info.plist:64). Files opened from outside the app arrive throughSceneDelegate.scene(_:openURLContexts:)(ScanningApp/Controllers/SceneDelegate.swift:36).
Overall architecture
flowchart LR
Scene["SceneDelegate"] -->|"rootViewController as? ViewController"| VC["ViewController (app State)"]
VC -->|"IBOutlet"| View["ARSCNView + ARSession"]
View -. "ARSCNViewDelegate / ARSessionDelegate" .-> VC
VC -->|"state = .scanning"| Scan["Scan (Scan.State)"]
VC -->|"state = .testing"| Test["TestRun"]
Scan --> SObj["ScannedObject: BoundingBox, ghost box, ObjectOrigin"]
Scan --> SPC["ScannedPointCloud"]
Test --> DObj["DetectedObject"]
SObj -. "NotificationCenter" .-> VC
Scan -. "stateChangedNotification" .-> VC
Scan -. "ViewController.instance" .-> VC
Reference code
ScanningApp/Controllers/ViewController+ApplicationState.swift:102 — the app state setter creates and discards the feature objects
extension ViewController {
// ...
var state: State {
// ...
set {
// ...
internalState = newState
switch newState {
case .startARSession:
// ...
scan = nil
testRun = nil
// ...
sceneView.session.run(configuration, options: .resetTracking)
// ...
case .scanning:
// ...
if scan == nil {
self.scan = Scan(sceneView)
self.scan?.state = .ready
}
testRun = nil
// ...
case .testing:
// ...
testRun = TestRun(sceneView: sceneView)
testObjectDetection()
cancelMaxScanTimeTimer()
}
// ...
}
}
// ...
}Interpretation
Observed: object lifetime follows the app state. Entering .startARSession releases scan and testRun and reruns an ARObjectScanningConfiguration; .scanning creates a Scan; .testing creates a TestRun. testObjectDetection(of:) then sets scan = nil so the user cannot return to scanning, with a comment explaining that testing reruns the session with a different configuration (ScanningApp/Controllers/ViewController.swift:317).
Observed: Scan and its nodes clean up in deinit by removing themselves from the scene (ScanningApp/Controllers/Scan.swift:139), and TestRun.deinit switches the session back to object scanning (ScanningApp/Controllers/TestRun.swift:39). Inference: releasing the controller’s reference is the teardown mechanism, which is why the state setter only assigns nil.
Ownership and state
classDiagram
ViewController o-- ARSCNView : weak @IBOutlet sceneView
ViewController *-- Scan : var scan
ViewController *-- TestRun : var testRun
ViewController o-- ARReferenceObject : referenceObjectToMerge / ToTest
Scan *-- ScannedObject : private(set)
Scan *-- ScannedPointCloud : private(set)
Scan o-- ARReferenceObject : scannedReferenceObject
ScannedObject *-- BoundingBox : boundingBox, ghostBoundingBox
ScannedObject *-- ObjectOrigin : origin
BoundingBox *-- BoundingBoxSide : sides
BoundingBoxSide *-- Tile : tiles
TestRun *-- DetectedObject : private(set)
TestRun o-- ARReferenceObject : referenceObject
Ownership evidence
ScanningApp/Controllers/Scan.swift:127 — Scan creates its nodes and observes the app state
class Scan {
// ...
// The object which we want to scan
private(set) var scannedObject: ScannedObject
// The result of this scan, an ARReferenceObject
private(set) var scannedReferenceObject: ARReferenceObject?
// The node for visualizing the point cloud.
private(set) var pointCloud: ScannedPointCloud
private var sceneView: ARSCNView
private var isBusyCreatingReferenceObject = false
// ...
init(_ sceneView: ARSCNView) {
self.sceneView = sceneView
scannedObject = ScannedObject(sceneView)
pointCloud = ScannedPointCloud()
NotificationCenter.default.addObserver(self,
selector: #selector(self.applicationStateChanged(_:)),
name: ViewController.appStateChangedNotification,
object: nil)
self.sceneView.scene.rootNode.addChildNode(self.scannedObject)
self.sceneView.scene.rootNode.addChildNode(self.pointCloud)
}
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
ViewController |
internalState behind state |
internal var with a computed setter that validates and applies transitions (ScanningApp/Controllers/ViewController.swift:33, ScanningApp/Controllers/ViewController+ApplicationState.swift:22) |
ViewController and its extensions |
ViewController |
scan, testRun |
Created by the state setter and released by assigning nil (ScanningApp/Controllers/ViewController.swift:35, ScanningApp/Controllers/ViewController.swift:40) |
State setter, testObjectDetection(of:) |
ViewController |
referenceObjectToMerge, referenceObjectToTest |
Implicitly internal vars set from file import and the merge menu (ScanningApp/Controllers/ViewController.swift:37) |
ViewController, and Scan through ViewController.instance |
Scan |
stateValue behind state |
private var with a validating setter (ScanningApp/Controllers/Scan.swift:26, ScanningApp/Controllers/Scan.swift:27) |
Scan; the controller sets scan.state |
Scan |
ScannedObject, ScannedPointCloud |
private(set), created in init and added to the scene |
Scan |
ScannedObject |
boundingBox, ghostBoundingBox, origin |
private(set) nodes (ScanningApp/3D UI and Visualizations /ScannedObject.swift:19) |
ScannedObject |
TestRun |
DetectedObject, detection statistics |
private(set) var detectedObject; plain var counters (ScanningApp/Controllers/TestRun.swift:17, ScanningApp/Controllers/TestRun.swift:19) |
TestRun |
ViewController (type) |
static var instance |
Global reference set in viewWillAppear (ScanningApp/Controllers/ViewController.swift:17, ScanningApp/Controllers/ViewController.swift:73) |
ViewController |
Observed: ViewController.instance is read by Scan (alerts, merge input), TestRun (messages), ShareScanViewController (session restart), BoundingBox snapping, and ScannedObject (screen center) (ScanningApp/Controllers/Scan.swift:119, ScanningApp/Controllers/TestRun.swift:114, ScanningApp/Controllers/ShareScanViewController.swift:28, ScanningApp/3D UI and Visualizations /Snapping.swift:18). Interpretation: model and node types depend on the concrete controller through a global, so the dependency direction is two-way.
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 |
|---|---|---|---|
| Per-frame work | renderer(_:updateAtTime:) calls scan?.updateOnEveryFrame(frame) and testRun?.updateOnEveryFrame() |
Bounding-box fitting, point-cloud updates, and coverage progress run from SceneKit’s update callback | ScanningApp/Controllers/ViewController.swift:447, ScanningApp/Controllers/ViewController.swift:449 |
| Off-main value cache | screenCenter = sceneView.center in viewDidLayoutSubviews |
The comment says the value is stored “so it can be retrieved later from outside the main thread”; ScannedObject reads it during per-frame fitting |
ScanningApp/Controllers/ViewController.swift:123, ScanningApp/3D UI and Visualizations /ScannedObject.swift:96 |
| Throttled async framework call | isBusyCreatingReferenceObject and a 1-second interval around session.createReferenceObject |
At most one preliminary reference-object request is in flight; its completion updates the point cloud and clears the flag | ScanningApp/Controllers/Scan.swift:363, ScanningApp/Controllers/Scan.swift:366, ScanningApp/Controllers/Scan.swift:373 |
| Frame-rate throttling | frameCounter % 20 / % 10 and isUpdatingCapturingProgress |
Coverage rays are sampled every 20 calls and tiles re-evaluated every 10 | ScanningApp/3D UI and Visualizations /BoundingBox.swift:362, ScanningApp/3D UI and Visualizations /BoundingBox.swift:380 |
| Background merge | DispatchQueue.global(qos: .background).async then DispatchQueue.main.async { completion(...) } |
ARReferenceObject.merging(_:) runs on a global queue; the completion is delivered on the main queue |
ScanningApp/Utility Extensions/Utilities.swift:270, ScanningApp/Utility Extensions/Utilities.swift:273 |
| Background export | DispatchQueue.global().async { try object.export(...) ... } |
Export runs on a global queue; the ShareScanViewController is created in that work item and presented from the main queue |
ScanningApp/Controllers/ViewController.swift:331, ScanningApp/Controllers/ViewController.swift:339, ScanningApp/Controllers/ViewController.swift:340 |
| Main-queue UI | DispatchQueue.main.async around Scan-state UI, alerts, labels, and navigation title |
UI changes triggered from notifications and callbacks are submitted to the main queue | ScanningApp/Controllers/ViewController+ApplicationState.swift:133, ScanningApp/Views/MessageLabel.swift:40, ScanningApp/Controllers/ViewController.swift:555 |
| Timers | Timer.scheduledTimer for limited tracking (2 s), max scan time (5 min), no detection (5 s), message expiry |
Each timer is stored and invalidated by a matching cancel… method before restart |
ScanningApp/Controllers/ViewController.swift:351, ScanningApp/Controllers/ViewController.swift:378, ScanningApp/Controllers/TestRun.swift:112 |
| Shared-state safety | Flags only | isBusyCreatingReferenceObject and isUpdatingCapturingProgress are plain Bools, not locks; scan and controller state are touched from callbacks and queue work items without synchronization |
ScanningApp/Controllers/Scan.swift:112, ScanningApp/3D UI and Visualizations /BoundingBox.swift:65 |
Reference code
ScanningApp/Utility Extensions/Utilities.swift:270 — background merge with main-queue completion
extension ARReferenceObject {
func mergeInBackground(with otherReferenceObject: ARReferenceObject, completion: @escaping (ARReferenceObject?, Error?) -> Void) {
DispatchQueue.global(qos: .background).async {
do {
let mergedObject = try self.merging(otherReferenceObject)
DispatchQueue.main.async {
completion(mergedObject, nil)
}
} catch {
DispatchQueue.main.async {
completion(nil, error)
}
}
}
}
}Not established by source: which thread runs renderer(_:updateAtTime:), which queue ARKit uses for session callbacks (no delegateQueue is set), and where createReferenceObject’s completion handler runs. Interpretation: the merge helper is the one place with an explicit off-main/on-main round trip; elsewhere, the code relies on flags and main-queue submissions for UI without protecting shared model state.
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 |
|---|---|---|---|
| App state broadcast | ViewController.appStateChangedNotification posted at the end of every app-state change |
Scan hides or shows its nodes in response |
ScanningApp/Controllers/ViewController+ApplicationState.swift:122, ScanningApp/Controllers/Scan.swift:145 |
| Scan state broadcast | Scan.stateChangedNotification |
ViewController.scanningStateChanged(_:) maps each Scan.State to buttons, titles, and instructions |
ScanningApp/Controllers/Scan.swift:87, ScanningApp/Controllers/ViewController+ApplicationState.swift:129 |
| Node events | BoundingBox extent/position/percentage, ScannedObject box created/ghost created/removed, ObjectOrigin position |
Nodes post; the controller and point cloud observe | ScanningApp/3D UI and Visualizations /BoundingBox.swift:13, ScanningApp/3D UI and Visualizations /ScannedObject.swift:15, ScanningApp/Controllers/ViewController.swift:91 |
| Scan completion | scanPercentageChanged(_:) advances to the next state at 100 % |
Progress drives the state machine | ScanningApp/Controllers/ViewController.swift:546, ScanningApp/Controllers/ViewController.swift:551 |
| Scene lifecycle | SceneDelegate forwards activation, resign, foreground, and URLs to the root ViewController |
Blur overlay, interrupted-scan warning, and file import | ScanningApp/Controllers/SceneDelegate.swift:22, ScanningApp/Controllers/SceneDelegate.swift:30, ScanningApp/Controllers/SceneDelegate.swift:38 |
| Framework import | ARKit, SceneKit, UIKit |
Controller compilation dependencies | ScanningApp/Controllers/ViewController.swift:10, ScanningApp/Controllers/ViewController.swift:9, ScanningApp/Controllers/ViewController.swift:8 |
| Framework import | AVFoundation |
Torch control in FlashlightButton |
ScanningApp/Views/FlashlightButton.swift:9 |
| Package declaration | None | The project file declares no Swift package | ScanningApp.xcodeproj/project.pbxproj:509 |
The source uses no Combine or observation framework.
Class and protocol design
classDiagram
class PointCloud {
<<protocol>>
createVisualization(points, color, size)
}
ScannedPointCloud ..|> PointCloud
DetectedPointCloud ..|> PointCloud
ScannedObject --|> SCNNode
BoundingBox --|> SCNNode
ObjectOrigin --|> SCNNode
DetectedObject --|> SCNNode
ViewController ..|> ARSCNViewDelegate
ViewController ..|> ARSessionDelegate
ViewController ..|> UIDocumentPickerDelegate
ShareScanViewController --|> UIActivityViewController
Reference code
ScanningApp/3D UI and Visualizations /PointCloud+CreateVisualization.swift:16 — protocol with a shared default implementation
extension PointCloud {
func createVisualization(for points: [SIMD3<Float>], color: UIColor, size: CGFloat) -> SCNGeometry? {
guard !points.isEmpty else { return nil }
let stride = MemoryLayout<SIMD3<Float>>.size
let pointData = Data(bytes: points, count: stride * points.count)
// Create geometry source
let source = SCNGeometrySource(data: pointData,
semantic: SCNGeometrySource.Semantic.vertex,
vectorCount: points.count,
usesFloatComponents: true,
componentsPerVector: 3,
bytesPerComponent: MemoryLayout<Float>.size,
dataOffset: 0,
dataStride: stride)
// Create geometry element
let element = SCNGeometryElement(data: nil, primitiveType: .point, primitiveCount: points.count, bytesPerIndex: 0)
element.pointSize = 0.001
element.minimumPointScreenSpaceRadius = size
element.maximumPointScreenSpaceRadius = size
let pointsGeometry = SCNGeometry(sources: [source], elements: [element])
pointsGeometry.materials = [SCNMaterial.material(withDiffuse: color)]
return pointsGeometry
}
}| Type | Responsibility | Depends on or conforms to |
|---|---|---|
ViewController (+4 extensions) |
App state machine, session delegates, gestures routing, file import/export, alerts and timers | UIViewController, ARSCNViewDelegate, ARSessionDelegate, UIDocumentPickerDelegate, UIGestureRecognizerDelegate |
Scan |
Scan state machine, preliminary and final ARReferenceObject creation, gesture handling while scanning |
ScannedObject, ScannedPointCloud, ARSCNView |
TestRun |
Runs detection, measures detection delay, forces re-detection by removing anchors | DetectedObject, ARSCNView |
ScannedObject |
Owns the ghost box, bounding box, and origin; creates boxes from hit tests | SCNNode |
BoundingBox, BoundingBoxSide, Tile |
Interactive box with draggable sides and coverage tiles; computes scan percentage | SCNNode |
ScannedPointCloud, DetectedPointCloud |
Feature-point visualization | SCNNode, PointCloud |
Threshold*GestureRecognizer |
Gesture recognizers that start only past a movement threshold | UIKit recognizers |
Observed: the only local protocol is PointCloud, and its single requirement is satisfied by the extension for both conformers. The state machines are plain enums with validating setters, not polymorphic State objects.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
ViewController.internalState, scan, testRun, timers (ScanningApp/Controllers/ViewController.swift:33) |
explicit internal |
Same as the default: module-wide read and write | The keyword documents that extension files in other source files use them; it does not restrict access. |
ViewController.instance (ScanningApp/Controllers/ViewController.swift:17) |
implicit internal static var |
Any type can read or overwrite the global controller reference | Inference: convenience access for nodes and models. |
Scan.stateValue (ScanningApp/Controllers/Scan.swift:26) |
private |
Transitions must go through the validating state setter |
Keeps preconditions and notifications in one place. |
Scan.scannedObject, pointCloud, scannedReferenceObject, screenshot (ScanningApp/Controllers/Scan.swift:102) |
private(set) |
Readable by the controller; replaced only by Scan |
Inference: the scan owns its nodes and result. |
ScannedObject.origin, boundingBox, ghostBoundingBox (ScanningApp/3D UI and Visualizations /ScannedObject.swift:19) |
private(set) |
Box and origin nodes are created only by ScannedObject |
Same as above. |
TestRun.detectedObject (ScanningApp/Controllers/TestRun.swift:17) |
private(set) |
Controller can read it (for 3D model overlays) but not replace it | Same as above. |
mergeIntoCurrentScan(referenceObject:from:) (ScanningApp/Controllers/ViewController.swift:479) |
fileprivate |
Callable only from ViewController.swift |
Inference: an implementation step of loadReferenceObjectToMerge(from:). |
SceneDelegate.viewController (ScanningApp/Controllers/SceneDelegate.swift:41) |
private computed |
Encapsulates the root-controller cast | Inference: one lookup for all forwarded events. |
Reference code
ScanningApp/Controllers/Scan.swift:26 — private storage behind a validating setter
class Scan {
// ...
// The current state the scan is in
private var stateValue: State = .ready
var state: State {
get {
return stateValue
}
set {
// Check that preconditions for the state change are met.
switch newValue {
case .ready:
break
case .defineBoundingBox where !boundingBoxExists && !ghostBoundingBoxExists:
print("Error: Ghost bounding box not yet created.")
return
// ...
default:
break
}
// Apply the new state
stateValue = newValue
NotificationCenter.default.post(name: Scan.stateChangedNotification,
object: self,
userInfo: [Scan.stateUserInfoKey: self.state])
}
}
// ...
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| App-level transitions | ViewController.state setter, switchToNextState(), switchToPreviousState() |
Tracking state can force .notReady or .scanning; .testing requires a box or a received object (ScanningApp/Controllers/ViewController+ApplicationState.swift:57, ScanningApp/Controllers/ViewController+ApplicationState.swift:213). |
| Scan-level transitions and quality gates | Scan.state setter |
Size limits, feature count, and coverage checks trigger alerts that can send the user back (ScanningApp/Controllers/Scan.swift:42, ScanningApp/Controllers/Scan.swift:59, ScanningApp/Controllers/Scan.swift:69). |
| Tracking reactions | session(_:cameraDidChangeTrackingState:) |
Relocalization during a scan prompts a restart; other limited states start a 2-second warning timer (ScanningApp/Controllers/ViewController.swift:395, ScanningApp/Controllers/ViewController.swift:414). |
| Final reference object | Scan.createReferenceObject(completionHandler:) |
Applies the user’s origin transform, names the object, and merges a pending object when present (ScanningApp/Controllers/Scan.swift:426, ScanningApp/Controllers/Scan.swift:440, ScanningApp/Controllers/Scan.swift:443). |
| Detection testing | TestRun.setReferenceObject(_:screenshot:), successfulDetection(_:) |
Runs world tracking with detectionObjects, then removes each detected anchor to measure re-detection (ScanningApp/Controllers/TestRun.swift:71, ScanningApp/Controllers/TestRun.swift:90). |
| Coverage measurement | BoundingBox.updateCapturingProgress() |
Camera rays hit tiles; five non-bottom sides average into a percentage (ScanningApp/3D UI and Visualizations /BoundingBox.swift:355). |
| File routing | ViewController.readFile(_:) |
.arobject files go to merge/test; .usdz files become a model overlay (ScanningApp/Controllers/ViewController.swift:471). |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| View-controller organization | One ViewController owns the session and outlets and is split into concern-named extensions (ScanningApp/Controllers/ViewController.swift:12, ScanningApp/Controllers/ViewController+ApplicationState.swift:12) |
Keeps a large controller navigable by file; feature logic still lives in Scan and TestRun. |
| Delegate or data-source callbacks | sceneView.delegate = self, sceneView.session.delegate = self, documentPicker.delegate = self (ScanningApp/Controllers/ViewController.swift:84, ScanningApp/Controllers/ViewController.swift:85, ScanningApp/Controllers/ViewController.swift:194) |
Frames, anchors, tracking changes, and picked files arrive as callbacks. |
| Observer | Named notifications posted by Scan, ScannedObject, BoundingBox, ObjectOrigin, and the controller; observed with addObserver(_:selector:name:object:) (ScanningApp/Controllers/ViewController.swift:91, ScanningApp/Controllers/Scan.swift:130, ScanningApp/3D UI and Visualizations /ScannedObject.swift:46) |
Nodes report changes without references to the controller; the cost is untyped userInfo payloads. |
| Protocol-oriented abstraction | PointCloud with a default createVisualization in an extension, adopted by both point-cloud nodes (ScanningApp/3D UI and Visualizations /PointCloud+CreateVisualization.swift:11, ScanningApp/3D UI and Visualizations /ScannedPointCloud.swift:12, ScanningApp/3D UI and Visualizations /DetectedPointCloud.swift:11) |
Shares geometry construction between two otherwise unrelated SCNNode subclasses. |
The two State enums are finite state machines implemented with validating setters; no polymorphic State pattern is claimed.
Naming conventions
- Types: domain nouns for the workflow (
Scan,TestRun), the scanned entity (ScannedObject,ScannedPointCloud), and the detected entity (DetectedObject,DetectedPointCloud,DetectedBoundingBox). Scanned and detected types are named in parallel. - Notifications:
static let …Notificationon the posting type, past-tense orChangednames (stateChangedNotification,boundingBoxCreatedNotification), with…UserInfoKeyconstants beside them. - Methods:
updateOnEveryFramefor per-frame hooks;switchToNextState/switchToPreviousStatefor the state machine;start…Timer/cancel…Timerpairs;did…for gesture handlers. - Files:
ViewController+Concern.swiftfor controller extensions;Type+Feature.swiftfor protocol files (PointCloud+CreateVisualization.swift).
Architecture takeaways
- Two nested state machines (app and scan) with validating setters make every transition, precondition, and side effect explicit and searchable.
- Tying object lifetime to state, and cleanup to
deinit, keeps teardown simple: assigningnilremoves nodes and restores the session configuration. NotificationCenterdecouples SceneKit nodes from the controller, but the globalViewController.instancereintroduces a dependency from models back to the controller.- Expensive ARKit work (
createReferenceObject, coverage ray tests) is rate-limited with timestamps, frame counters, and busy flags rather than queues. - The scene-based lifecycle is added by moving app-delegate forwarding (foreground, activation, URL opening) into
SceneDelegate, which looks up the root controller.
Source map
| Source file | Relevant symbols |
|---|---|
ScanningApp/Controllers/ViewController.swift |
ViewController, instance, internalState, scan, testRun, screenCenter, testObjectDetection(of:), createAndShareReferenceObject(), session(_:cameraDidChangeTrackingState:), renderer(_:updateAtTime:), readFile(_:), mergeIntoCurrentScan(referenceObject:from:), scanPercentageChanged(_:) |
ScanningApp/Controllers/ViewController+ApplicationState.swift |
State, state, scanningStateChanged(_:), switchToNextState() |
ScanningApp/Controllers/Scan.swift |
Scan, State, state, updateOnEveryFrame(_:), createReferenceObject(completionHandler:), applicationStateChanged(_:) |
ScanningApp/Controllers/TestRun.swift |
TestRun, setReferenceObject(_:screenshot:), successfulDetection(_:), startNoDetectionTimer() |
ScanningApp/Controllers/ShareScanViewController.swift |
ShareScanViewController |
ScanningApp/Controllers/SceneDelegate.swift |
SceneDelegate, scene(_:openURLContexts:), viewController |
ScanningApp/3D UI and Visualizations /ScannedObject.swift |
ScannedObject, boundingBox, ghostBoundingBox, origin |
ScanningApp/3D UI and Visualizations /BoundingBox.swift |
BoundingBox, notifications, updateCapturingProgress() |
ScanningApp/3D UI and Visualizations /Snapping.swift |
snapToHorizontalPlane() |
ScanningApp/3D UI and Visualizations /PointCloud+CreateVisualization.swift |
PointCloud, createVisualization(for:color:size:) |
ScanningApp/3D UI and Visualizations /ScannedPointCloud.swift |
ScannedPointCloud |
ScanningApp/3D UI and Visualizations /DetectedPointCloud.swift |
DetectedPointCloud |
ScanningApp/Utility Extensions/Utilities.swift |
ARReferenceObject.mergeInBackground(with:completion:) |
ScanningApp/Views/MessageLabel.swift |
Message, MessageLabel |
ScanningApp/Views/FlashlightButton.swift |
FlashlightButton |
ScanningApp/Info.plist |
CFBundleDocumentTypes, UIApplicationSceneManifest |
ScanningApp.xcodeproj/project.pbxproj |
SWIFT_VERSION, deployment target |