Sample CodeiOS, iPadOSReviewed 2026-11-01View on Apple Developer

Displaying a point cloud using scene depth

At a glance

Item Summary
Purpose Read LiDAR sceneDepth and smoothedSceneDepth from ARKit, optionally upscale depth with an MPS guided filter, and render the depth map as a colored, confidence-filtered point cloud plus depth, confidence, and coefficient previews.
App architecture A SwiftUI app whose views are MTKViews wrapped in UIViewRepresentable. A shared ARReceiver owns the ARSession and forwards frames to a weak ARDataReceiver delegate. ARProvider (that delegate) converts pixel buffers to Metal textures and runs the GPU upscaling pass. Each MTKView has a UIViewRepresentable coordinator subclass that draws one texture or the point cloud.
Main patterns Delegate callbacks (ARSessionDelegate, the local ARDataReceiver, MTKViewDelegate), @Binding values passed into render coordinators, and two static let shared instances (ARReceiver, EnvironmentVariables).
Project style Nine flat Swift files plus shaders.metal in pointCloudSample/. Files pair data (ARReceiver.swift, ARDataProvider.swift, EnvironmentVariables.swift) with one file per Metal view.
Execution model No Swift concurrency and no app-created queue. ARKit delegate callbacks drive ARProvider; MTKView delegate draw(in:) callbacks render; GPU work is submitted with MTLCommandBuffer.commit() without waiting.
State/event model ARSessionDelegate → ARDataReceiver.onNewARData → shared MetalTextureContent boxes that every coordinator reads at draw time. UI toggles write ARProvider properties whose didSet reprocesses the last frame.
Key frameworks/packages ARKit, Metal, MetalKit, MetalPerformanceShaders, Accelerate, SwiftUI. The project declares no Swift package.

Project structure

pointCloudSample.xcodeproj/            one app target, Swift 5, iOS 15.0 deployment target
pointCloudSample/
├── PointCloudDepthSample.swift        @main App + AppDelegate (supported orientations)
├── ARReceiver.swift                   ARDataReceiver protocol, ARData, ARReceiver (ARSession owner)
├── ARDataProvider.swift               MetalTextureContent, CVPixelBuffer.texture, ARProvider (MPS upscaling)
├── EnvironmentVariables.swift         singleton MTLDevice / command queue / default library
├── MetalViewSample.swift              MetalDepthView (portrait and landscape layouts), zoom modifier
├── MetalPointCloud.swift              CoordinatorPointCloud + MetalPointCloud representable
├── MetalTextureViewCoefs.swift        MTKCoordinator base class + coefficients view
├── MetalTextureViewDepth.swift        CoordinatorDepth + depth view
├── MetalTextureViewConfidence.swift   CoordinatorConfidence + confidence view
└── shaders.metal                      plane shaders, point-cloud vertex/fragment, YCbCr→RGBA kernel
scene-depth-point-cloud/               README images

Structure observations

  • MTKCoordinator, the base class for every render coordinator, is declared in MetalTextureViewCoefs.swift rather than in a file of its own (pointCloudSample/MetalTextureViewCoefs.swift:14).
  • The ARDataProvider.swift file declares ARProvider; the file name and type name differ (pointCloudSample/ARDataProvider.swift:41).
  • PointCloudDepthSample.swift contains a small AppDelegate, attached with @UIApplicationDelegateAdaptor, whose only job is to choose supported orientations (pointCloudSample/PointCloudDepthSample.swift:11, pointCloudSample/PointCloudDepthSample.swift:21).

Platform boundary

The DocC record lists iOS and iPadOS, and the target builds for iPhone and iPad (TARGETED_DEVICE_FAMILY = "1,2", pointCloudSample.xcodeproj/project.pbxproj:340) with an iOS 15.0 deployment target (pointCloudSample.xcodeproj/project.pbxproj:248). Rotation support is gated at run time: ARSession.viewRotationAngle and viewLayer are used only under #available(iOS 27.0, *), and earlier systems are limited to portrait (pointCloudSample/PointCloudDepthSample.swift:22).

Overall architecture

Reference code

pointCloudSample/ARReceiver.swift:31 — shared session owner and frame forwarding

final class ARReceiver: NSObject, ARSessionDelegate {
    static let shared = ARReceiver()
    var arData = ARData()
    var arSession = ARSession()
    weak var delegate: ARDataReceiver?
    
    // Configure and start the ARSession.
    override init() {
        super.init()
        arSession.delegate = self
        start()
    }
    // ...
    // Send required data from `ARFrame` to the delegate class via the `onNewARData` callback.
    func session(_ session: ARSession, didUpdate frame: ARFrame) {
        if(frame.sceneDepth != nil) && (frame.smoothedSceneDepth != nil) {
            arData.depthImage = frame.sceneDepth?.depthMap
            arData.depthSmoothImage = frame.smoothedSceneDepth?.depthMap
            arData.confidenceImage = frame.sceneDepth?.confidenceMap
            arData.confidenceSmoothImage = frame.smoothedSceneDepth?.confidenceMap
            arData.colorImage = frame.capturedImage
            arData.cameraIntrinsics = frame.camera.intrinsics
            arData.cameraResolution = frame.camera.imageResolution
            delegate?.onNewARData(arData: arData)
        }
    }
}

Interpretation

Observed: the pipeline has three layers that depend in one direction. ARReceiver knows ARKit and a protocol; ARProvider knows the receiver and Metal; views and coordinators know ARProvider and its texture boxes. The session starts the first time ARReceiver.shared is accessed, because init() calls start() (pointCloudSample/ARReceiver.swift:40).

Observed: MetalDepthView stores var arProvider: ARProvider = ARProvider() as a plain property, not @State (pointCloudSample/MetalViewSample.swift:53), so a new ARProvider is constructed whenever SwiftUI re-creates the view value, and each one sets itself as the receiver’s weak delegate (pointCloudSample/ARDataProvider.swift:146). Inference: because the receiver is a shared instance, repeated provider construction re-targets frame delivery instead of starting another ARSession.

Ownership and state

Ownership evidence

pointCloudSample/ARDataProvider.swift:58 — provider-owned texture boxes and working textures

final class ARProvider: ARDataReceiver {
    // ...
    let arReceiver = ARReceiver.shared
    var lastArData: ARData?
    let depthContent = MetalTextureContent()
    let confidenceContent = MetalTextureContent()
    let colorYContent = MetalTextureContent()
    let colorCbCrContent = MetalTextureContent()
    let upscaledCoef = MetalTextureContent()
    let downscaledRGB = MetalTextureContent()
    let upscaledConfidence = MetalTextureContent()
    
    let coefTexture: MTLTexture
    let destDepthTexture: MTLTexture
    let destConfTexture: MTLTexture
    let colorRGBTexture: MTLTexture
    let colorRGBTextureDownscaled: MTLTexture
    let colorRGBTextureDownscaledLowRes: MTLTexture
    // ...
}
Owner Object or state Relationship Mutation authority
ARReceiver (shared) ARSession, ARData Creates both as stored vars; one ARData instance is overwritten on every frame (pointCloudSample/ARReceiver.swift:32, pointCloudSample/ARReceiver.swift:67) ARReceiver session callback
ARReceiver delegate weak var delegate: ARDataReceiver? (pointCloudSample/ARReceiver.swift:34) Set by each ARProvider.init
MetalDepthView ARProvider Plain stored property initialized inline Re-created with the view value
ARProvider Seven MetalTextureContent boxes let references whose texture field changes per frame (pointCloudSample/ARDataProvider.swift:60) ARProvider.processLastArData()
ARProvider Six working MTLTextures Created once in init with fixed sizes (pointCloudSample/ARDataProvider.swift:129) GPU passes write them
EnvironmentVariables (shared) MTLDevice, MTLCommandQueue, MTLLibrary Created once in a private init (pointCloudSample/EnvironmentVariables.swift:19) Immutable lets
MTKCoordinator subclasses content, pipelineState, metalCommandQueue, weak mtkView Created by makeCoordinator(); setupView(mtkView:) stores the view and pipeline (pointCloudSample/MetalTextureViewCoefs.swift:25) Coordinator
CoordinatorPointCloud confSelection, scaleMovement @Binding to MetalDepthView’s @State (pointCloudSample/MetalPointCloud.swift:26) MetalDepthView controls

Observed: MetalTextureContent is a one-field reference box (pointCloudSample/ARDataProvider.swift:16). Coordinators keep the box, not the texture, so they see whatever texture ARProvider assigned most recently without any notification.

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
Frame callback ARSessionDelegate.session(_:didUpdate:) Copies depth, confidence, color buffers, and intrinsics into the shared ARData, then calls onNewARData synchronously pointCloudSample/ARReceiver.swift:65, pointCloudSample/ARReceiver.swift:74
Frame processing ARProvider.onNewARData → processLastArData() Creates Metal textures from pixel buffers through a CVMetalTextureCache and, when enabled, encodes the YCbCr kernel, MPS scale, and guided-filter passes in the same callback pointCloudSample/ARDataProvider.swift:154, pointCloudSample/ARDataProvider.swift:160
GPU submission cmdBuffer.commit() with no wait or completion handler depthContent.texture is switched to destDepthTexture immediately after commit, before the GPU pass is known to be finished pointCloudSample/ARDataProvider.swift:210, pointCloudSample/ARDataProvider.swift:213
Render loop MTKViewDelegate.draw(in:) with preferredFramesPerSecond = 60 and enableSetNeedsDisplay = false Each coordinator draws continuously from the current texture boxes pointCloudSample/MetalTextureViewCoefs.swift:27, pointCloudSample/MetalTextureViewCoefs.swift:32, pointCloudSample/MetalPointCloud.swift:124
UI-triggered reprocessing didSet { processLastArData() } on isToUpsampleDepth and isUseSmoothedDepthForUpsampling A toggle reprocesses the last frame immediately from the SwiftUI action pointCloudSample/ARDataProvider.swift:76, pointCloudSample/ARDataProvider.swift:83
Session to view layer arSession.viewLayer = windowLayer inside draw(in:) on iOS 27 The point-cloud coordinator hands the window’s layer to the session on every draw pointCloudSample/MetalPointCloud.swift:134, pointCloudSample/MetalPointCloud.swift:136
Shared-state safety None ARData, lastArData, and the texture boxes are written by the session callback and UI toggles and read by draw callbacks with no lock or queue pointCloudSample/ARDataProvider.swift:155, pointCloudSample/MetalPointCloud.swift:125

Reference code

pointCloudSample/ARDataProvider.swift:210 — commit without waiting, then swap the texture box

final class ARProvider: ARDataReceiver {
    // ...
    func processLastArData() {
        // ...
        if isToUpsampleDepth {
            guard let cmdBuffer = commandQueue.makeCommandBuffer() else { return }
            // ...
            guidedFilter?.encodeReconstruction(to: cmdBuffer, guidanceTexture: colorRGBTextureDownscaled,
                                               coefficientsTexture: coefTexture, destinationTexture: destDepthTexture)
            cmdBuffer.commit()
            
            // Override the original depth texture with the upscaled version.
            depthContent.texture = destDepthTexture
        }
    }
}

Not established by source: which queue ARKit uses for session(_:didUpdate:) (no delegateQueue is set) and which thread MTKView uses for draw(in:). Interpretation: every coordinator and the provider submit to the one command queue from EnvironmentVariables (pointCloudSample/ARDataProvider.swift:124, pointCloudSample/MetalTextureViewCoefs.swift:37), so GPU ordering follows commit order on that queue; CPU-side state has no synchronization.

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
Receiver to provider Local ARDataReceiver protocol with a weak delegate One-method push contract for each depth frame pointCloudSample/ARReceiver.swift:14
Provider to renderers Shared MetalTextureContent boxes read in draw(in:) Pull at render time; no observation pointCloudSample/MetalPointCloud.swift:125, pointCloudSample/MetalTextureViewCoefs.swift:109
UI to renderer @State in MetalDepthView passed as @Binding to representables and coordinators Confidence filter and camera-movement scale reach the point-cloud shader as vertex bytes pointCloudSample/MetalViewSample.swift:57, pointCloudSample/MetalPointCloud.swift:156
UI to provider Toggle onChange handlers write arProvider.isToUpsampleDepth / isUseSmoothedDepthForUpsampling; the pause button calls pause()/start() Provider settings and session lifetime pointCloudSample/MetalViewSample.swift:136, pointCloudSample/MetalViewSample.swift:145
Rotation ARReceiver.viewRotationAngle (iOS 27 session value, else 90) Rotates the point-cloud orientation matrix and selects texture-coordinate order for plane views pointCloudSample/ARReceiver.swift:57, pointCloudSample/MetalPointCloud.swift:71, pointCloudSample/MetalTextureViewCoefs.swift:90
Framework import ARKit, Combine, SwiftUI Receiver compilation dependencies; no Combine API is used in the file pointCloudSample/ARReceiver.swift:11, pointCloudSample/ARReceiver.swift:10
Framework import MetalPerformanceShaders, Accelerate Provider: guided filter and bilinear scale pointCloudSample/ARDataProvider.swift:13, pointCloudSample/ARDataProvider.swift:12
Framework import MetalKit, Metal Render coordinators pointCloudSample/MetalPointCloud.swift:10, pointCloudSample/MetalPointCloud.swift:11
Package declaration None The project file declares no Swift package pointCloudSample.xcodeproj/project.pbxproj:339

Combine is imported in two files but no publisher, subscriber, receive(on:), or subscribe(on:) appears in the source.

Class and protocol design

Reference code

pointCloudSample/MetalTextureViewCoefs.swift:41 — base coordinator with an overridable pipeline hook

class MTKCoordinator: NSObject, MTKViewDelegate {
    var content: MetalTextureContent
    weak var mtkView: MTKView!
    var pipelineState: MTLRenderPipelineState!
    var metalCommandQueue: MTLCommandQueue!
    // ...
    func prepareFunctions() {
        guard let metalDevice = mtkView.device else { fatalError("Expected a Metal device.") }
        do {
            let library = EnvironmentVariables.shared.metalLibrary
            let pipelineDescriptor = MTLRenderPipelineDescriptor()
            pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
            pipelineDescriptor.depthAttachmentPixelFormat = .depth32Float
            pipelineDescriptor.vertexFunction = library.makeFunction(name: "planeVertexShader")
            pipelineDescriptor.fragmentFunction = library.makeFunction(name: "planeFragmentShaderCoefs")
            pipelineDescriptor.vertexDescriptor = createPlaneMetalVertexDescriptor()
            pipelineState = try metalDevice.makeRenderPipelineState(descriptor: pipelineDescriptor)
        } catch {
            print("Unexpected error: \(error).")
        }
    }
    // ...
}
Type Responsibility Depends on or conforms to
ARReceiver Owns and runs the ARSession; packages each depth frame into ARData; exposes viewRotationAngle NSObject, ARSessionDelegate
ARProvider Pixel buffer → texture conversion; optional guided-filter upscaling ARDataReceiver, MPS
EnvironmentVariables One device, queue, and default library for the app Metal
MTKCoordinator Base MTKViewDelegate: view setup, plane pipeline, textured-quad draw MTKViewDelegate
CoordinatorDepth, CoordinatorConfidence Override prepareFunctions() to choose a fragment shader MTKCoordinator
CoordinatorPointCloud Overrides prepareFunctions() and draw(in:); builds the projection-model-view matrix and draws one point per depth pixel MTKCoordinator, ARProvider
MetalPointCloud, MetalTextureView* UIViewRepresentable wrappers that create the MTKView and coordinator SwiftUI

Observed: variation among render views is by subclass override of prepareFunctions() (and draw(in:) for the point cloud); setupView(mtkView:) calls prepareFunctions() at the end (pointCloudSample/MetalTextureViewCoefs.swift:38). The only local protocol is the one-method ARDataReceiver.

Access control

Symbol Access Verified effect Likely rationale
EnvironmentVariables.init (pointCloudSample/EnvironmentVariables.swift:19) private Only shared can exist Enforces one Metal device and queue.
ARReceiver.init (pointCloudSample/ARReceiver.swift:37) implicit internal override Other code could create a second receiver and session; only shared is used No type-level single-instance guarantee.
ARProvider.isToUpsampleDepth, isUseSmoothedDepthForUpsampling (pointCloudSample/ARDataProvider.swift:76, pointCloudSample/ARDataProvider.swift:83) public in an app target Same effective reach as internal; nothing imports this module Inference: marks the provider’s intended settings.
ARReceiver.arSession, arData, delegate (pointCloudSample/ARReceiver.swift:32) implicit internal var CoordinatorPointCloud reaches arReceiver.arSession directly to set viewLayer The session is not encapsulated behind the receiver.
MetalDepthView.selectedConfidence, scaleMovement (pointCloudSample/MetalViewSample.swift:57, pointCloudSample/MetalViewSample.swift:62) private @State Children receive bindings, not the storage Standard SwiftUI ownership.
landscapeLayout(size:), controls, textureStrip(width:height:) (pointCloudSample/MetalViewSample.swift:97) private Layout helpers are internal to the root view Inference: keeps the two layouts sharing one set of subviews.

Reference code

pointCloudSample/EnvironmentVariables.swift:12 — singleton with a private initializer

class EnvironmentVariables {
    static let shared: EnvironmentVariables = {
       let instance = EnvironmentVariables()
        return instance
    }()
    let metalDevice: MTLDevice
    let metalCommandQueue: MTLCommandQueue
    let metalLibrary: MTLLibrary
    private init() {
        // ...
    }
}

Logic ownership and placement

Logic Owning type or file Placement rationale
Capability check ARReceiver.start() and MetalDepthView.body Both check supportsFrameSemantics([.sceneDepth, .smoothedSceneDepth]); the view shows a message instead of the UI when unsupported (pointCloudSample/ARReceiver.swift:45, pointCloudSample/MetalViewSample.swift:67).
Depth upscaling ARProvider.processLastArData() YCbCr→RGBA kernel, two bilinear downscales, confidence upscale, guided-filter regression and reconstruction in one command buffer (pointCloudSample/ARDataProvider.swift:174).
Unprojection and confidence filter pointCloudVertexShader Converts each depth pixel to camera space with the intrinsics and zeroes depth below the selected confidence (pointCloudSample/shaders.metal:118, pointCloudSample/shaders.metal:144, pointCloudSample/shaders.metal:149).
Intrinsics scaling CoordinatorPointCloud.draw(in:) Rescales full-resolution intrinsics to the depth texture’s resolution before upload (pointCloudSample/MetalPointCloud.swift:144).
Rotation-aware output ARReceiver.viewRotationAngle, calcCurrentPMVMatrix, MTKCoordinator.draw(in:) One angle source; the point cloud rotates its orientation matrix, and plane views pick one of four texture-coordinate tables (pointCloudSample/MetalPointCloud.swift:65, pointCloudSample/MetalTextureViewCoefs.swift:90).
Supported orientations AppDelegate.application(_:supportedInterfaceOrientationsFor:) .all on iOS 27, otherwise .portrait (pointCloudSample/PointCloudDepthSample.swift:21).
Layout choice MetalDepthView.body GeometryReader picks landscapeLayout(size:) when wider than tall (pointCloudSample/MetalViewSample.swift:72).

Design patterns

Pattern Source evidence Purpose or tradeoff
Delegate or data-source callbacks arSession.delegate = self in ARReceiver; arReceiver.delegate = self in ARProvider; mtkView.delegate = context.coordinator (pointCloudSample/ARReceiver.swift:39, pointCloudSample/ARDataProvider.swift:146, pointCloudSample/MetalPointCloud.swift:174) Frames are pushed from ARKit to the provider, and rendering is pulled by each view’s draw callback.
Binding-based state propagation @Binding var confSelection / scaleMovement in CoordinatorPointCloud, initialized from the representable’s bindings (pointCloudSample/MetalPointCloud.swift:26, pointCloudSample/MetalPointCloud.swift:39) The renderer reads the latest control values each frame without the view rebuilding it.
Singleton static let shared on ARReceiver and EnvironmentVariables (pointCloudSample/ARReceiver.swift:31, pointCloudSample/EnvironmentVariables.swift:12). Only EnvironmentVariables enforces one instance with private init() (pointCloudSample/EnvironmentVariables.swift:19); ARReceiver keeps an implicitly internal override init() (pointCloudSample/ARReceiver.swift:37), so its uniqueness is a convention One session and one Metal device for every view; dependencies are reached globally rather than injected.

Removed labels: “Coordinator” (the types are SwiftUI UIViewRepresentable coordinators acting as MTKViewDelegates, not a navigation or flow coordinator) and “Protocol-oriented abstraction” (the single local protocol is a one-conformer delegate contract, covered by the delegate row).

Naming conventions

  • Types: …Receiver for the ARKit-facing owner, …Provider for the texture producer, Coordinator… / MTKCoordinator for UIViewRepresentable coordinators, Metal… for the SwiftUI wrappers, …Content for the texture box.
  • Methods: onNewARData(arData:) names the callback event; processLastArData() and calcCurrentPMVMatrix(viewSize:) describe the computation; prepareFunctions() is the override hook for pipeline setup.
  • Properties: Booleans use is… (isToUpsampleDepth, isUseSmoothedDepthForUpsampling, isArPaused).
  • Files: mostly one feature per file; MetalTextureViewCoefs.swift also holds the shared MTKCoordinator base, and ARDataProvider.swift holds ARProvider.

Architecture takeaways

  • Separate the session owner (ARReceiver) from the GPU consumer (ARProvider) with a one-method delegate; the consumer can be replaced without touching ARKit code.
  • Reference boxes (MetalTextureContent) let many renderers pick up the latest texture at draw time with no observation machinery.
  • A single rotation source (viewRotationAngle) feeds both the 3D projection and the 2D texture views; OS-version gating keeps older systems on portrait.
  • Making the receiver a shared instance prevents duplicate sessions when SwiftUI re-creates the root view, but the provider itself is still re-created because it is not @State.
  • CPU-side frame state and texture swaps are unsynchronized, and the upscaled texture is published before its command buffer completes; treat this as sample-level simplicity.

Source map

Source file Relevant symbols
pointCloudSample/PointCloudDepthSample.swift PointCloudDepthSample, AppDelegate, application(_:supportedInterfaceOrientationsFor:)
pointCloudSample/ARReceiver.swift ARDataReceiver, ARData, ARReceiver, shared, start(), viewRotationAngle, session(_:didUpdate:)
pointCloudSample/ARDataProvider.swift MetalTextureContent, CVPixelBuffer.texture(withFormat:planeIndex:addToCache:), ARProvider, onNewARData(arData:), processLastArData()
pointCloudSample/EnvironmentVariables.swift EnvironmentVariables, shared
pointCloudSample/MetalViewSample.swift MetalDepthView, landscapeLayout(size:), controls, textureStrip(width:height:), Texture, zoomOnTapModifier
pointCloudSample/MetalPointCloud.swift CoordinatorPointCloud, calcCurrentPMVMatrix(viewSize:), draw(in:), MetalPointCloud
pointCloudSample/MetalTextureViewCoefs.swift MTKCoordinator, setupView(mtkView:), prepareFunctions(), draw(in:), MetalTextureViewCoefs
pointCloudSample/MetalTextureViewDepth.swift CoordinatorDepth, MetalTextureViewDepth
pointCloudSample/MetalTextureViewConfidence.swift CoordinatorConfidence, MetalTextureViewConfidence
pointCloudSample/shaders.metal pointCloudVertexShader, pointCloudFragmentShader, planeVertexShader, convertYCbCrToRGBA
pointCloudSample.xcodeproj/project.pbxproj TARGETED_DEVICE_FAMILY, IPHONEOS_DEPLOYMENT_TARGET, SWIFT_VERSION